Add new Files and Folders to Azure Git Repository with Azure DevOps REST API - azure-devops

How to Add new Files and Folders to Azure Git Repository with Azure DevOps REST API?
I want to add some static files to my repository using Azure DevOps REST APIs.
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories?view=azure-devops-rest-5.1
Is there any option available via REST API?.
or anyother automated way available, either CICD or through c#?

I found the answer, we can use the Git Push REST API uri
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-5.1
Follow below steps in your C# code
call GetRef REST https://dev.azure.com/{0}/{1}/_apis/git/repositories/{2}/refs{3}
this should return the object of your repository branch which you can use to push your changes
Next, call Push REST API to create folder or file into your repository
https://dev.azure.com/{0}/{1}/_apis/git/repositories/{2}/pushes{3}
var changes = new List<ChangeToAdd>();
//Add Files
//pnp_structure.yml
var jsonContent = File.ReadAllText(#"./static-files/somejsonfile.json");
ChangeToAdd changeJson = new ChangeToAdd()
{
changeType = "add",
item = new ItemBase() { path = string.Concat(path, "/[your-folder-name]/somejsonfile.json") },
newContent = new Newcontent()
{
contentType = "rawtext",
content = jsonContent
}
};
changes.Add(changeJson);
CommitToAdd commit = new CommitToAdd();
commit.comment = "commit from code";
commit.changes = changes.ToArray();
var content = new List<CommitToAdd>() { commit };
var request = new
{
refUpdates = refs,
commits = content
};
var personalaccesstoken = _configuration["azure-devOps-configuration-token"];
var authorization = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccesstoken)));
_logger.LogInformation($"[HTTP REQUEST] make a http call with uri: {uri} ");
//here I making http client call
// https://dev.azure.com/{orgnizationName}/{projectName}/_apis/git/repositories/{repositoryId}/pushes{?api-version}
var result = _httpClient.SendHttpWebRequest(uri, method, data, authorization);

Related

Service Now REST API script for listening from DevOps web hooks

I am wondering how connect between DevOps Boards Incidents and Tasks (web hooks used) to ServiceNow. The requirement is Service Now will need to listen every time there is an update to Azure DevOps boards incidents or Tasks.
I have created a Scripted REST API at Service Now with the following Example script:
`(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var body = request.body.data;
var eventType = request.headers['auth_token'];
var workItem = body.resource;
var title = workItem.fields['System.Title'];
var description = workItem.fields['System.Description'];
var state = workItem.fields['System.State'];
var priority = workItem.fields['System.priority'];
if(eventType == 'workitem.created') {
title = workItem.fields['System.Title'];
description = workItem.fields['System.Description'];
state = workItem.fields['System.State'];
} else if(eventType == 'workitem.updated') {
title = workItem.fields['System.Title'];
description = workItem.fields['System.Description'];
state = workItem.fields['System.State'];
}
response.setStatus(200);
})(request, response);`
Now, Just wondering how to invoke this API end point when there is an update.
If you are on the Scripted REST Resource form in ServiceNow, then you should see a "Explore REST API" link at the bottom of the page. If you click that link it will take you page that you can use to test your API. Right below the "Send" button there should be links to generate code samples to call your API.

Using the Azure Devops Server client library, how do you create the master branch in a new repository?

Using the client API I can create a new repository, but it hasn't been initialized and so doesn't contain a master branch.
public void CreateRepository(string name)
{
TeamProjectReference tpr = new TeamProjectReference();
tpr.Name = "AppDev";
tpr.Id = new Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
GitRepositoryCreateOptions grco = new GitRepositoryCreateOptions();
grco.ProjectReference = tpr;
grco.Name = name;
newRepo = gitClient.CreateRepositoryAsync(grco).Result;
}
I can't figure out how to create a master branch. The methods to create branches all require a parent branch to create from. How do I create master using the client libraries?
How do I create master using the client libraries?
Apart from creating the empty repo, you also need to initialize it with initial commit. Hint from this rest api Initial commit, and also from this official document. You can follow my working sample below:
static void Main(string[] args)
{
//Connect to Azure Devops Service and create an empty git repo.
ConnectToAzureDevopsService(OrgUrl, PAT);
TeamProjectReference teamProjectReference = new TeamProjectReference();
teamProjectReference.Name = "MyProjectName";
teamProjectReference.Id = new Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
GitRepositoryCreateOptions gitRepositoryCreateOptions = new GitRepositoryCreateOptions();
gitRepositoryCreateOptions.ProjectReference = teamProjectReference;
gitRepositoryCreateOptions.Name = "MyTestRepo";
GitRepository gitRepo = GitClient.CreateRepositoryAsync(gitRepositoryCreateOptions).Result;
//You need extra steps below to initialize your newly created repo.
//Craft the branch and commit that we'll push.
GitRefUpdate newBranch = new GitRefUpdate()
{
RepositoryId = gitRepo.Id,
Name = $"refs/heads/master",
OldObjectId = "0000000000000000000000000000000000000000",
};
string newFileName = $"README.md";
GitCommitRef newCommit = new GitCommitRef()
{
Comment = "Initial the repo with custom README.md",
Changes = new GitChange[]
{
new GitChange()
{
ChangeType = VersionControlChangeType.Add,
Item = new GitItem() { Path = $"/{newFileName}" },
NewContent = new ItemContent()
{
Content = "# Thank you for using VSTS!",
ContentType = ItemContentType.RawText,
},
}
},
};
//Start initializing the repo via creating the push.
GitPush InitialPush = GitClient.CreatePushAsync(new GitPush()
{
RefUpdates = new GitRefUpdate[] { newBranch },
Commits = new GitCommitRef[] { newCommit },
}, gitRepo.Id).Result;
//Let me know if it succeeds.
Console.WriteLine("Done");
}
The result:
Let me know if it helps.

