Reputation: 25
I'm creating an Azure function for a renaming a file in an Azure DevOps Repository but need the 'oldObjectId' which is the last 'commitId' from the Get Commits API call i.e.
I'm testing the code locally and through PostMan but don't know what to include in the body of the request as there is nothing specified for that.
I'm quiet new to C# and Azure functions and don't know how to properly implement this in my own project. I would really appreciate it if someone could guide me into the right direction.
I am using Visual Studio with .NET Core 3.0 and Azure Functions.
Here is the code so far:
using System;
using System.IO;
using System.Net;
using Microsoft.Azure.WebJobs;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace FileRename
{
public static class Rename
{
private static bool flgFileRenamed;
private static bool flgRepoCommit;
[FunctionName("RenameFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
HttpRequest req, ILogger log)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic body = JsonConvert.DeserializeObject(requestBody);
string devOpsUsername = Environment.GetEnvironmentVariable("DevOpsUsername", EnvironmentVariableTarget.Process);
string devOpsPAT = Environment.GetEnvironmentVariable("DevOpsPAT", EnvironmentVariableTarget.Process);
string serviceEndpointId = Environment.GetEnvironmentVariable("ServiceEndpointId", EnvironmentVariableTarget.Process);
string sourceRepoUrl = Environment.GetEnvironmentVariable("SourceRepoUrl", EnvironmentVariableTarget.Process);
string baseTargetUri = Environment.GetEnvironmentVariable("BaseTargetUri", EnvironmentVariableTarget.Process);
string RepoId = "1bfc406f-5dd7-44e1-b5fc-bd14829fbb12";
using HttpClient client = new HttpClient();
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", devOpsUsername, devOpsPAT))));
// Get Latest Commits to the Repository
var latestCommittsRequestBody = new
{
};
//GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits?searchCriteria.$top=1&api-version=6.1-preview.1
var latestCommittsUrl = baseTargetUri + "git/repositories/" + RepoId + "/commits?searchCriteria.$top=1&api-version=6.1-preview.1";
HttpRequestMessage latestCommittsRequest = new HttpRequestMessage(HttpMethod.Get, latestCommittsUrl);
latestCommittsRequest.Content = new StringContent(JsonConvert.SerializeObject(latestCommittsRequestBody), Encoding.UTF8, "application/json");
//var CommitId = body.value.commitId;
// latest Commits Response
using HttpResponseMessage latestCommittsResponse = await client.SendAsync(latestCommittsRequest);
{
if (latestCommittsResponse.StatusCode == HttpStatusCode.Created)
{
flgRepoCommit = true;
}
else
{
flgRepoCommit = false;
}
}
// Rename a File
var renameFileRequestBody = new
{
refUpdates = new
{
name = "refs/heads/master",
oldObjectId = body.value.commitId,
},
commits = new
{
comment = "Renaming ABC.txt to XYZ.txt",
changes = new
{
changeType = "rename",
sourceServerItem = "/ABC.txt",
item = new
{
path = "/XYZ.txt",
}
},
}
};
var renameFileUrl = baseTargetUri + "git/repositories/" + RepoId + "/pushes?api-version=6.0-preview.1";
HttpRequestMessage renameFileRequest = new HttpRequestMessage(HttpMethod.Post, renameFileUrl);
renameFileRequest.Content = new StringContent(JsonConvert.SerializeObject(renameFileRequestBody), Encoding.UTF8, "application/json");
using HttpResponseMessage renameFileResponse = await client.SendAsync(renameFileRequest);
{
if (renameFileResponse.StatusCode == HttpStatusCode.Created)
{
flgFileRenamed = true;
}
else
{
flgFileRenamed = false;
}
}
// Checks if file is renamed or not
if (flgFileRenamed == true)
{
return new OkObjectResult("File is renamed successfully!"); // 200
}
else
{
return new BadRequestObjectResult("File could not be renamed successfully."); // 400
}
}
}
}
}
Upvotes: 1
Views: 535
Reputation: 23111
Regarding the issue, please refer to the following code
Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits?api-version=6.0-preview.1&searchCriteria.$top=1");
string content = string.Empty;
using (HttpResponseMessage response = await Client.SendAsync(requestMessage))
{
if (!response.IsSuccessStatusCode)
{
try
{
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex)
{
throw ex;
}
}
var res = await response.Content.ReadAsStringAsync();
JObject resObj = JsonConvert.DeserializeObject<JObject>(res);
var commitId = (resObj["value"].Last).Value<string>("commitId");
log.LogInformation("commitId: "+ commitId);
var renameFileRequestBody = new
{
refUpdates = new Object[] {
new {
name = "refs/heads/master",
oldObjectId = commitId,
},
},
commits =new Object[] {
new{
comment = "Renaming test.txt to mytest.txt",
changes = new Object[]{
new{
changeType = "rename",
sourceServerItem = "/test.txt",
item = new
{
path = "/mytest.txt",
}
},
}
}
}
};
HttpRequestMessage renameFileRequest = new HttpRequestMessage(HttpMethod.Post, "https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pushes?api-version=6.1-preview.2");
renameFileRequest.Content = new StringContent(JsonConvert.SerializeObject(renameFileRequestBody), Encoding.UTF8, "application/json");
using (HttpResponseMessage renameFileResponse=await Client.SendAsync(renameFileRequest))
{
if (renameFileResponse.StatusCode == HttpStatusCode.Created)
{
return new OkObjectResult("File is renamed successfully!");
}
else
{
return new BadRequestObjectResult("File could not be renamed successfully."); // 400
}
}
Upvotes: 1