public override void OnException(HttpActionExecutedContext context) { Exception exp; try { var logLevel = GetLogLevel(context.Exception); _logException(context.Exception, logLevel); var error = ToError(context.Exception); var httpResponseMessage = new HttpResponseMessage { StatusCode = GetStatusCode(context.Exception), ReasonPhrase = context.Exception.Message, RequestMessage = context.Request, Content = new ObjectContent<Error>(error, new JsonMediaTypeFormatter(), "application/json"), }; exp = new HttpResponseException(httpResponseMessage); } catch (Exception exception) { var e = new AggregateException(exception, context.Exception); _logException(e, LogLevel.SystemError); throw; } throw exp; }
private bool MessageHandler(HttpRequestMessage request, HttpResponseMessage response) { if (request.RequestUri.OriginalString.Contains("status")) { try { int code = Convert.ToInt32( request.RequestUri.OriginalString.Substring(request.RequestUri.OriginalString.Length - 3, 3)); HttpStatusCode status = (HttpStatusCode)code; throw new HttpStatusException(status); } catch (HttpStatusException) { throw; } catch (Exception) { throw new HttpStatusException(HttpStatusCode.BadRequest); } } else response.Content = new StringContent(string.Format(Html, DateTime.Now.ToString("s"), request.RequestUri.OriginalString), Encoding.UTF8, "text/html"); return true; }
public void ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults() { // Arrange Mock<IAuthorizationFilter> mockAttr = new Mock<IAuthorizationFilter>() { CallBase = true }; HttpResponseMessage response = new HttpResponseMessage(); InvalidOperationException exception = new InvalidOperationException("test"); TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(response); tcs.TrySetException(exception); mockAttr.Setup(a => a.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task); Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object); Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromResult<HttpResponseMessage>(response); TestTraceWriter traceWriter = new TestTraceWriter(); AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockAttr.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAuthorizationFilterAsync" }, new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ExecuteAuthorizationFilterAsync" } }; // Act & Assert Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation); Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait()); // Assert Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public virtual GetDatabaseResponse Create(HttpResponseMessage httpResponse) { return Materialize<GetDatabaseResponse>( httpResponse, SuccessfulResponseMaterializer.Materialize, FailedResponseMaterializer.Materialize); }
public bool CanEnrich(HttpResponseMessage response) { var content = response.Content as ObjectContent; return content != null && (content.ObjectType == typeof(MediaModel)); }
public void PostTest() { var response = new HttpResponseMessage(HttpStatusCode.OK); var result = _contactController.Post(contact); Assert.AreEqual(response.StatusCode, result.StatusCode); }
/// <summary> /// Get the resource description of the api for swagger documentation /// </summary> /// <remarks>It is very convenient to have this information available for generating clients. This is the entry point for the swagger UI /// </remarks> /// <returns>JSON document representing structure of API</returns> public HttpResponseMessage Get() { var docProvider = (XmlCommentDocumentationProvider)GlobalConfiguration.Configuration.Services.GetDocumentationProvider(); ResourceListing r = SwaggerGen.CreateResourceListing(ControllerContext); List<string> uniqueControllers = new List<string>(); foreach (var api in GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; if (uniqueControllers.Contains(controllerName) || controllerName.ToUpper().Equals(SwaggerGen.SWAGGER.ToUpper())) continue; uniqueControllers.Add(controllerName); ResourceApi rApi = SwaggerGen.CreateResourceApi(api); r.apis.Add(rApi); } HttpResponseMessage resp = new HttpResponseMessage(); resp.Content = new ObjectContent<ResourceListing>(r, ControllerContext.Configuration.Formatters.JsonFormatter); return resp; }
public void AddAndDeleteGridWidgetFromFileSystemVerifyPageToolbox() { RuntimeSettingsModificator.ExecuteWithClientTimeout(800000, () => BAT.Macros().NavigateTo().CustomPage("~/sitefinity/pages", false)); RuntimeSettingsModificator.ExecuteWithClientTimeout(800000, () => BAT.Macros().User().EnsureAdminLoggedIn()); BAT.Wrappers().Backend().Pages().PagesWrapper().OpenPageZoneEditor(PageName); BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().SwitchEditorLayoutMode(EditorLayoutMode.Layout); BATFrontend.Wrappers().Backend().Widgets().GridWidgets().ClickBootstrapGridWidgetButton(); BATFrontend.Wrappers().Backend().Pages().PageZoneEditorWrapper().DragAndDropLayoutWidgetToPlaceholder(LayoutCaption); BAT.Wrappers().Backend().Pages().PageLayoutEditorWrapper().VerifyLayoutWidgetPageEditor(LayoutCaption, GridCount1); BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().PublishPage(); BAT.Macros().NavigateTo().CustomPage("~/" + PageName.ToLower(), false); BATFrontend.Wrappers().Frontend().Widgets().GridWidgets().VerifyNewGridWidgetOnTheFrontend(this.layouts); BAT.Arrange(this.TestName).ExecuteArrangement("DeleteGridWidgetFromFileSystem"); BAT.Macros().NavigateTo().Pages(); BAT.Wrappers().Backend().Pages().PagesWrapper().OpenPageZoneEditor(PageName); BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().SwitchEditorLayoutMode(EditorLayoutMode.Layout); BATFrontend.Wrappers().Backend().Widgets().GridWidgets().ClickBootstrapGridWidgetButton(); Assert.IsFalse( BATFrontend.Wrappers().Backend().Pages().PageZoneEditorWrapper().IsLayoutWidgetPresentInToolbox(LayoutCaption), "Layout widget is found in the toolbox"); BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().PublishPage(); BAT.Macros().NavigateTo().CustomPage("~/" + PageName.ToLower(), false); // Asserts that the page is not throwing an error 500 on the frontend HttpResponseMessage response = new HttpResponseMessage(); Assert.AreEqual(200, (int)response.StatusCode); }
internal static void ReadStatusLine(HttpResponseMessage response, string responseHeader) { Debug.Assert(responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase), "Status Line starts with http prefix"); int index = HttpPrefix.Length; int majorVersion = ReadInt(responseHeader, ref index); CheckResponseMsgFormat(majorVersion != 0); CheckResponseMsgFormat(index < responseHeader.Length && responseHeader[index] == '.'); index++; // Need minor version CheckResponseMsgFormat(index < responseHeader.Length && responseHeader[index] >= '0' && responseHeader[index] <= '9'); int minorVersion = ReadInt(responseHeader, ref index); CheckResponseMsgFormat(SkipSpace(responseHeader, ref index)); // parse status code int statusCode = ReadInt(responseHeader, ref index); CheckResponseMsgFormat(statusCode >= 100 && statusCode < 600); bool foundSpace = SkipSpace(responseHeader, ref index); CheckResponseMsgFormat(index <= responseHeader.Length); CheckResponseMsgFormat(foundSpace || index == responseHeader.Length); // Set the response HttpVersion response.Version = (majorVersion == 1 && minorVersion == 1) ? HttpVersion.Version11 : (majorVersion == 1 && minorVersion == 0) ? HttpVersion.Version10 : (majorVersion == 2 && minorVersion == 0) ? HttpVersion.Version20 : HttpVersion.Unknown; response.StatusCode = (HttpStatusCode)statusCode; response.ReasonPhrase = responseHeader.Substring(index); }
public Task<HttpResponseMessage> ExecuteAsync( CancellationToken cancellationToken ) { //Request.GetOwinContext().Authentication.Challenge( LoginProvider ); HttpResponseMessage response = new HttpResponseMessage( HttpStatusCode.Unauthorized ); response.RequestMessage = Request; return Task.FromResult( response ); }
public static void ThrowIfError(HttpResponseMessage response, dynamic json) { if (json == null) return; if (!JsonHelpers.ContainsProperty(json, Constants.ErrorProperty)) return; var error = json[Constants.ErrorProperty]; if (string.IsNullOrWhiteSpace(error)) return; CexApiException exception; if (error == Constants.NonceMustBeIncremented) { exception = new CexNonceException(response, Constants.NonceMustBeIncremented); } else if (error == Constants.PermissionDenied) { exception = new CexPermissionDeniedException(response, Constants.PermissionDenied); } else if (error == Constants.InvalidApiKey) { exception = new CexInvalidApiKeyException(response, Constants.InvalidApiKey); } else { exception = new CexApiException(response, error); } throw exception; }
public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { if (actionContext.Request.Headers.Contains("X-AccessToken")) { var tokenvalue = actionContext.Request.Headers.GetValues("X-AccessToken").FirstOrDefault(); if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"])) { return continuation(); } } else if (actionContext.Request.RequestUri.ParseQueryString() != null) { var queryValues = actionContext.Request.RequestUri.ParseQueryString(); var tokenvalue = queryValues["token"]; if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"])) { return continuation(); } } return Task.Factory.StartNew(() => { var retur = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("This resource cannot be used without the correct access token") }; return retur; }); }
private HttpResponseMessage Execute() { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; response.ReasonPhrase = ReasonPhrase; return response; }
public static HttpResponseMessage CreateSuccessTokenResponseMessage() { HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); HttpContent content = new StringContent("{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"scope\":\"some-scope1 some-scope2\",\"access_token\":\"some-access-token\",\"refresh_token\":\"OAAsomethingencryptedQwgAA\",\"id_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJlODU0YTRhNy02YzM0LTQ0OWMtYjIzNy1mYzdhMjgwOTNkODQiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vNmMzZDUxZGQtZjBlNS00OTU5LWI0ZWEtYTgwYzRlMzZmZTVlL3YyLjAvIiwiaWF0IjoxNDU1ODMzODI4LCJuYmYiOjE0NTU4MzM4MjgsImV4cCI6MTQ1NTgzNzcyOCwiaXBhZGRyIjoiMTMxLjEwNy4xNTkuMTE3IiwibmFtZSI6Ik1hcmlvIFJvc3NpIiwib2lkIjoidW5pcXVlX2lkIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiZGlzcGxheWFibGVAaWQuY29tIiwic3ViIjoiSzRfU0dHeEtxVzFTeFVBbWhnNkMxRjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSIsInZlciI6IjIuMCJ9.Z6Xc_PzqTtB-2TjyZwPpFGgkAs47m95F_I-NHxtIJT-H20i_1kbcBdmJaj7lMjHhJwAAMM-tE-iBVF9f7jNmsDZAADt-HgtrrXaXxkIKMwQ_MuB-OI4uY9KYIurEqmkGvOlRUK1ZVNNf7IKE5pqNTOZzyFDEyG8SwSvAmN-J4VnrxFz3d47klHoKVKwLjWJDj7edR2UUkdUQ6ZRj7YBj9UjC8UrmVNLBmvyatPyu9KQxyNyJpmTBT2jDjMZ3J1Z5iL98zWw_Ez0-6W0ti87UaPreJO3hejqQE_pRa4rXMLpw3oAnyEE1H7n0F6tK_3lJndZi9uLTIsdSMEXVnZdoHg\",\"id_token_expires_in\":\"3600\",\"profile_info\":\"eyJ2ZXIiOiIxLjAiLCJuYW1lIjoiTWFyaW8gUm9zc2kiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJtYXJpb0BkZXZlbG9wZXJ0ZW5hbnQub25taWNyb3NvZnQuY29tIiwic3ViIjoiSzRfU0dHeEtxVzFTeFVBbWhnNkMxRjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSJ9\"}"); responseMessage.Content = content; return responseMessage; }
public static HttpResponseMessage CreateInvalidGrantTokenResponseMessage() { HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); HttpContent content = new StringContent("{\"error\":\"invalid_grant\",\"error_description\":\"AADSTS70002: Error validating credentials.AADSTS70008: The provided access grant is expired or revoked.Trace ID: f7ec686c-9196-4220-a754-cd9197de44e9Correlation ID: 04bb0cae-580b-49ac-9a10-b6c3316b1eaaTimestamp: 2015-09-16 07:24:55Z\",\"error_codes\":[70002,70008],\"timestamp\":\"2015-09-16 07:24:55Z\",\"trace_id\":\"f7ec686c-9196-4220-a754-cd9197de44e9\",\"correlation_id\":\"04bb0cae-580b-49ac-9a10-b6c3316b1eaa\"}"); responseMessage.Content = content; return responseMessage; }
public HttpResponseMessage GetProvidersData([FromUri]Filter filter) { string factualJsonData; try { factualJsonData = repository.GetHealthCareProviderData(filter); } catch (FactualApiException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message) }); } // Get the IContentNegotiator IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator(); // Run content negotiation to select a formatter ContentNegotiationResult result = negotiator.Negotiate( typeof(string), this.Request, this.Configuration.Formatters); var response = new HttpResponseMessage(HttpStatusCode.OK); if (result.MediaType.MediaType.Equals("application/xml")) { string json = string.Format("{0}{1}{2}", "{Root: ", factualJsonData, "}"); var doc = (XDocument)JsonConvert.DeserializeXNode(json); response.Content = new StringContent(doc.ToString(), Encoding.UTF8, result.MediaType.MediaType); } else response.Content = new StringContent(factualJsonData, Encoding.UTF8, "application/json"); return response; }
public void ListWebHostingPlans() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(HttpPayload.ListWebHostingPlans) }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetWebSiteManagementClient(handler); var result = client.WebHostingPlans.List("space1"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); // Validate response Assert.NotNull(result.WebHostingPlans); Assert.Equal(1, result.WebHostingPlans.Count); Assert.NotNull(result.WebHostingPlans.ElementAt(0)); Assert.Equal("Default1", result.WebHostingPlans.ElementAt(0).Name); Assert.Equal(SkuOptions.Standard, result.WebHostingPlans.ElementAt(0).SKU); Assert.Equal(1, result.WebHostingPlans.ElementAt(0).NumberOfWorkers); Assert.Equal("adminsite1", result.WebHostingPlans.ElementAt(0).AdminSiteName); }
// GET /api/messages/5 public HttpResponseMessage<MessageModels.MessageResponse> Get(string id) { var message = GetMessage(id); //TODO: check to see if message exists with id if (message == null) return new HttpResponseMessage<MessageModels.MessageResponse>(HttpStatusCode.NotFound); //TODO: return message var response = new HttpResponseMessage<MessageModels.MessageResponse>(new MessageModels.MessageResponse() { amount = message.Amount, comments = message.Comments, createDate = message.CreateDate, Id = message.Id.ToString(), lastUpdatedDate = message.LastUpdatedDate, messageStatus = message.MessageStatus.ToString(), messageType = message.MessageType.ToString(), recipient = new UserModels.UserResponse() { }, recipientUri = message.RecipientUri, sender = new UserModels.UserResponse() { }, senderUri = message.SenderUri, senderAccount = new AccountModels.AccountResponse() { } }, HttpStatusCode.OK); return response; }
public static void LogHttpResponse(this DiagnosticListener @this, HttpResponseMessage response, Guid loggingRequestId) { if (@this.IsEnabled(HttpHandlerLoggingStrings.ResponseWriteName)) { LogHttpResponseCore(@this, response, loggingRequestId); } }
public void TestDeleteAzureMediaServiceAccountAsync404() { FakeHttpMessageHandler fakeHttpHandler; MediaServicesManagementClient clientWithHandler = CreateMediaManagementClientWithFakeHttpMessageHandler(out fakeHttpHandler); const string responseText = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">{\"Code\":\"NotFound\",\"Message\":\"The specified account was not found.\"}</string>"; HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new FakeHttpContent(responseText) }; fakeHttpHandler.Send = request => response; MediaServicesClient target = new MediaServicesClient(null, clientWithHandler, StorageClient.WithHandler(new FakeHttpMessageHandler())); try { OperationResponse result = target.DeleteAzureMediaServiceAccountAsync(AccountName).Result; } catch (AggregateException ax) { CloudException x = (CloudException)ax.InnerExceptions.Single(); Assert.AreEqual(HttpStatusCode.NotFound, x.Response.StatusCode); return; } Assert.Fail("ServiceManagementClientException expected"); }
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsyncCore( HttpRequestMessage request, CancellationToken cancellationToken) { TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.Redirect; response.Headers.Location = new Uri(Location + Calls); response.RequestMessage = request; if (Calls == 1) { // First call the message should contain If-* headers Assert.That(request.RequestUri, Is.EqualTo(new Uri(Location))); Assert.That(request.Headers.IfMatch.Count == 1); Assert.That(request.Headers.IfNoneMatch.Count == 1); Assert.That(request.Headers.IfModifiedSince.HasValue); Assert.That(request.Headers.IfUnmodifiedSince.HasValue); } else { // After first call the message should not contain If-* headers Assert.That(request.RequestUri, Is.EqualTo(new Uri(Location + (Calls - 1)))); Assert.That(request.Headers.IfMatch.Count == 0); Assert.That(request.Headers.IfNoneMatch.Count == 0); Assert.IsNull(request.Headers.IfModifiedSince); Assert.IsNull(request.Headers.IfUnmodifiedSince); } tcs.SetResult(response); return tcs.Task; }
public override Task<HttpResponseMessage> HandleResponseAsync(string linkRelation, HttpResponseMessage responseMessage) { _action(linkRelation, responseMessage); return base.HandleResponseAsync(linkRelation, responseMessage); }
private HttpResponseMessage Execute() { HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); response.RequestMessage = request; response.ReasonPhrase = errorMessage; return response; }
public WebApiResponseMessage(HttpResponseMessage response) : base(response.Content) { this.response = response; this.response.Headers.ToList() .ForEach(h => this.messageHeaders.Add(h.Key, h.Value.ToArray())); }
public void ExecuteExceptionFilterAsync_Traces() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage(); Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true }; Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response); TestTraceWriter traceWriter = new TestTraceWriter(); ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" }, new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "OnException" }, }; // Act Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None); task.Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage(); Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true }; InvalidOperationException exception = new InvalidOperationException("test"); mockAttr.Setup(a => a.OnException(It.IsAny<HttpActionExecutedContext>())).Throws(exception); Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response); TestTraceWriter traceWriter = new TestTraceWriter(); ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" }, new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "OnException" } }; // Act Exception thrown = Assert.Throws<InvalidOperationException>( () => ((IExceptionFilter) tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None)); // Assert Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { bool authorized = false; var controller = actionContext.ControllerContext.Controller as ApiAuthorizeController; if (controller != null) { var cookie = actionContext.Request.Headers.GetCookies().Select( c => c[controller.Authenticator.CookieTicketConfig.CookieName]).FirstOrDefault(); CookieHeaderValue cookieValue; CookieTicket ticket; if (controller.Authenticator.ValidateCookieTicket(cookie, out ticket, out cookieValue)) { authorized = true; controller.UserId = int.Parse(ticket.Name); if (cookieValue != null) { actionContext.Request.Properties.Add(RenewAuthorizationCookieToken, cookieValue); } } } if (!authorized) { var message = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); actionContext.Response = message; } }
public void RetryAfter_RetryHeader_100() { var headers = new HttpResponseMessage().Headers; headers.Add("Retry-After", "100"); var response = new FitbitResponse<string>((HttpStatusCode)429, headers, null); Assert.AreEqual(100, response.RetryAfter()); }
public void ResponsePolicyWithBody() { // Assert var responseMessage = new HttpResponseMessage() { Content = new StringContent("Hello World!") }; var variables = new Dictionary<string, object>() { { "message-id","xxxyyy"} }; var context = new Context(responseMessage: responseMessage, variables: variables); // Act string policyResult = SendResponseToEventHub(context); //Assert Assert.Equal("response:xxxyyy\n" + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain; charset=utf-8\r\n" + "Content-Length: 12\r\n" + "\r\n" + "Hello World!", policyResult); }
public async Task SendDelivered_request_caregiver() { //bool status = false; string mealtype = SelectedMealTime.meal_name; string meal_time = ""; if (mealtype.ToLowerInvariant() == "Breakfast".ToLowerInvariant()) { meal_time = "BF"; } else if (mealtype.ToLowerInvariant() == "Lunch".ToLowerInvariant()) { meal_time = "LH"; } else if (mealtype.ToLowerInvariant() == "Dinner".ToLowerInvariant()) { meal_time = "DN"; } else { meal_time = mealtype; } try { string ss = ""; if (string.IsNullOrEmpty(RemarkText)) { ss = "NA"; } else { ss = RemarkText; } //--------POST----------- dynamic jObj = new JObject(); jObj.MealTime = meal_time; jObj.meal_time_id = SelectedMealTime.ID; jObj.mode_of_payment = 0; jObj.orderId = SelectedOrderDetail.OrderedID; jObj.payment_remark = string.Empty; // var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(p)); string stringPayload = JsonConvert.SerializeObject(jObj); // Wrap our JSON inside a StringContent which then can be used by the HttpClient class var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json"); using (var httpClient = new System.Net.Http.HttpClient()) { var httpResponse = new System.Net.Http.HttpResponseMessage(); httpResponse = await httpClient.PostAsync(Library.URL + "/" + Library.METHODE_SETDELIVEREDSTATUS, httpContent); if (httpResponse.Content != null) { var responseContent = await httpResponse.Content.ReadAsStringAsync(); } } } catch (Exception exp) { await PageDialog.DisplayAlertAsync("Alert!!", exp.Message, "OK"); } }
public void ReceiveResponse(string invocationId, System.Net.Http.HttpResponseMessage response, string methodName, string filePath, int line) { _traceSource.TraceEvent(TraceEventType.Verbose, 2, Strings.SystemTraceSink_ReceiveResponse, invocationId, methodName, filePath, line, (int)response.StatusCode, response.RequestMessage.RequestUri); }
/// <summary> /// PostData is ageneric method to authenticate the users /// </summary> /// <typeparam name="T"></typeparam> /// <param name="methodName"></param> /// <param name="postedObject"></param> /// <returns></returns> public async Task <ServiceResponse> PostData <T>(string methodName, object postedObject) { string response = string.Empty; try { string serviceUrl = Helpers.AppConstants.GetSettingsItem("BaseURL"); Uri requestUri = new Uri(serviceUrl + methodName, UriKind.RelativeOrAbsolute); string json = ""; json = Newtonsoft.Json.JsonConvert.SerializeObject(postedObject); var objClint = new System.Net.Http.HttpClient(); FormUrlEncodedContent formContent = new FormUrlEncodedContent((Dictionary <string, string>)postedObject); var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); System.Net.Http.HttpResponseMessage respon = await objClint.PostAsync(requestUri, formContent); response = await respon.Content.ReadAsStringAsync(); if (respon.IsSuccessStatusCode) { svcResponse.ResponseObject = JsonConvert.DeserializeObject <T>(response); svcResponse.Success = true; return(svcResponse); } else { try { svcResponse.ErrorObject = JsonConvert.DeserializeObject <Error>(response); } catch (Exception ex) { svcResponse.Success = false; svcResponse.ErrorObject.Message = AppConstants.UnhandledException; svcResponse.ErrorObject.Message += " " + ex.Message; } svcResponse.ResponseObject = null; svcResponse.Success = false; return(svcResponse); } } catch (HttpRequestException ex) { svcResponse.ResponseObject = null; svcResponse.ErrorObject.Message = AppConstants.HttpRequestException; svcResponse.ErrorObject.Message += " " + ex.Message; svcResponse.Success = false; } catch (JsonSerializationException ex) { if (!string.IsNullOrEmpty(response)) { svcResponse.ErrorObject.Message = AppConstants.SerilizationExceptoin; svcResponse.ErrorObject.Message += " " + ex.Message; svcResponse.Success = false; } else { svcResponse.ErrorObject.Message = AppConstants.SerilizationExceptoin; svcResponse.ErrorObject.Message += " " + ex.Message; svcResponse.Success = false; } } catch (Exception ex) { svcResponse.ErrorObject.Message = AppConstants.UnhandledException; svcResponse.ErrorObject.Message += " " + ex.Message; svcResponse.Success = false; } return(svcResponse); }
public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) { }
public RestException(System.Net.Http.HttpResponseMessage response) { StatusCode = response.StatusCode; //CloneWithContent will not work here since the content is disposed after sendAsync //Besides, it seems there is no need for the request content cloned here. RequestMessage = response.RequestMessage.Clone(); ResponseBody = response.Content.ReadAsStringAsync().Result; ResponseHeaders = response.Headers; RequestId = response.GetFirstHeader("x-ms-request-id"); ClientRequestId = response.GetFirstHeader("x-ms-client-request-id"); try { // try to parse the body as JSON, and see if a code and message are in there. var json = Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Runtime.Json.JsonObject; // error message could be in properties.statusMessage { message = If(json?.Property("properties"), out var p) && If(p?.PropertyT <Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Runtime.Json.JsonString>("statusMessage"), out var sm) ? (string)sm : (string)Message; } // see if there is an error block in the body json = json?.Property("error") ?? json; { Code = If(json?.PropertyT <Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Runtime.Json.JsonString>("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } { message = If(json?.PropertyT <Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Runtime.Json.JsonString>("message"), out var m) ? (string)m : (string)Message; } { Action = If(json?.PropertyT <Microsoft.Azure.PowerShell.Cmdlets.ManagedServices.Runtime.Json.JsonString>("action"), out var a) ? (string)a : (string)Action; } } #if DEBUG catch (System.Exception E) { System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); } #else catch { // couldn't get the code/message from the body response. // In this case, we will assume the response is the expected error message if (!string.IsNullOrEmpty(ResponseBody)) { message = ResponseBody; } } #endif if (string.IsNullOrEmpty(message)) { if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) { message = $"The server responded with a Request Error, Status: {StatusCode}"; } else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) { message = $"The server responded with a Server Error, Status: {StatusCode}"; } else { message = $"The server responded with an unrecognized response, Status: {StatusCode}"; } } }
/// <summary> /// Provides a resouce group with name 'testgroup101' and location 'West US'. /// </summary> /// <param name='resourceGroupName'> /// Resource Group name 'testgroup101'. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <SampleResourceGroup> > GetSampleResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSampleResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <SampleResourceGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <SampleResourceGroup>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <Product> > PatchProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PatchProduct", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (product != null) { _requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject <Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <Product>(_responseContent, DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// GetData is ageneric method to call restfull service and getting the data /// </summary> /// <typeparam name="T"></typeparam> /// <param name="methodName"></param> /// <returns></returns> public async Task <ServiceResponse> GetData <T>(string methodName, string AccessToken = null) { string response = string.Empty; try { string serviceUrl = Helpers.AppConstants.GetSettingsItem("BaseURL"); if (string.IsNullOrEmpty(serviceUrl)) { svcResponse.ErrorObject.Message = AppConstants.CantReadSettingfile; svcResponse.Success = false; return(svcResponse); } Uri geturi = new Uri(serviceUrl + methodName, UriKind.RelativeOrAbsolute); using (var client = new HttpClient()) { if (AccessToken != null) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken); } System.Net.Http.HttpResponseMessage getResponse = await client.GetAsync(geturi); response = await getResponse.Content.ReadAsStringAsync(); if (getResponse.IsSuccessStatusCode) { svcResponse.ResponseObject = JsonConvert.DeserializeObject <T>(response); svcResponse.Success = true; return(svcResponse); } else { try { svcResponse.ErrorObject = JsonConvert.DeserializeObject <Error>(response); } catch (Exception ex) { svcResponse.ErrorObject.Message = ex.Message; svcResponse.Success = false; svcResponse.ErrorObject.Message = AppConstants.UnhandledException; } svcResponse.ResponseObject = null; svcResponse.Success = false; return(svcResponse); } } } catch (HttpRequestException ex) { svcResponse.ResponseObject = null; svcResponse.ErrorObject.Message = AppConstants.HttpRequestException; svcResponse.ErrorObject.Message += " " + ex.Message; svcResponse.Success = false; } catch (JsonSerializationException ex) { if (!string.IsNullOrEmpty(response)) { svcResponse.ErrorObject.Message = AppConstants.SerilizationExceptoin; svcResponse.ErrorObject.Message += " " + ex.Message; svcResponse.Success = false; } else { svcResponse.ErrorObject.Message = AppConstants.SerilizationExceptoin; svcResponse.ErrorObject.Message += " " + ex.Message; svcResponse.Success = false; } } catch (Exception ex) { svcResponse.ErrorObject.Message = AppConstants.UnhandledException; svcResponse.ErrorObject.Message += " " + ex.Message; svcResponse.Success = false; } return(svcResponse); }
public async Task LoadPreviewImage() { // Geting url for download var httpClient = new System.Net.Http.HttpClient(); string fullPathFrom = AddBackslash(Path); fullPathFrom += Name; string url = "https://graph.microsoft.com/v1.0/me" + fullPathFrom + ":/thumbnails/0/medium"; var request = new System.Net.Http.HttpRequestMessage(HttpMethod.Get, url); request.Version = Version.Parse("1.0"); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Account.Token); System.Net.Http.HttpResponseMessage response = await httpClient.SendAsync(request); string urlImage = null; using (System.IO.Stream stream = await response.Content.ReadAsStreamAsync()) { DeserializedImage deserializedImage = new DeserializedImage(); DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedImage.GetType()); deserializedImage = ser.ReadObject(stream) as DeserializedImage; if (deserializedImage == null || String.IsNullOrEmpty(deserializedImage.Url)) { throw new NullReferenceException("Couldn't deserialized the data"); } urlImage = deserializedImage.Url; } // Download image httpClient = new System.Net.Http.HttpClient(); request = new System.Net.Http.HttpRequestMessage(HttpMethod.Get, urlImage); response = await httpClient.SendAsync(request); using (var streamCopy = new MemoryStream()) { using (System.IO.Stream stream = await response.Content.ReadAsStreamAsync()) { Byte[] bytes = new Byte[1024]; int reader = 0; do { reader = await stream.ReadAsync(bytes, 0, bytes.Length); await streamCopy.WriteAsync(bytes, 0, reader); } while (reader > 0); await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() => { PreviewImage = new BitmapImage(); // ReSharper disable AccessToDisposedClosure streamCopy.Seek(0, SeekOrigin.Begin); await PreviewImage.SetSourceAsync(streamCopy.AsRandomAccessStream()); // ReSharper restore AccessToDisposedClosure }); } } }
partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response);
public override async System.Threading.Tasks.Task <IList <SeafDirEntry> > ParseResponseAsync(System.Net.Http.HttpResponseMessage msg) { var entries = await base.ParseResponseAsync(msg); // set the library id & path of the items foreach (var entry in entries) { entry.LibraryId = LibraryId; // parent_dir is only sent when recursive was true if (entry.ParentDirectory == null) { entry.ParentDirectory = Path; } if (!entry.ParentDirectory.EndsWith("/")) { entry.ParentDirectory += "/"; } entry.Path = entry.ParentDirectory + entry.Name; } return(entries); }
internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => string.Equals(headerName, each.Key, System.StringComparison.OrdinalIgnoreCase)).Value?.FirstOrDefault() ?? string.Empty;
/// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } if (complexBody != null) { complexBody.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString(); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public override async System.Threading.Tasks.Task <bool> ParseResponseAsync(System.Net.Http.HttpResponseMessage msg) { string content = await msg.Content.ReadAsStringAsync(); return(content == "\"success\""); }
/// <summary> /// Updates the tags for an availability set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='avset'> /// The name of the storage availability set. /// </param> /// <param name='tags'> /// A set of tags. A description about the set of tags. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string avset, IDictionary <string, string> tags, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (avset == null) { throw new ValidationException(ValidationRules.CannotBeNull, "avset"); } if (avset != null) { if (avset.Length > 80) { throw new ValidationException(ValidationRules.MaxLength, "avset", 80); } } if (tags == null) { throw new ValidationException(ValidationRules.CannotBeNull, "tags"); } AvailabilitySetUpdateParameters tags1 = new AvailabilitySetUpdateParameters(); if (tags != null) { tags1.Tags = tags; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("avset", avset); tracingParameters.Add("tags1", tags1); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterFlattening/{resourceGroupName}/{availabilitySetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{availabilitySetName}", System.Uri.EscapeDataString(avset)); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (tags1 != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(tags1, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response) { ProcessResponse(response).GetAwaiter().GetResult(); }
/// <summary> /// Gets all deployments operations for a deployment. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <IPage <DeploymentOperation> > > ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <DeploymentOperation> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <DeploymentOperation> >(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
protected virtual async System.Threading.Tasks.Task <ObjectResponseResult <T> > ReadObjectResponseAsync <T>(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary <string, System.Collections.Generic.IEnumerable <string> > headers, System.Threading.CancellationToken cancellationToken) { if (response == null || response.Content == null) { return(new ObjectResponseResult <T>(default(T) !, string.Empty)); } if (ReadResponseAsString) { var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(responseText, JsonSerializerSettings); return(new ObjectResponseResult <T>(typedBody !, responseText)); } catch (Newtonsoft.Json.JsonException exception) { var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; throw new ApiException(message, (int)response.StatusCode, responseText, headers, exception); } } else { try { using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) using (var streamReader = new System.IO.StreamReader(responseStream)) using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); var typedBody = serializer.Deserialize <T>(jsonTextReader); return(new ObjectResponseResult <T>(typedBody !, string.Empty)); } } catch (Newtonsoft.Json.JsonException exception) { var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; throw new ApiException(message, (int)response.StatusCode, string.Empty, headers, exception); } } }
/// <summary> /// Gets a pet from the store /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> GetWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <param name='limit'> /// number of pets to return /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <IList <Pet> > > PetsWithHttpMessagesAsync(int?limit = 11, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (limit > 10000) { throw new ValidationException(ValidationRules.InclusiveMaximum, "limit", 10000); } if (limit < 11) { throw new ValidationException(ValidationRules.InclusiveMinimum, "limit", 11); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("limit", limit); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Pets", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "").ToString(); List <string> _queryParameters = new List <string>(); if (limit != null) { _queryParameters.Add(string.Format("limit={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(limit, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <IList <Pet> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <IList <Pet> >(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Get method that overwrites x-ms-client-request header with value /// 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> GetWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/overwrite/x-ms-client-request-id/method/").ToString(); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// search the imaging system for our invoice to get the document's unique identifier /// </summary> /// <param name="sessionToken">the token received from logging into the integration server</param> /// <param name="customerInfo">branch and customer information</param> /// <param name="invoiceNumber">the customer's invoice number</param> /// <returns>the document's unique identifier within the imaging system</returns> /// <remarks> /// jwames - 3/30/2015 - original code /// </remarks> public List <string> GetDocumentIds(string sessionToken, UserSelectedContext customerInfo, string invoiceNumber) { if (sessionToken.Length == 0) { throw new ArgumentException("SessionToken cannot be blank. Reauthentication might be necessary."); } if (customerInfo.BranchId.Length == 0) { throw new ArgumentException("Branch cannot be blank"); } if (customerInfo.CustomerId.Length == 0) { throw new ArgumentException("Customer number cannot be blank"); } if (invoiceNumber.Length == 0) { throw new ArgumentException("Invoice number cannot be blank"); } using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add(Constants.IMAGING_HEADER_SESSIONTOKEN, sessionToken); client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); client.DefaultRequestHeaders.Add("Accept", "application/json"); try { Dictionary <string, string> values = new Dictionary <string, string>(); values.Add("vslText", string.Format("[drawer] = '{0}AR501' AND [tab] = '{1}' AND [f4] = '{2}'", customerInfo.BranchId, customerInfo.CustomerId, invoiceNumber)); string endPoint = string.Format("{0}{1}/{2}/result?category=DOCUMENT", Configuration.ImagingServerUrl, API_ENDPOINT_VIEW, Configuration.ImagingViewId); System.Net.Http.HttpResponseMessage response = client.PostAsJsonAsync(endPoint, values).Result; if (response.StatusCode.Equals(System.Net.HttpStatusCode.OK) || response.StatusCode.Equals(System.Net.HttpStatusCode.NoContent)) { string rawJson = response.Content.ReadAsStringAsync().Result; ImageNowViewQueryReturnModel jsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <ImageNowViewQueryReturnModel>(rawJson); if (jsonResponse.resultRows.Count == 0) { throw new ApplicationException("Document not found"); } else { List <string> docIds = new List <string>(); foreach (var result in jsonResponse.resultRows) { docIds.AddRange(result.fields.Where(item => item.columnId.Equals("8")).Select(i => i.value).ToList()); } return(docIds); } } else { throw new ApplicationException("Invalid response from server"); } } catch (Exception ex) { _log.WriteErrorLog("Error connecting to the Imaging Server", ex); throw; } } }
// PUT "vendas/corrigevendaserp" // JSON : { idsRecebimento [int] } public static void CorrigeVenda(string token, CorrigeVendasErp param, painel_taxservices_dbContext _dbContext = null) { painel_taxservices_dbContext _db; if (_dbContext == null) { _db = new painel_taxservices_dbContext(); } else { _db = _dbContext; } try { if (param == null) { throw new Exception("Nenhum recebimento foi informado!"); } //string outValue = null; string script = String.Empty; if (param.idsRecebimento == null || param.idsRecebimento.Count == 0) { if (param.data == null) { throw new Exception("O período deve ser informado!"); } // Obtém os recebíveis conciliados baseadas no filtro DateTime dtIni, dtFim; // Usa outros dados if (param.data.Contains("|")) { string[] dts = param.data.Split('|'); dtIni = DateTime.ParseExact(dts[0] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture); dtFim = DateTime.ParseExact(dts[1] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture); } else { dtIni = dtFim = DateTime.ParseExact(param.data + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture); } script = "SELECT R.id" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" + " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" + " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" + //" LEFT JOIN card.tbBandeiraSacado BS on BS.cdGrupo = ER.id_grupo and BS.cdBandeira = R.cdBandeira" + " WHERE R.dtaVenda BETWEEN '" + DataBaseQueries.GetDate(dtIni) + "' AND '" + DataBaseQueries.GetDate(dtFim) + " 23:59:00'" + (param.nrCNPJ != null ? " AND R.cnpj = '" + param.nrCNPJ + "'" : "") + " AND V.dtAjuste IS NULL AND (" + " CONVERT(VARCHAR(10), R.dtaVenda, 120) <> V.dtVenda" + " OR (V.cdAdquirente IS NOT NULL AND R.cdSacado IS NOT NULL AND V.cdSacado IS NOT NULL AND V.cdSacado <> R.cdSacado)" + " OR (R.numParcelaTotal IS NOT NULL AND V.qtParcelas <> R.numParcelaTotal)" + " OR V.vlVenda <> R.valorVendaBruta" + " OR (B.cdAdquirente NOT IN (5, 6, 11, 14) AND SUBSTRING('000000000000' + CONVERT(VARCHAR(12), R.nsu), LEN(R.nsu) + 1, 12) <> SUBSTRING('000000000000' + CONVERT(VARCHAR(12), V.nrNSU), LEN(V.nrNSU) + 1, 12))" + ")"; // Obtém os recebíveis conciliados com divergência que respeitam o filtro param.idsRecebimento = _db.Database.SqlQuery <int>(script).ToList(); if (param.idsRecebimento == null || param.idsRecebimento.Count == 0) { throw new Exception("Não há vendas a serem corrigadas " + (dtIni.Equals(dtFim) ? " em " + dtIni.ToShortDateString() : " no período de " + dtIni.ToShortDateString() + " a " + dtFim.ToShortDateString()) + (param.nrCNPJ != null ? " para a empresa " + param.nrCNPJ : "") + "."); } } else { #region DESCOBRE AS VENDAS QUE PRECISAM SER CORRIGIDAS script = "SELECT R.id" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" + " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" + " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" + //" LEFT JOIN card.tbBandeiraSacado BS on BS.cdGrupo = ER.id_grupo and BS.cdBandeira = R.cdBandeira" + " WHERE R.id IN (" + string.Join(", ", param.idsRecebimento) + ")" + " AND V.dtAjuste IS NULL AND (" + " CONVERT(VARCHAR(10), R.dtaVenda, 120) <> V.dtVenda" + " OR (V.cdAdquirente IS NOT NULL AND R.cdSacado IS NOT NULL AND V.cdSacado IS NOT NULL AND V.cdSacado <> R.cdSacado)" + " OR (R.numParcelaTotal IS NOT NULL AND V.qtParcelas <> R.numParcelaTotal)" + " OR V.vlVenda <> R.valorVendaBruta" + // POLICARD, GETNET, SODEXO e VALECARD não trazem NSU do sitef " OR (B.cdAdquirente NOT IN (5, 6, 11, 14) AND SUBSTRING('000000000000' + CONVERT(VARCHAR(12), R.nsu), LEN(R.nsu) + 1, 12) <> SUBSTRING('000000000000' + CONVERT(VARCHAR(12), V.nrNSU), LEN(V.nrNSU) + 1, 12))" + ")"; param.idsRecebimento = _db.Database.SqlQuery <int>(script).ToList(); #endregion if (param.idsRecebimento == null || param.idsRecebimento.Count == 0) { throw new Exception("Não há vendas a serem corrigadas!"); } } string idsRecebimento = string.Join(", ", param.idsRecebimento); int[] gruposRecebimentos = _db.Database.SqlQuery <int>("SELECT DISTINCT E.id_grupo" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN cliente.empresa E (NOLOCK) ON E.nu_cnpj = R.cnpj" + " WHERE R.id IN (" + idsRecebimento + ")") .ToArray(); if (gruposRecebimentos == null || gruposRecebimentos.Length == 0) { throw new Exception(param.idsRecebimento.Count == 1 ? "Identificador de recebível inexistente!" : "Identificadores de recebíveis inexistentes!"); } //if (gruposRecebimentos.Length < param.idsRecebimento.Count) // throw new Exception("Há " + (param.idsRecebimento.Count - gruposRecebimentos.Length) + ((param.idsRecebimento.Count - gruposRecebimentos.Length) == 1 ? " identificador de recebível inexistente!" : " identificadores de recebíveis inexistentes!")); // GRUPO EMPRESA => OBRIGATÓRIO! Int32 IdGrupo = Permissoes.GetIdGrupo(token, _db); if (IdGrupo == 0) { throw new Exception("Um grupo deve ser selecionado como para a correção das vendas no ERP!"); } if (gruposRecebimentos.Any(t => t != IdGrupo)) { throw new Exception("Permissão negada! " + (gruposRecebimentos.Length == 1 ? "Recebível informado não se refere" : "Recebíveis informados não se referem") + " ao grupo associado ao usuário."); } grupo_empresa grupo_empresa = _db.Database.SqlQuery <grupo_empresa>("SELECT G.*" + " FROM cliente.grupo_empresa G (NOLOCK)" + " WHERE G.id_grupo = " + IdGrupo) .FirstOrDefault(); if (grupo_empresa.dsAPI == null || grupo_empresa.dsAPI.Equals("")) { throw new Exception("Permissão negada! Empresa não possui o serviço ativo"); } SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["painel_taxservices_dbContext"].ConnectionString); List <IDataRecord> resultado; //List<int> idsReceb = new List<int>(); try { connection.Open(); } catch { throw new Exception("Não foi possível estabelecer conexão com a base de dados"); } try { #region AVALIA SE POSSUI ALGUM VENDA CONCILIADO COM MAIS DE UM RECEBÍVEL List <int> idsRecebimentoVenda = _db.Database.SqlQuery <int>("SELECT R.idRecebimentoVenda" + " FROM pos.Recebimento R (NOLOCK)" + " WHERE R.idRecebimentoVenda IS NOT NULL" + " AND R.idRecebimentoVenda IN" + " (SELECT R.idRecebimentoVenda" + " FROM pos.Recebimento R (NOLOCK)" + " WHERE R.id IN (" + idsRecebimento + ")" + " )" + " GROUP BY R.idRecebimentoVenda" + " HAVING COUNT(*) > 1") .ToList(); if (idsRecebimentoVenda.Count > 0) { string error = "Há " + idsRecebimentoVenda.Count + (idsRecebimentoVenda.Count == 1 ? " venda que está conciliada" : " vendas que estão conciliadas") + " com mais de um recebível! Essa relação deve ser de um para um." + Environment.NewLine + (idsRecebimentoVenda.Count == 1 ? " Segue a venda e os correspondentes recebíveis conciliados com ele:" : " Seguem as vendas e os correspondentes recebíveis conciliados com cada uma delas") + Environment.NewLine; // Reporta os vendas e as parcelas.... foreach (int idRecebimentoVenda in idsRecebimentoVenda) { // Obtém as informações da base script = "SELECT R.dtaVenda AS R_dtVenda" + ", R.nsu AS R_nsu" + ", R.valorVendaBruta AS R_vlVenda" + ", R_filial = UPPER(ER.ds_fantasia + CASE WHEN ER.filial IS NULL THEN '' ELSE ' ' + ER.filial END)" + ", B.dsBandeira AS R_dsBandeira" + ", AAR.nmAdquirente AS R_nmAdquirente" + ", R.numParcelaTotal AS R_qtParcelas" + ", V.dtVenda AS V_dtVenda" + ", V.nrNSU AS V_nsu" + ", V.vlVenda AS V_vlVenda" + ", V_filial = UPPER(EV.ds_fantasia + CASE WHEN EV.filial IS NULL THEN '' ELSE ' ' + EV.filial END)" + ", V.dsBandeira AS V_dsBandeira" + ", AAV.nmAdquirente AS V_nmAdquirente" + ", V.qtParcelas AS V_qtParcelas" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" + " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" + " JOIN card.tbAdquirente AAR (NOLOCK) ON AAR.cdAdquirente = B.cdAdquirente" + " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" + " JOIN cliente.empresa EV (NOLOCK) ON EV.nu_cnpj = V.nrCNPJ" + //" JOIN card.tbAdquirente AAV (NOLOCK) ON AAV.cdAdquirente = V.cdAdquirente" + " LEFT JOIN card.tbBandeiraSacado BS ON BS.cdSacado = V.cdSacado AND EV.id_grupo = BS.cdGrupo" + " JOIN card.tbBandeira BV ON BV.cdBandeira = BS.cdBandeira" + " JOIN card.tbAdquirente AAV ON AAV.cdAdquirente = BV.cdAdquirente" + " WHERE R.idRecebimentoVenda = " + idRecebimentoVenda; resultado = DataBaseQueries.SqlQuery(script, connection); error += Environment.NewLine + "==========VENDA========="; if (resultado == null || resultado.Count == 0) { error += Environment.NewLine + " " + idRecebimentoVenda; } else { IDataRecord v = resultado[0]; DateTime V_dtVenda = (DateTime)v["V_dtVenda"]; string V_nsu = Convert.ToString(v["V_nsu"]); decimal V_vlVenda = Convert.ToDecimal(v["V_vlVenda"]); string V_filial = Convert.ToString(v["V_filial"]); string V_bandeira = Convert.ToString(v["V_dsBandeira"].Equals(DBNull.Value) ? "" : v["V_dsBandeira"]); string V_adquirente = Convert.ToString(v["V_nmAdquirente"]); byte V_qtParcelas = Convert.ToByte(v["V_qtParcelas"].Equals(DBNull.Value) ? 0 : v["V_qtParcelas"]); error += Environment.NewLine + "Adquirente: " + V_adquirente; error += Environment.NewLine + "Bandeira: " + V_bandeira; error += Environment.NewLine + "Filial: " + V_filial; error += Environment.NewLine + "Venda em " + V_dtVenda.ToShortDateString() + " no valor de " + V_vlVenda.ToString("C"); error += Environment.NewLine + "NSU: " + V_nsu; error += Environment.NewLine + "Parcelas: " + V_qtParcelas; error += Environment.NewLine; foreach (IDataRecord r in resultado) { DateTime R_dtVenda = (DateTime)r["R_dtVenda"]; string R_nsu = Convert.ToString(r["R_nsu"]); decimal R_vlVenda = Convert.ToDecimal(r["R_vlVenda"]); string R_filial = Convert.ToString(r["R_filial"]); string R_bandeira = Convert.ToString(r["R_dsBandeira"]); string R_adquirente = Convert.ToString(r["R_nmAdquirente"]); int R_qtParcelas = Convert.ToInt32(r["R_qtParcelas"].Equals(DBNull.Value) ? 1 : r["R_qtParcelas"]); error += Environment.NewLine + "=> RECEBÍVEL"; error += Environment.NewLine + " Adquirente: " + R_adquirente; error += Environment.NewLine + " Bandeira: " + R_bandeira; error += Environment.NewLine + " Filial: " + R_filial; error += Environment.NewLine + " Venda em " + R_dtVenda.ToShortDateString() + " no valor de " + R_vlVenda.ToString("C"); error += Environment.NewLine + " NSU: " + R_nsu; error += Environment.NewLine + " Parcelas: " + R_qtParcelas; error += Environment.NewLine; } } } throw new Exception(error); } #endregion } catch (Exception e) { if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao listar realizar a correção das vendas" : erro); } throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message); } finally { try { connection.Close(); } catch { } } if (param.idsRecebimento == null || param.idsRecebimento.Count == 0) { //if (idsReceb.Count == 0) throw new Exception("Não há nenhuma venda para ser corrigida!"); } string url = "http://" + grupo_empresa.dsAPI + DOMINIO; //string url = "http://localhost:50939"; string complemento = "vendas/corrigevendas/" + token; CorrigeVendaERP o = new CorrigeVendaERP(param.idsRecebimento);//idsReceb); HttpContent json = new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json"); HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromMinutes(5); // 5 minutos de timeout client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); System.Net.Http.HttpResponseMessage response = client.PutAsync(complemento, json).Result; //se não retornar com sucesso busca os dados if (!response.IsSuccessStatusCode) { string resp = String.Empty; try { resp = response.Content.ReadAsAsync <string>().Result; } catch { throw new Exception("Serviço indisponível no momento"); } if (resp != null && !resp.Trim().Equals("")) { throw new Exception(((int)response.StatusCode) + " - " + resp); } throw new Exception(((int)response.StatusCode) + ""); } // Avalia se alguma venda teve que inserir dados script = "SELECT V.*" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN card.tbRecebimentoVenda V ON R.idRecebimentoVenda = V.idRecebimentoVenda" + " WHERE R.id IN (" + idsRecebimento + ")" + " AND V.dsMensagem IS NOT NULL"; try { tbRecebimentoVenda[] vendas = _db.Database.SqlQuery <tbRecebimentoVenda>(script).ToArray(); if (vendas.Length > 0) { string result = String.Empty; //foreach (tbRecebimentoVenda venda in vendas) //{ // result += "NSU: " + venda.nrNSU + Environment.NewLine + // (venda.cdSacado != null ? "Sacado : " + venda.cdSacado + Environment.NewLine : "") + // "Valor: " + venda.vlVenda.ToString("C") + Environment.NewLine + // "Parcelas: " + venda.qtParcelas + Environment.NewLine + // "Mensagem: '" + venda.dsMensagem + "'" + // Environment.NewLine + Environment.NewLine; //} //throw new Exception("Vendas corrigidas que precisam ser corrigidas manualmente no sistema do cliente: " + // Environment.NewLine + Environment.NewLine + result); if (vendas.Length == 1) { result = "Há 1 venda que precisa ser corrigida manualmente no sistema do cliente."; } else { result = "Há " + vendas.Length + " vendas que precisam ser corrigidas manualmente no sistema do cliente."; } result += Environment.NewLine + "Por favor, acesse a tela ADMINISTRATIVO > INTEGRAÇÃO ERP > VENDAS" + " e seleciono como filtro de TIPO a opção CORREÇÃO MANUAL " + " usando como filtro de data o mesmo período selecionado aqui na Conciliação de Vendas."; throw new Exception(result); } } catch (Exception e) { if (e.Message.StartsWith("Há") && e.Message.Contains("Por favor, acesse a tela ADMINISTRATIVO > INTEGRAÇÃO ERP > VENDAS")) { throw new Exception(e.Message); } throw new Exception("Falha de comunicação com o servidor"); } } catch (Exception e) { if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao realizar a correção das vendas" : erro); } throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message); } }
public BugState create(string bugsummary, string errordetails, BugState bg) { string tktID = null; string tkyKey = null; string state = ""; string issuetype = ""; string closedtktID = null; string closedtkyKey = null; bg.bugclosed = false; bg.bugexists = false; bg.bugopen = false; //Checking whether the Bug already exists, if true, do not create a new ticket HttpClient client2 = new HttpClient(); string issueurl = ("https://spiderlogic.jira.com/rest/api/2/search?jql=project=SFLOW&fields=issues&fields=summary&fields=description&fields=status&fields=project&fields=issuetype"); var credentials = Encoding.ASCII.GetBytes("[email protected]:spiderqa"); client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials)); Uri uri = new Uri(issueurl.ToString()); string ApiResponse = client2.GetStringAsync(uri).Result; var root = JsonConvert.DeserializeObject <RootObject>(ApiResponse); var Sumry = root.issues.Count; //Checking if the user story already exists by iterating though the issue list in jira var issues = root.issues; Debug.WriteLine("Upali Debug: "); foreach (var issue in issues) { var fields = issue.fields; var summary = (fields.summary).ToString(); state = (fields.status.name).ToString(); issuetype = (fields.issuetype.name).ToString(); if ((issuetype == "Bug") & summary.Equals(bugsummary)) { if (state == "Open") { // the control may not go to if block ever if (bg.bugclosed) { Console.WriteLine("In BugCreate: Bug OPened after closed "); bg.bugexists = true; Console.WriteLine("Ticket Key: " + issue.key); } else { Console.WriteLine("In BugCreate : Bug exists"); bg.bugexists = true; tktID = issue.id; tkyKey = issue.key; Console.WriteLine("Ticket Key: " + issue.key); bg.bugopen = true; } } else if (state == "Closed") { if (bg.bugopen) { Console.WriteLine("In BugCreate: Bug closed and ALSO REOPENED"); bg.bugexists = true; bg.bugclosed = true; bg.bugclosedcount = bg.bugclosedcount + 1; bg.buglist.Add(closedtkyKey); } else { Console.WriteLine("In BugCreate: Bug exists bug closed "); bg.bugexists = false; closedtktID = issue.id; closedtkyKey = issue.key; bg.bugclosed = true; bg.closedtkyKey = issue.key; bg.bugclosedcount = bg.bugclosedcount + 1; bg.buglist.Add(closedtkyKey); } } } } //If the Bug not exist, create a new user story by using the POST method in JIRA via API if (bg.bugexists == false) { //The fields required to create a new JIRA ticket var data = new CreateIssue(); data.fields.project.key = "SFLOW"; data.fields.summary = bugsummary; data.fields.description = errordetails; data.fields.issuetype.name = "Bug"; string postUrl = "https://spiderlogic.jira.com/rest/api/latest/"; System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new System.Uri(postUrl); byte[] cred = UTF8Encoding.UTF8.GetBytes("[email protected]:spiderqa"); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred)); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent <CreateIssue>(data, jsonFormatter); System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; Console.Write(result); } else { Console.Write(response.StatusCode.ToString()); Console.ReadLine(); } } return(bg); }
// Blog Comment public void InsertBlogComment(MovieComment blogComment) { blogComment.IsPublic = false; blogComment.DateCreated = DateTime.Now; db.MovieComments.Add(blogComment); db.SaveChanges(); try { var movie = db.Movies.FirstOrDefault(m => m.MovieID == blogComment.MovieID); var subject = "有新的评论需要审核-bt.henhaoji.com.cn"; var message = string.Format("<p>Hi {0},</p>" + "<p>评论信息:</p>" + "{1}" + "<p>文章: <a href='http://bt.henhaoji.com.cn/{2}'>{3}</a></p>" + "<p><a href='http://bt.henhaoji.com.cn/admin/blog/PendingComments'>点击审核</a></p>", blogComment.Name, blogComment.Message, movie.Slug, movie.MovieTitle ); //BtVideo.Models.Others.MailBag mailBag = new BtVideo.Models.Others.MailBag(); //mailBag.ToMailAddress = "*****@*****.**"; ////mailBag.CcMailAddress = ""; //mailBag.Subject = subject; //mailBag.Message = message; //mailBag.Send(true); IDictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("apiUser", "henhaoji"); parameters.Add("apiKey", "Nca7r8U1ho2eYXpX"); parameters.Add("from", "*****@*****.**"); parameters.Add("fromName", "很好记bt"); parameters.Add("to", "*****@*****.**"); parameters.Add("subject", subject); parameters.Add("html", message); using (var client = new System.Net.Http.HttpClient()) { client.BaseAddress = new Uri("http://api.sendcloud.net"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HTTP GET HttpResponseMessage response = new System.Net.Http.HttpResponseMessage(); response = client.PostAsync("/apiv2/mail/send", new FormUrlEncodedContent(parameters)).Result; var product = ""; if (response.IsSuccessStatusCode) { product = response.Content.ReadAsStringAsync().Result; } } } catch (Exception e) { LogHelper.WriteLog("添加评论发邮件错误", e.Message); } }
public void ApproveBlogComment(int commentID) { var c = db.MovieComments.FirstOrDefault(m => m.CommentID == commentID); try { c.IsPublic = true; db.SaveChanges(); } catch (Exception e) { LogHelper.WriteLog("pinglun:", e.StackTrace + e.Message + e.Source); } // notify posting user try { var subject = "您的评论已经审核通过-bt.henhaoji.com.cn"; var message = string.Format("<p>Hi {0},</p>" + "<p>您的评论已经被审核通过:</p>" + "{1}" + "<p>文章: <a href='http://bt.henhaoji.com.cn/{2}'>{3}</a></p>", c.Name, c.Message, c.Movie.Slug, c.Movie.MovieTitle ); IDictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("apiUser", "henhaoji"); parameters.Add("apiKey", "Nca7r8U1ho2eYXpX"); parameters.Add("from", "*****@*****.**"); parameters.Add("fromName", "很好记bt"); parameters.Add("to", c.Email); parameters.Add("subject", subject); parameters.Add("html", message); using (var client = new System.Net.Http.HttpClient()) { client.BaseAddress = new Uri("http://api.sendcloud.net"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HTTP GET HttpResponseMessage response = new System.Net.Http.HttpResponseMessage(); response = client.PostAsync("/apiv2/mail/send", new FormUrlEncodedContent(parameters)).Result; var product = ""; if (response.IsSuccessStatusCode) { product = response.Content.ReadAsStringAsync().Result; } } } catch (Exception e) { } }
/// <summary> /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the /// header of the request, via a parameter group /// </summary> /// <param name='headerCustomNamedRequestIdParamGroupingParameters'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationHeaderResponse <HeaderCustomNamedRequestIdParamGroupingHeadersInner> > CustomNamedRequestIdParamGroupingWithHttpMessagesAsync(HeaderCustomNamedRequestIdParamGroupingParametersInner headerCustomNamedRequestIdParamGroupingParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (headerCustomNamedRequestIdParamGroupingParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "headerCustomNamedRequestIdParamGroupingParameters"); } if (headerCustomNamedRequestIdParamGroupingParameters != null) { headerCustomNamedRequestIdParamGroupingParameters.Validate(); } string fooClientRequestId = default(string); if (headerCustomNamedRequestIdParamGroupingParameters != null) { fooClientRequestId = headerCustomNamedRequestIdParamGroupingParameters.FooClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("fooClientRequestId", fooClientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestIdParamGrouping", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestIdParamGrouping").ToString(); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (fooClientRequestId != null) { if (_httpRequest.Headers.Contains("foo-client-request-id")) { _httpRequest.Headers.Remove("foo-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse <HeaderCustomNamedRequestIdParamGroupingHeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("foo-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <HeaderCustomNamedRequestIdParamGroupingHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async Task SendDelivered_request() { //bool status = false; try { for (int i = 0; i < MealDeliveredCollection.Count; i++) { mstr_mealdelivered mealdelivered = MealDeliveredCollection.ElementAt(i); if (mealdelivered.is_checked) { string order_id = mealdelivered.OrderedID.ToString(); string mealtime = mealdelivered.MealTime; string nullvalue = ""; string meatype = mealtime; string meal_time = ""; if (meatype.ToLowerInvariant() == "Breakfast".ToLowerInvariant()) { meal_time = "BF"; } else if (meatype.ToLowerInvariant() == "Lunch".ToLowerInvariant()) { meal_time = "LH"; } else if (meatype.ToLowerInvariant() == "Dinner".ToLowerInvariant()) { meal_time = "DN"; } else { meal_time = meatype; } // String url = Gloabal.URL + Gloabal.METHODE_SETDELIVEREDSTATUS + "/" + orderid + "/" + Uri.encode(mealtime) + "/" + mealtimeid + "/" + paymentmode_id + "/" + Uri.encode(payment_remark); //--------POST----------- dynamic p = new JObject(); p.MealTime = meal_time; p.meal_time_id = Convert.ToString(SelectedMealTime.ID); p.mode_of_payment = 0; p.orderId = order_id; p.payment_remark = nullvalue; // var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(p)); string stringPayload = JsonConvert.SerializeObject(p); // Wrap our JSON inside a StringContent which then can be used by the HttpClient class var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json"); // display a message jason conversion //var message1 = new MessageDialog("Data is converted in json."); //await message1.ShowAsync(); using (var httpClient = new System.Net.Http.HttpClient()) { var httpResponse = new System.Net.Http.HttpResponseMessage(); httpResponse = await httpClient.PostAsync(Library.URL + "/" + Library.METHODE_SETDELIVEREDSTATUS, httpContent); if (httpResponse.Content != null) { var responseContent = await httpResponse.Content.ReadAsStringAsync(); success = true; } } } } } catch (Exception exp) { await PageDialog.DisplayAlertAsync("Alert!!", exp.Message, "OK"); //await DisplayAlert("", AppResources.ResourceManager.GetString(excp.Message, CultureInfo.CurrentCulture), "OK"); } }
protected override void Delete(int id, System.Net.Http.HttpResponseMessage response) { DeleteCalled = true; }
/// <summary> /// send globalStringPath='globalStringPath', /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery='globalStringQuery', /// pathItemStringQuery='pathItemStringQuery', /// localStringQuery='localStringQuery' /// </summary> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain value 'localStringQuery' /// </param> /// <param name='pathItemStringQuery'> /// A string value 'pathItemStringQuery' that appears as a query parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> GetAllWithValuesWithHttpMessagesAsync(string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (localStringPath == null) { throw new ValidationException(ValidationRules.CannotBeNull, "localStringPath"); } if (pathItemStringPath == null) { throw new ValidationException(ValidationRules.CannotBeNull, "pathItemStringPath"); } if (Client.GlobalStringPath == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.GlobalStringPath"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("localStringPath", localStringPath); tracingParameters.Add("localStringQuery", localStringQuery); tracingParameters.Add("pathItemStringPath", pathItemStringPath); tracingParameters.Add("pathItemStringQuery", pathItemStringQuery); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetAllWithValues", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/globalStringQuery/pathItemStringQuery/localStringQuery").ToString(); _url = _url.Replace("{localStringPath}", System.Uri.EscapeDataString(localStringPath)); _url = _url.Replace("{pathItemStringPath}", System.Uri.EscapeDataString(pathItemStringPath)); _url = _url.Replace("{globalStringPath}", System.Uri.EscapeDataString(Client.GlobalStringPath)); List <string> _queryParameters = new List <string>(); if (localStringQuery != null) { _queryParameters.Add(string.Format("localStringQuery={0}", System.Uri.EscapeDataString(localStringQuery))); } if (pathItemStringQuery != null) { _queryParameters.Add(string.Format("pathItemStringQuery={0}", System.Uri.EscapeDataString(pathItemStringQuery))); } if (Client.GlobalStringQuery != null) { _queryParameters.Add(string.Format("globalStringQuery={0}", System.Uri.EscapeDataString(Client.GlobalStringQuery))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
// GET /api/Contacts/5 public HttpResponseMessage<Contact> Get(int id) { var contact = _contactRepository.Get().Where(y => y.Id == id).SingleOrDefault(); var statusCode = contact != null ? HttpStatusCode.OK : HttpStatusCode.NotFound; var response = new HttpResponseMessage<Contact>(contact, statusCode); return response; }