1
votes

I have a project in Azure Devops with underlying repository as git. I have a automatically created database documentation which is stored in the project repository. To keep this documentation up-to date I want to schedule an application to push the generated documentation to azure on daily basis.

Basically, check out the file, write new content & check-in. Can we do this using Azure devops rest APIs? Is there any example code that I can follow?

2
is it Git or TFVC? (you mentioned git and after that, you mentioned "check-in" that it's TFVC) - Shayki Abramczyk
@ShaykiAbramczyk yes, its Git. - Jay
so you can perform git commands in your console app. - Shayki Abramczyk
@ShaykiAbramczyk are there any examples that shows how to authenticate & use .net libraries to do sync my changes to Git - Jay
Hi Jay, any update on this, have you figure it out? Just checking to see if the information provided was helpful. If my reply helped or gave a right direction. Appreciate for marking it as an answer which will also help others in the community. - PatrickLu-MSFT

2 Answers

0
votes

You can have a scheduled build using Azure Pipelines, and in the build definition you define a Powershell script that run git related git commands as ShaykiAbramczyk suggested.

Need pay attention with below if you want to run Git commands in a script:

  • Grant version control permissions to the build service
  • Allow scripts to access the system token
  • Merge a feature branch to master

More details please refer our official doc here-- Run Git commands in a script

Script snippet:

#Config Set
git config user.email "$(Build.RequestedForEmail)"
git config  user.name "$(Build.RequestedFor)"

#Push new Branch
git -c http.extraheader="AUTHORIZATION: bearer $(System.AccessToken)" push origin master:refs/heads/my-branch

#Other command
......
0
votes

This is how I have implemented the a solution to check-in content in Azure Devops Git Repo.

Below is the generic class & caller method.

class AzureDevops
{
    private readonly Uri uri;
    private readonly string personalAccessToken;

    public AzureDevops(string orgName, string personalAccessToken)
    {
        this.uri = new Uri("https://dev.azure.com/" + orgName);
        this.personalAccessToken = personalAccessToken;
    }

    public T Post<T>(dynamic body, string path)
    {
        if (body == null)
            throw new ArgumentNullException("body");

        if (path == null)
            throw new ArgumentNullException("path");

        T output = default(T);
        using (var client = new HttpClient())
        {
            client.BaseAddress = uri;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", personalAccessToken);

            string serl_body = JsonConvert.SerializeObject(body);

            var content = new StringContent(serl_body, Encoding.UTF8, "application/json");
            using (HttpResponseMessage response = client.PostAsync(path, content).Result)
            {
                response.EnsureSuccessStatusCode();
                output = response.Content.ReadAsAsync<T>().Result;
            }
        }
        return output;
    }

    public T Get<T>(string path)
    {
        if (path == null)
            throw new ArgumentNullException("path");

        T output = default(T);
        using (var client = new HttpClient())
        {
            client.BaseAddress = uri;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", personalAccessToken);

            HttpResponseMessage response = client.GetAsync(path).Result;

            if (response.IsSuccessStatusCode)
                output = response.Content.ReadAsAsync<T>().Result;
            else
                throw new ApplicationException(string.Format("Response message is not OK. Issues in action: {0}", path));
        }

        return output;
    }
}


public class Main
    {
        AzureDevops azureDevops = new AzureDevops("OrgName", "PAT");

        private void AddNewContent()
        {
            ListOfRefResponse.Root listOfRefResponse = azureDevops.Get<ListOfRefResponse.Root>(string.Format("{0}/_apis/git/repositories/{1}/refs? api-version=6.0-preview.1&filter=heads/master", "projectId", "repositoryId"));
            ArrayList contentArray = new ArrayList();
            contentArray.Add(new ChangesBO
            {
                changeType = "add",
                item = new ChangeItemBO { path = string.Concat("/", Constants.BaseAzureFolder, "/", "projedctName" + "/" + "filename.md") },
                newContent = new ChangeContent { content = "new text content", contentType = "rawtext" }
            });

            dynamic body = new
            {
                refUpdates = new[] { new { name = Constants.Branch, oldObjectId = listOfRefResponse.value.First().objectId } },
                commits = new[] {
                                    new {
                                        comment = Constants.AppKeysUpdateComment,
                                        changes = contentArray.ToArray()
                                    }}
            };
            CommitSuccessBO.Root commitSuccess = azureDevops.Post<CommitSuccessBO.Root>(body, string.Format("_apis/git/repositories/{0}/pushes?api-version=5.0", "RepositoryId"));

        }
    }