[Azure] C# 如何控制 Azure DevOps - 上面的專案 取得檔案內容跟所有 Repository資訊

2020-12-09

最近一些需要,要直接控制 放在 https://dev.azure.com/ 上面的東西,所以大概就筆記一下,敘述一下,這邊我是用 .net Core 3.1 寫的,然後是以理解並且分享給同事使用為主,所以沒有封裝…




Step1. 申請 https://dev.azure.com/ 帳號

Step2. 開一個專案

Step3. 申請自己的的 Personal Access Tokens,請注意最多只有 90 天,所以如果你有 production 要記得要做更換機制。


Step4. 安裝  Microsoft.TeamFoundationServer.Client

網址:  https://www.nuget.org/packages/Microsoft.TeamFoundationServer.Client/16.153.0   


 

Step5. 接下來就是 Code 的部分,因為 我看到的官方 sample 封裝的有點複雜,所以我盡量簡單化動作,所以如果你想知道更多比較詳細的話可以看一下官方範例,接下來我都寫在註解裡。
    

取得所有 Repository :

//Step2 就會拿到網址
var orgUrl = new Uri("https://dev.azure.com/yourporjectname");
//Step3 就會拿到 Personal Access Token
//
var personalAccessToken = "your_personal_access_token";
// Create a connection
var connection = new VssConnection(orgUrl, new VssBasicCredential(string.Empty, personalAccessToken));
var githttpClient = connection.GetClient<GitHttpClient>();
var repos = githttpClient.GetRepositoriesAsync().Result;
if (repos != null)
{
foreach (var repo in repos)
{
// Repo Id 很重要,之後文章會用到
Content += "==>" + repo.Name + "," + repo.Id + "<br>";
}
}
//Result
//==>HubStorage,723e2ea7-11f8-4693-ad59-30664a4360af
//==>AMNOD,663d14ea-6b23-4c1f-a083-ec38e2812320


取得 Repositroy 下的資訊

//Step2 就會拿到網址
var orgUrl = new Uri("https://dev.azure.com/yourporjectname");
//Step3 就會拿到 Personal Access Token
var personalAccessToken = "your_personal_access_token";
// Create a connection
var connection = new VssConnection(orgUrl, new VssBasicCredential(string.Empty, personalAccessToken));
var githttpClient = connection.GetClient<GitHttpClient>();
var repos = githttpClient.GetRepositoriesAsync().Result;
if (repos != null)
{
foreach (var repo in repos)
{
// Repo Id 很重要,之後文章會用到
Content += "==>" + repo.Name + "," + repo.Id + "<br>";
var contents = githttpClient.GetItemsAsync(repo.Id, "/", VersionControlRecursionType.OneLevel, true, true, true, true).Result;
foreach (var con in contents)
{
//如果不是 Folder
if (!con.IsFolder)
{
Content += "[File] "+" OBJECTID : " + con.ObjectId + " , PATH:" + con.Path + "<br>";
}
}
}
}
//Result
//==> HubStorage,723e2ea7-11f8-4693-ad59-30664a4360af
//[File] OBJECTID: 34c428e8aba3851661a6eca56f517a4c038e55ad , PATH:/ 1599303643 - 9940.jpg
//[File] OBJECTID: 0ca446aab9d09eac8625b53e3df8da661976c458 , PATH:/ README.md
//[File] OBJECTID: e836475870da67f3c72f64777c6e0f37d9f4c87b , PATH:/ jquery - 1.12.4.min.js
//==> AMNOD,663d14ea-6b23-4c1f-a083-ec38e2812320
//[File] OBJECTID: fe978ae31dc613140c2b94a1205292adb964b6ab , PATH:/ 1325c6c7bc04f2861b95b2058a26a47a.jpg
//[File] OBJECTID: 0ca446aab9d09eac8625b53e3df8da661976c458 , PATH:/ README.md
//[File] OBJECTID: e836475870da67f3c72f64777c6e0f37d9f4c87b , PATH:/ jquery - 1.12.4.min.js
//[File] OBJECTID: 96fe003633a2b87ecebd8fd2c4793f5bfb0e1810 , PATH:/ t1.7z
//[File] OBJECTID: 74b2368510ca983c873db9cb208d5e8e7a740e4d , PATH:/ xxx.jpg



reference:
https://github.com/microsoft/azure-devops-dotnet-samples


當麻許的超技八 2014 | Donma Hsu Design.