/// <summary> /// This method is used to execute a Dev Ops work item query and get the number of bugs for a given query. /// If result is not found for a query, it will return 0. /// Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/wiql/query%20by%20wiql?view=azure-devops-rest-5.1 /// </summary> /// <param name="bugQuery">Bug query object representing vsts shared queries</param> /// <returns>Number of bugs output by query</returns> public async Task <int> GetBugsCountAsync(BugQuery bugQuery) { // TODO: need to think about how to handle unexpected exception during REST API call string requestPath = string.Format(WorkItemPathSegmentFormat, DevOpsAccessSetting.BaseUrl, this.accessSetting.Organization, this.accessSetting.Project, this.accessSetting.Team); IFlurlRequest workItemQueryRequest = ((Url)requestPath) .WithBasicAuth(string.Empty, this.accessSetting.PersonalAccessToken) .SetQueryParam("api-version", "5.1"); JObject result; try { IFlurlResponse response = await workItemQueryRequest .PostJsonAsync(new { query = bugQuery.GetWiqlFromConfiguration() }); result = await response.GetJsonAsync <JObject>(); } catch (FlurlHttpException e) { Console.WriteLine($"Failed making call to vsts work item api: {e.Message}"); Console.WriteLine(e.Call.RequestBody); Console.WriteLine(e.Call.Response.StatusCode); Console.WriteLine(e.Call.Response.ResponseMessage); return(0); } if (!result.ContainsKey("queryType")) { return(0); } return(result["workItems"].Count()); }
private async Task <T> HandleSynologyResponse <T>(IFlurlResponse httpResponse, IApiInfo apiInfo, string apiMethod) { switch (httpResponse.StatusCode) { case (int)HttpStatusCode.OK: var response = await httpResponse.GetJsonAsync <ApiResponse <T> >(); if (!response.Success) { var errorDescription = GetErrorMessage(response?.Error?.Code ?? 0, apiInfo.Name); throw new SynologyApiException(apiInfo, apiMethod, response.Error.Code, errorDescription); } if (typeof(T) == typeof(BaseApiResponse)) { return((T)Activator.CreateInstance(typeof(T), new object[] { response.Success })); } return(response.Data); default: throw new UnexpectedResponseStatusException((HttpStatusCode)httpResponse.StatusCode);; } }
/// <summary> /// This method is used to get a commit author's full name via the github rest api. /// Reference: https://docs.github.com/en/rest /// For an example response: https://api.github.com/repos/Azure/iotedge/commits/704250b /// </summary> /// <param name="commit">Commit for which to get the author's full name.</param> /// <returns>Full name of author.</returns> public async Task <string> GetAuthorFullNameFromCommitAsync(string commit) { string requestPath = string.Format(UserPathSegmentFormat, commit); IFlurlRequest workItemQueryRequest = ((Url)requestPath) .WithHeader("Content-Type", "application/json") .WithHeader("User-Agent", "Azure/iotedge"); JObject result; try { IFlurlResponse response = await workItemQueryRequest.GetAsync(); result = await response.GetJsonAsync <JObject>(); string fullName = result["commit"]["author"]["name"].ToString(); return(fullName); } catch (FlurlHttpException e) { string message = $"Failed making call to commit api: {e.Message}"; Console.WriteLine(message); Console.WriteLine(e.Call.RequestBody); Console.WriteLine(e.Call.Response.StatusCode); Console.WriteLine(e.Call.Response.ResponseMessage); throw new Exception(message); } }
public async Task ShouldBeTheSameAsReported() { _httpResponse.StatusCode.Should().Be((int)HttpStatusCode.OK); var weatherForecastDto = await _httpResponse.GetJsonAsync <WeatherForecastDto>(); weatherForecastDto.Should().BeEquivalentTo(_lastInputForecastDto); }
private async Task <TResult> ReadResponseContentAsync <TResult>(IFlurlResponse responseMessage, Func <string, TResult> contentHandler = null) { string content = await responseMessage.GetJsonAsync().ConfigureAwait(false); return(contentHandler != null ? contentHandler(content) : JsonConvert.DeserializeObject <TResult>(content)); }
public async Task <RealtyObjectsResponse[]> GetRealtyObjects() { FlurlHttp.Configure(setting => { setting.Timeout = new TimeSpan(1, 30, 0); }); IFlurlResponse request = await RequestUrl.PostJsonAsync(_requestObject); DataModel.Response response = await request.GetJsonAsync <DataModel.Response>(); return(response.Result.RealtyObjectsReponses); }
private async Task <ApiOffersResponse> PostOffersAsync(ApiOffers offers) { IFlurlResponse httpResponse = await Policy .Handle <HttpRequestException>() .Or <FlurlHttpException>() .OrResult <IFlurlResponse>(result => !result.ResponseMessage.IsSuccessStatusCode) .WaitAndRetryAsync(new TimeSpan[] { TimeSpan.FromSeconds(1) }) .ExecuteAsync(async() => await _basicModel.BasicApiOffers.PostJsonAsync(offers)); ApiOffersResponse apiOffersResponse = await httpResponse.GetJsonAsync <ApiOffersResponse>(); return(apiOffersResponse); }
internal static async Task <string> GetBadRequestErrorDescriptionAsync(this IFlurlResponse response) { try { var json = await response .GetJsonAsync <JObject>() .ConfigureAwait(false); return(json?.SelectToken("$..ErrorDescription")?.ToString() ?? json.ToString()); } catch { return(null); } }
public async Task <ActionResult <ContactInfoResponse> > Post(ContactInfoRequest requestObject) { IFlurlResponse response = await $"{URLConstants.ContactAPIURL}/api/contacts".PostJsonAsync(requestObject); if (response.StatusCode >= 500) { return(StatusCode(500)); } else if (response.StatusCode >= 400) { return(StatusCode(400)); } ContactInfoResponse responseObject = await response.GetJsonAsync <ContactInfoResponse>(); return(CreatedAtAction("Post", responseObject)); }
public async Task <ActionResult <ICollection <ContactInfoResponse> > > GetAll() { IFlurlResponse response = await $"{URLConstants.ContactAPIURL}/api/contacts".GetAsync(); if (response.StatusCode >= 500) { return(StatusCode(500)); } else if (response.StatusCode >= 400) { return(StatusCode(400)); } ICollection <ContactInfoResponse> responseObjects = await response.GetJsonAsync <ICollection <ContactInfoResponse> >(); return(Ok(responseObjects)); }
/// <summary> /// Gets a single transaction. /// Given the transaction id or and error object if the transaction was not found. /// </summary> /// <returns> /// Returns <c>Response</c> object. /// </returns> /// <example> /// <code> /// var merchant = new Vpos(); /// var transaction = merchant.GetTransaction("XCSd3csdbadshg67348tgyfr"); /// </code> /// </example> /// <param name="transactionId"><c>transactionId</c> The id of the transaction to retrieve</param> public Response <Transaction> GetTransaction(string transactionId) { IFlurlResponse result = HttpRequest($"transactions/{transactionId}") .GetAsync().Result; int status = result.StatusCode; string message = StatusMessage.GetMessage(status); if (status == 200) { var transaction = result.GetJsonAsync <Transaction>().Result; Response <Transaction> transactionResponse = new Response <Transaction>(status, message, transaction); return(transactionResponse); } { var errorResponse = new Response <Transaction>(status, message, details: Utils.GetDetails(result)); return(errorResponse); } }
public async Task <ActionResult <ContactInfoResponse> > GetById(long id) { IFlurlResponse response = await $"{URLConstants.ContactAPIURL}/api/contacts/{id}".GetAsync(); if (response.StatusCode == 404) { return(NotFound()); } else if (response.StatusCode >= 500) { return(StatusCode(500)); } else if (response.StatusCode >= 400) { return(StatusCode(400)); } ContactInfoResponse responseObject = await response.GetJsonAsync <ContactInfoResponse>(); return(Ok(responseObject)); }
/// <summary> /// This method is used to retrieve all the team members for the larger iotedge team. /// Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/graph/users/list?view=azure-devops-rest-6.0 /// </summary> /// <returns>List of users. Each containing full name and email.</returns> public async Task <IList <VstsUser> > ListUsersAsync() { string requestPath = string.Format(UserPathSegmentFormat, DevOpsAccessSetting.UserManagementBaseUrl, DevOpsAccessSetting.IotedgeOrganization); IFlurlRequest workItemQueryRequest = ((Url)requestPath) .WithBasicAuth(string.Empty, this.accessSetting.IotedgePAT) .WithHeader("Content-Type", "application/json") .SetQueryParam("api-version", "6.0-preview.1"); JObject result; try { IFlurlResponse response = await workItemQueryRequest.GetAsync(); result = await response.GetJsonAsync <JObject>(); } catch (FlurlHttpException e) { string message = $"Failed making call to list user api: {e.Message}"; Console.WriteLine(message); Console.WriteLine(e.Call.RequestBody); Console.WriteLine(e.Call.Response.StatusCode); Console.WriteLine(e.Call.Response.ResponseMessage); throw new Exception(message); } if (!result.ContainsKey("count") || (int)result["count"] <= 0) { return(new VstsUser[0]); } IList <VstsUser> users = JsonConvert.DeserializeObject <VstsUser[]>(result["value"].ToString()); return(users); }
/// <summary> /// retrieves a request /// Given its id /// </summary> /// <returns> /// Returns <c>RequestResponse</c> if the status is 200 or <c>LocationResponse</c> if the status is 303 /// </returns> /// <example> /// <code> /// var merchant = new Vpos(); /// Response response = merchant.GetRequest("xSDRWFTs48unv9348ut9e"); /// if (response.status == 200) /// { /// // Use response.data /// } /// else if(response.status == 303) /// { /// // Use response.location /// } /// else /// { /// // User response.details /// } /// </code> /// </example> /// <param name="requestId"><c>requestId</c> The id of the request we are consulting</param> public Response <Request> GetRequest(string requestId) { IFlurlResponse result = HttpRequest($"requests/{requestId}") .GetAsync().Result; int status = result.StatusCode; string message = StatusMessage.GetMessage(status); if (status == 200) { var request = result.GetJsonAsync <Request>().Result; var requestResponse = new Response <Request>(status, message, request); return(requestResponse); } else if (status == 303) { var locationResponse = new Response <Request>(status, message, location: Utils.GetLocation(result)); return(locationResponse); } { var errorResponse = new Response <Request>(status, message, details: Utils.GetDetails(result)); return(errorResponse); } }
public async Task <Guid> GetTodoId() => await _response.GetJsonAsync <Guid>();
/// <summary> /// This method is used to create a bug in Azure Dev Ops. /// If it cannot create the bug it will rethrow the exception from the DevOps api. /// Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/create?view=azure-devops-rest-6.0 /// </summary> /// <param name="branch">Branch for which the bug is being created</param> /// <param name="build">Build for which the bug is being created</param> /// <returns>Work item id for the created bug.</returns> public async Task <string> CreateBugAsync(string branch, VstsBuild build) { string requestPath = string.Format(WorkItemPathSegmentFormat, DevOpsAccessSetting.BaseUrl, this.accessSetting.Organization, this.accessSetting.Project); IFlurlRequest workItemQueryRequest = ((Url)requestPath) .WithBasicAuth(string.Empty, this.accessSetting.PersonalAccessToken) .WithHeader("Content-Type", "application/json-patch+json") .SetQueryParam("api-version", "6.0"); var jsonBody = new object[] { new { op = "add", path = "/fields/System.Title", from = string.Empty, value = $"Test failure on {branch}: {build.DefinitionId.ToString()} {build.BuildNumber}" }, new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", from = string.Empty, value = $"This bug is autogenerated by the vsts-pipeline-sync service. Link to failing build:<div> {build.WebUri}" }, new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", from = string.Empty, value = "0" }, new { op = "add", path = "/fields/System.AreaPath", from = string.Empty, value = "One\\IoT\\Platform\\IoTEdge" }, new { op = "add", path = "/relations/-", value = new { rel = "Hyperlink", url = $"{build.WebUri}" } } }; JObject result; try { IFlurlResponse response = await workItemQueryRequest .PostJsonAsync(jsonBody); result = await response.GetJsonAsync <JObject>(); } catch (FlurlHttpException e) { string message = $"Failed making call to vsts work item api: {e.Message}"; Console.WriteLine(message); Console.WriteLine(e.Call.RequestBody); Console.WriteLine(e.Call.Response.StatusCode); Console.WriteLine(e.Call.Response.ResponseMessage); throw new Exception(message); } return(result["id"].ToString()); }
private async Task <TResponse> SetStatusCodeAndGetJsonResponse <TResponse>(IFlurlResponse flurlResponse) { StatusCode = flurlResponse.StatusCode; return(await flurlResponse.GetJsonAsync <TResponse>()); }
/// <summary> /// This method is used to create a bug in Azure Dev Ops. /// If it cannot create the bug it will rethrow the exception from the DevOps api. /// Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/create?view=azure-devops-rest-6.0 /// </summary> /// <param name="branch">Branch for which the bug is being created</param> /// <param name="build">Build for which the bug is being created</param> /// <returns>Work item id for the created bug.</returns> public async Task <string> CreateBugAsync(string branch, VstsBuild build) { string requestPath = string.Format(WorkItemPathSegmentFormat, DevOpsAccessSetting.BaseUrl, DevOpsAccessSetting.AzureOrganization, DevOpsAccessSetting.AzureProject); IFlurlRequest workItemQueryRequest = ((Url)requestPath) .WithBasicAuth(string.Empty, this.accessSetting.MsazurePAT) .WithHeader("Content-Type", "application/json-patch+json") .SetQueryParam("api-version", "6.0"); (string bugOwnerFullName, string bugOwnerEmail) = await this.GetBugOwnerInfoAsync(build.SourceVersion); string bugDescription = GenerateBugDescription(bugOwnerFullName, bugOwnerEmail, build); var jsonBody = new object[] { new { op = "add", path = "/fields/System.Title", from = string.Empty, value = $"Test failure on {branch}: {build.DefinitionId.ToString()} {build.BuildNumber}" }, new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", from = string.Empty, value = bugDescription }, new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", from = string.Empty, value = "0" }, new { op = "add", path = "/fields/System.AreaPath", from = string.Empty, value = "One\\IoT\\Platform and Devices\\IoTEdge" }, new { op = "add", path = "/relations/-", value = new { rel = "Hyperlink", url = $"{build.WebUri}" } }, new { op = "add", path = "/fields/System.AssignedTo", value = bugOwnerEmail }, new { op = "add", path = "/fields/System.Tags", value = "auto-pipeline-failed" } }; JObject result; try { IFlurlResponse response = await workItemQueryRequest .PostJsonAsync(jsonBody); result = await response.GetJsonAsync <JObject>(); } catch (FlurlHttpException e) { string message = $"Failed making call to vsts work item api: {e.Message}"; Console.WriteLine(message); Console.WriteLine(e.Call.RequestBody); Console.WriteLine(e.Call.Response.StatusCode); Console.WriteLine(e.Call.Response.ResponseMessage); throw new Exception(message); } return(result["id"].ToString()); }