How to create a GitHub tag using the octokit.net API

I am creating Release using the github's octokit API. Create release method creates release and also create corresponding tag.
I also want to create additional tag. So using the example here i am trying to create a tag. I am assuming when GitHubClient creates release it has to commit changes as well. However i am not sure how do get SHA of the release commit so that i can use that SHA to create additional tag?
Here is my current code:
var client = new GitHubClient(new ProductHeaderValue(Constants.ProductHeader));
var tokenAuth = new Credentials(options.AccessToken);
client.Credentials = tokenAuth;
var newRelease = new NewRelease(options.Version)
{
Name = options.Version,
Body = "This is test release",
Draft = false,
Prerelease = false
};
var result = await client.Repository.Release.Create(Constants.Owner, repositoryName, newRelease);
??? How do i get `sha` here for the release
var tag = "AdditionalTag"
var newTag = new NewTag()
{
Message = tag,
Tag = tag,
Type = TaggedType.Tag,
Object = ???
};
await client.Git.Tag.Create(Constants.Owner, repositoryName, newTag);
This throws the exception "Validation Failed", because I am not setting the SHA.
Questions
How do I calculate the SHA of the git object?
The octokit also has TagsClient class. What is the difference between TagsClient and GitHubClient?

How do you get a list of all project iterations using the Azure DevOps Services .NET SDK?

I'd like to get a list of all the iterations for a given project in a Azure DevOps repository, using the .NET API.
Is there any example of how to do this? The current documentation (https://learn.microsoft.com/en-us/dotnet/api/microsoft.teamfoundation.work.webapi.workhttpclientbase.getteamiterationsasync?view=azure-devops-dotnet) is pretty thin.
Below is a working example of how to achieve this.
You need to reference Microsoft.TeamFoundation.Work.WebApi.
public async Task<List<TeamSettingsIteration>> GetProjectIterations(string serverUrl, string projectName)
{
var uri = new Uri(serverUrl);
var creds = new VssClientCredentials(new WindowsCredential(true), new VssFederatedCredential(true), CredentialPromptType.PromptIfNeeded);
var azureDevopsConnection = new VssConnection(uri, creds);
await azureDevopsConnection.ConnectAsync();
WorkHttpClient azureDevOpsWorkHttpClient = azureDevopsConnection.GetClient<WorkHttpClient>();
TeamContext teamContext = new TeamContext(projectName);
List<TeamSettingsIteration> results= await azureDevOpsWorkHttpClient.GetTeamIterationsAsync(teamContext);
return results;
}

How to get/identity the Azure DevOps Server base URL from the extension?

I’m developing an extension for both Azure DevOps Services and Server but I’m struggling to get the base URL for the Azure DevOps Server version once I have some navigations to the target resource, such as: Pull Request details.
Is there any way to get it? For instance:
Azure DevOps Services
dev.azure.com/organization
organization.visualstudio.com
Azure DevOps Server
serverName/{?}
serverName:8080/{tfs}/{?}
I am using this code:
Use document.referrer from the plugin as a URL source.
Locate the project name and extract the part of the URL before the project name.
const url = document.referrer;
// how to detect base Url: get projectName and find 'ProjectName/_'
// http://tfs2017-test:8080/tfs/Org/MyProject/_apps/hub/...
const projectService = await SDK.getService<IProjectPageService>(CommonServiceIds.ProjectPageService);
const project = await projectService.getProject();
if (!project) {
throw new Error("Cannot get project.")
}
const findStr = `${project.name}/_`;
const index = url.indexOf(findStr);
if (index < 0) {
throw new Error(`URL '${url}' does not contain '${findStr}' substring`);
}
// extract from url without '_'
this._baseUrl = url.substring(0, index + findStr.length - 1);
Edit 04.05.2021:
Because document.referrer is not working good for some browsers, I am using now more "DevOps way":
// https://github.com/microsoft/azure-devops-extension-sdk/issues/28
this._locationService = await SDK.getService<ILocationService>(CommonServiceIds.LocationService);
const hostBaseUrl = await this._locationService.getResourceAreaLocation(
CoreRestClient.RESOURCE_AREA_ID
);
console.log(`hostBaseUrl: ${hostBaseUrl}`);
const projectService = await SDK.getService<IProjectPageService>(CommonServiceIds.ProjectPageService);
const project = await projectService.getProject();
if (!project) {
throw new Error("Cannot get project.")
}
this._baseUrl = `${hostBaseUrl}${project.name}/`;
console.log(`baseUrl: ${this._baseUrl}`);