protected GitEndPointResponseData SendRequest( long requestId, Uri requestUri, HttpMethod httpMethod, string requestContent, CancellationToken cancellationToken, MediaTypeWithQualityHeaderValue acceptType = null) { string authString; string errorMessage; if (!this.authentication.TryGetCredentials(this.Tracer, out authString, out errorMessage)) { return(new GitEndPointResponseData( HttpStatusCode.Unauthorized, new GitObjectsHttpException(HttpStatusCode.Unauthorized, errorMessage), shouldRetry: true, message: null, onResponseDisposed: null)); } HttpRequestMessage request = new HttpRequestMessage(httpMethod, requestUri); request.Headers.UserAgent.Add(this.userAgentHeader); if (!string.IsNullOrEmpty(authString)) { request.Headers.Authorization = new AuthenticationHeaderValue("Basic", authString); } if (acceptType != null) { request.Headers.Accept.Add(acceptType); } if (requestContent != null) { request.Content = new StringContent(requestContent, Encoding.UTF8, "application/json"); } EventMetadata responseMetadata = new EventMetadata(); responseMetadata.Add("RequestId", requestId); responseMetadata.Add("availableConnections", availableConnections.CurrentCount); Stopwatch requestStopwatch = Stopwatch.StartNew(); availableConnections.Wait(cancellationToken); TimeSpan connectionWaitTime = requestStopwatch.Elapsed; TimeSpan responseWaitTime = default(TimeSpan); GitEndPointResponseData gitEndPointResponseData = null; HttpResponseMessage response = null; try { requestStopwatch.Restart(); try { response = this.client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).GetAwaiter().GetResult(); } finally { responseWaitTime = requestStopwatch.Elapsed; } responseMetadata.Add("CacheName", GetSingleHeaderOrEmpty(response.Headers, "X-Cache-Name")); responseMetadata.Add("StatusCode", response.StatusCode); if (response.StatusCode == HttpStatusCode.OK) { string contentType = GetSingleHeaderOrEmpty(response.Content.Headers, "Content-Type"); responseMetadata.Add("ContentType", contentType); this.authentication.ConfirmCredentialsWorked(authString); Stream responseStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); gitEndPointResponseData = new GitEndPointResponseData( response.StatusCode, contentType, responseStream, message: response, onResponseDisposed: () => availableConnections.Release()); } else { errorMessage = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); int statusInt = (int)response.StatusCode; if (string.IsNullOrWhiteSpace(errorMessage)) { if (response.StatusCode == HttpStatusCode.Unauthorized) { this.authentication.Revoke(authString); if (!this.authentication.IsBackingOff) { errorMessage = "Server returned error code 401 (Unauthorized). Your PAT may be expired and we are asking for a new one."; } else { errorMessage = "Server returned error code 401 (Unauthorized) after successfully renewing your PAT. You may not have access to this repo"; } } else { errorMessage = string.Format("Server returned error code {0} ({1})", statusInt, response.StatusCode); } } gitEndPointResponseData = new GitEndPointResponseData( response.StatusCode, new GitObjectsHttpException(response.StatusCode, errorMessage), ShouldRetry(response.StatusCode), message: response, onResponseDisposed: () => availableConnections.Release()); } } catch (TaskCanceledException) { cancellationToken.ThrowIfCancellationRequested(); errorMessage = string.Format("Request to {0} timed out", requestUri); gitEndPointResponseData = new GitEndPointResponseData( HttpStatusCode.RequestTimeout, new GitObjectsHttpException(HttpStatusCode.RequestTimeout, errorMessage), shouldRetry: true, message: response, onResponseDisposed: () => availableConnections.Release()); } catch (WebException ex) { gitEndPointResponseData = new GitEndPointResponseData( HttpStatusCode.InternalServerError, ex, shouldRetry: true, message: response, onResponseDisposed: () => availableConnections.Release()); } finally { responseMetadata.Add("connectionWaitTimeMS", $"{connectionWaitTime.TotalMilliseconds:F4}"); responseMetadata.Add("responseWaitTimeMS", $"{responseWaitTime.TotalMilliseconds:F4}"); this.Tracer.RelatedEvent(EventLevel.Informational, "NetworkResponse", responseMetadata); if (gitEndPointResponseData == null) { // If gitEndPointResponseData is null there was an unhandled exception if (response != null) { response.Dispose(); } availableConnections.Release(); } } return(gitEndPointResponseData); }
public void GetEntryInODataJsonVerboseFormat() { // Arrange using (HttpConfiguration configuration = CreateConfiguration()) using (HttpServer host = new HttpServer(configuration)) using (HttpClient client = new HttpClient(host)) using (HttpRequestMessage request = CreateRequestWithDataServiceVersionHeaders("People(10)", MediaTypeWithQualityHeaderValue.Parse("application/json;odata=verbose"))) // Act using (HttpResponseMessage response = client.SendAsync(request).Result) { // Assert AssertODataVersion3JsonResponse(Resources.PersonEntryInJsonVerbose, response); } }
private void CheckInvalidParse(string input) { Assert.Throws <FormatException>(() => { MediaTypeWithQualityHeaderValue.Parse(input); }); }
public SearchClient(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger(nameof(SearchClient)) ?? throw new ArgumentNullException(nameof(loggerFactory)); var handlerWithDecompression = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }; this.client = new HttpClient(handlerWithDecompression) { BaseAddress = new Uri("http://www.google.com"), DefaultRequestHeaders = { Accept = { MediaTypeWithQualityHeaderValue.Parse("text/html"), MediaTypeWithQualityHeaderValue.Parse("application/xhtml+xml"), MediaTypeWithQualityHeaderValue.Parse("application/xml") }, AcceptEncoding = { StringWithQualityHeaderValue.Parse("gzip"), StringWithQualityHeaderValue.Parse("deflate") }, UserAgent = { ProductInfoHeaderValue.Parse("Chrome/10.0.648.151") } } }; }
public async Task CanContinueOnErrorWhenHeaderSet() { // Arrange var requestUri = string.Format("{0}/UnbufferedBatch/$batch", this.BaseAddress); string absoluteUri = this.BaseAddress + "/UnbufferedBatch/UnbufferedBatchCustomer"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("multipart/mixed")); request.Headers.Add("prefer", "odata.continue-on-error"); HttpContent content = new StringContent( @"--batch_abbe2e6f-e45b-4458-9555-5fc70e3aebe0 Content-Type: application/http Content-Transfer-Encoding: binary GET " + absoluteUri + @"(0) HTTP/1.1 --batch_abbe2e6f-e45b-4458-9555-5fc70e3aebe0 Content-Type: application/http Content-Transfer-Encoding: binary GET " + absoluteUri + @"(-1) HTTP/1.1 --batch_abbe2e6f-e45b-4458-9555-5fc70e3aebe0 Content-Type: application/http Content-Transfer-Encoding: binary GET " + absoluteUri + @"(1) HTTP/1.1 --batch_abbe2e6f-e45b-4458-9555-5fc70e3aebe0-- "); content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/mixed; boundary=batch_abbe2e6f-e45b-4458-9555-5fc70e3aebe0"); request.Content = content; // Act HttpResponseMessage response = await Client.SendAsync(request); var stream = await response.Content.ReadAsStreamAsync(); IODataResponseMessage odataResponseMessage = new ODataMessageWrapper(stream, response.Content.Headers); int subResponseCount = 0; // Assert using (var messageReader = new ODataMessageReader(odataResponseMessage, new ODataMessageReaderSettings(), GetEdmModel(new ODataConventionModelBuilder()))) { var batchReader = messageReader.CreateODataBatchReader(); while (batchReader.Read()) { switch (batchReader.State) { case ODataBatchReaderState.Operation: var operationMessage = batchReader.CreateOperationResponseMessage(); subResponseCount++; if (subResponseCount == 2) { Assert.Equal(500, operationMessage.StatusCode); } else { Assert.Equal(200, operationMessage.StatusCode); } break; } } } Assert.Equal(3, subResponseCount); }
public void Quality_GreaterThanOne_Throw() { MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("application/xml"); Assert.Throws <ArgumentOutOfRangeException>(() => { mediaType.Quality = 1.01; }); }
public Request Accept(MediaTypeWithQualityHeaderValue accept) { _hdrAccept.Add(accept); return(this); }
public void SortMediaTypeWithQualityHeaderValuesByQFactor_SortsCorrectly(IEnumerable <string> unsorted, IEnumerable <string> expectedSorted) { // Arrange MockContentNegotiator negotiator = new MockContentNegotiator(); List <MediaTypeWithQualityHeaderValue> unsortedValues = new List <MediaTypeWithQualityHeaderValue>(unsorted.Select(u => MediaTypeWithQualityHeaderValue.Parse(u))); List <MediaTypeWithQualityHeaderValue> expectedSortedValues = new List <MediaTypeWithQualityHeaderValue>(expectedSorted.Select(u => MediaTypeWithQualityHeaderValue.Parse(u))); // Act IEnumerable <MediaTypeWithQualityHeaderValue> actualSorted = negotiator.SortMediaTypeWithQualityHeaderValuesByQFactor(unsortedValues); // Assert Assert.True(expectedSortedValues.SequenceEqual(actualSorted)); }
public RepositoryClinica() { this.url = "https://proyectoapiclinicatajamar.azurewebsites.net/"; //this.url = "https://localhost:44389/"; this.header = new MediaTypeWithQualityHeaderValue("application/json"); }
public void QueriesWorkOnAliasedModels() { IEnumerable <Customer> customers = Enumerable.Range(0, 10).Select(i => new Customer { Id = i, ClientName = "Customer Name " + i, FinancialAddress = new Location.Direction { FirstLine = "Billing First line" + i, SecondLine = "Billing Second line " + i, ZipCode = i * 5, City = "Billing City " + i, Reign = new Location.PoliticalRegion { CountryOrRegion = "Billing Region CountryOrRegion" + i, State = "Billing Region State" + i } }, DefaultShippingAddress = new Location.Direction { FirstLine = "DefaultShipping First line" + i, SecondLine = "DefaultShipping Second line " + i, ZipCode = i * 5, City = "DefaultShipping City " + i, Reign = new Location.PoliticalRegion { CountryOrRegion = "DefaultShipping Region CountryOrRegion" + i, State = "DefaultShipping Region State" + i } }, Purchases = new System.Collections.ObjectModel.Collection <AliasedNamespace.Order>(Enumerable.Range(0, i).Select <int, AliasedNamespace.Order>(j => { switch (j % 3) { case 0: return(new AliasedNamespace.Order { Id = i * 10 + j, PurchaseDate = DateTime.Today.Subtract(TimeSpan.FromDays(i * 10 + j)), ShippingAddress = new Location.Direction { FirstLine = "Order Shipping First line" + i, SecondLine = "Order Shipping Second line " + i, ZipCode = i * 5, City = "Order Shipping City " + i, Reign = new Location.PoliticalRegion { CountryOrRegion = "Order Shipping Region CountryOrRegion" + i, State = "Order Shipping Region State" + i } }, Details = new System.Collections.ObjectModel.Collection <Billing.OrderLine>(Enumerable.Range(0, j).Select(k => new Billing.OrderLine { Id = i * 100 + j * 10 + k, Ammount = i * 100 + j * 10 + k, Cost = i * 100 + j * 10 + k, Product = new Purchasing.Product { Id = i * 100 + j * 10 + k, ProductName = "Product " + i * 100 + j * 10 + k, AvailableRegions = new System.Collections.ObjectModel.Collection <Location.PoliticalRegion>(Enumerable.Range(0, k).Select(l => new Location.PoliticalRegion { CountryOrRegion = "Product CountryOrRegion " + 1000 * i + 100 * j + 10 * k + l, State = "Product State " + 1000 * i + 100 * j + 10 * k + l }).ToList()) } }).ToList()) }); case 1: return(new Purchasing.ExpressOrder { Id = i * 10 + j, PurchaseDate = DateTime.Today.Subtract(TimeSpan.FromDays(i * 10 + j)), ShippingAddress = new Location.Direction { FirstLine = "Order Shipping First line" + i, SecondLine = "Order Shipping Second line " + i, ZipCode = i * 5, City = "Order Shipping City " + i, Reign = new Location.PoliticalRegion { CountryOrRegion = "Order Shipping Region CountryOrRegion" + i, State = "Order Shipping Region State" + i } }, DeliveryDate = DateTime.Today.Subtract(TimeSpan.FromDays(i * 10 + j)), Details = new System.Collections.ObjectModel.Collection <Billing.OrderLine>(Enumerable.Range(0, j).Select(k => new Billing.OrderLine { Id = i * 100 + j * 10 + k, Ammount = i * 100 + j * 10 + k, Cost = i * 100 + j * 10 + k, Product = new Purchasing.Product { Id = i * 100 + j * 10 + k, ProductName = "Product " + i * 100 + j * 10 + k, AvailableRegions = new System.Collections.ObjectModel.Collection <Location.PoliticalRegion>(Enumerable.Range(0, k).Select(l => new Location.PoliticalRegion { CountryOrRegion = "Product CountryOrRegion " + 1000 * i + 100 * j + 10 * k + l, State = "Product State " + 1000 * i + 100 * j + 10 * k + l }).ToList()) } }).ToList()) }); case 2: return(new Purchasing.FreeDeliveryOrder { Id = i * 10 + j, PurchaseDate = DateTime.Today.Subtract(TimeSpan.FromDays(i * 10 + j)), ShippingAddress = new Location.Direction { FirstLine = "Order Shipping First line" + i, SecondLine = "Order Shipping Second line " + i, ZipCode = i * 5, City = "Order Shipping City " + i, Reign = new Location.PoliticalRegion { CountryOrRegion = "Order Shipping Region CountryOrRegion" + i, State = "Order Shipping Region State" + i } }, Details = new System.Collections.ObjectModel.Collection <Billing.OrderLine>(Enumerable.Range(0, j).Select(k => new Billing.OrderLine { Id = i * 100 + j * 10 + k, Ammount = i * 100 + j * 10 + k, Cost = i * 100 + j * 10 + k, Product = new Purchasing.Product { Id = i * 100 + j * 10 + k, ProductName = "Product " + i * 100 + j * 10 + k, AvailableRegions = new System.Collections.ObjectModel.Collection <Location.PoliticalRegion>(Enumerable.Range(0, k).Select(l => new Location.PoliticalRegion { CountryOrRegion = "Product CountryOrRegion " + 1000 * i + 100 * j + 10 * k + l, State = "Product State " + 1000 * i + 100 * j + 10 * k + l }).ToList()) } }).ToList()) }); default: throw new ArgumentOutOfRangeException("j"); } }).ToList()) }); string expand = "$expand=Purchases($select=Details;$expand=Details($select=Product;$expand=Product($select=AvailableRegions)))"; string filter = "$filter=FinancialAddress/ZipCode le 30 and startswith(FinancialAddress/Reign/CountryOrRegion,'Billing Region CountryOrRegion')"; string orderBy = "$orderby=DefaultShippingAddress/Reign/State desc, FinancialAddress/ZipCode asc"; string select = "$select=Id"; string query = string.Format("?{0}&{1}&{2}&{3}", expand, filter, orderBy, select); customers = customers.Where(c => c.FinancialAddress.ZipCode <= 30 && c.FinancialAddress.Reign.CountryOrRegion.StartsWith("Billing Region CountryOrRegion")) .OrderByDescending(c => c.DefaultShippingAddress.Reign.State).ThenBy(c => c.FinancialAddress.ZipCode); var projectedCustomers = customers.Select(c => new { Purchases = c.Purchases.Select(p => new { Details = p.Details.Select(d => new { Product = new { AvailableRegions = d.Product.AvailableRegions } }) }), Id = c.Id }); dynamic jsonCustomers = JToken.FromObject(projectedCustomers); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseAddress + "/convention/ModelAliasingQueryCustomers" + query); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata.metadata=none")); HttpResponseMessage response = Client.SendAsync(request).Result; dynamic queriedObject = JObject.Parse(response.Content.ReadAsStringAsync().Result); Assert.Equal(jsonCustomers, queriedObject.value, JToken.EqualityComparer); }
public void GetSingletonInODataJsonLightFormat(string metadata, string expect) { // Arrange using (HttpConfiguration configuration = CreateConfiguration()) using (HttpServer host = new HttpServer(configuration)) using (HttpClient client = new HttpClient(host)) using (HttpRequestMessage request = CreateRequestWithDataServiceVersionHeaders("President", MediaTypeWithQualityHeaderValue.Parse(metadata))) // Act using (HttpResponseMessage response = client.SendAsync(request).Result) { // Assert AssertODataVersion4JsonResponse(Resources.GetString(expect), response); } }
private static string[] GetAcceptHeaders(HttpRequest contextRequest) => Array.ConvertAll( contextRequest.Headers.GetCommaSeparatedValues("Accept"), value => MediaTypeWithQualityHeaderValue.TryParse(value, out var header) ? header.MediaType : null);
/// <summary> /// Derived classes implement this to return an API version from the specified media type string. /// </summary> /// <param name="mediaType">The media type containing the version number.</param> /// <returns> /// Returns the version number specified in the accept header. /// </returns> protected abstract string GetVersion(MediaTypeWithQualityHeaderValue mediaType);
protected GitEndPointResponseData SendRequest( long requestId, Uri requestUri, HttpMethod httpMethod, string requestContent, CancellationToken cancellationToken, MediaTypeWithQualityHeaderValue acceptType = null) { string authString = null; string errorMessage; if (!this.authentication.IsAnonymous && !this.authentication.TryGetCredentials(this.Tracer, out authString, out errorMessage)) { return(new GitEndPointResponseData( HttpStatusCode.Unauthorized, new GitObjectsHttpException(HttpStatusCode.Unauthorized, errorMessage), shouldRetry: true, message: null, onResponseDisposed: null)); } HttpRequestMessage request = new HttpRequestMessage(httpMethod, requestUri); // By default, VSTS auth failures result in redirects to SPS to reauthenticate. // To provide more consistent behavior when using the GCM, have them send us 401s instead request.Headers.Add("X-TFS-FedAuthRedirect", "Suppress"); request.Headers.UserAgent.Add(this.userAgentHeader); if (!this.authentication.IsAnonymous) { request.Headers.Authorization = new AuthenticationHeaderValue("Basic", authString); } if (acceptType != null) { request.Headers.Accept.Add(acceptType); } if (requestContent != null) { request.Content = new StringContent(requestContent, Encoding.UTF8, "application/json"); } EventMetadata responseMetadata = new EventMetadata(); responseMetadata.Add("RequestId", requestId); responseMetadata.Add("availableConnections", availableConnections.CurrentCount); Stopwatch requestStopwatch = Stopwatch.StartNew(); availableConnections.Wait(cancellationToken); TimeSpan connectionWaitTime = requestStopwatch.Elapsed; TimeSpan responseWaitTime = default(TimeSpan); GitEndPointResponseData gitEndPointResponseData = null; HttpResponseMessage response = null; try { requestStopwatch.Restart(); try { response = this.client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).GetAwaiter().GetResult(); } finally { responseWaitTime = requestStopwatch.Elapsed; } responseMetadata.Add("CacheName", GetSingleHeaderOrEmpty(response.Headers, "X-Cache-Name")); responseMetadata.Add("StatusCode", response.StatusCode); if (response.StatusCode == HttpStatusCode.OK) { string contentType = GetSingleHeaderOrEmpty(response.Content.Headers, "Content-Type"); responseMetadata.Add("ContentType", contentType); if (!this.authentication.IsAnonymous) { this.authentication.ApproveCredentials(this.Tracer, authString); } Stream responseStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); gitEndPointResponseData = new GitEndPointResponseData( response.StatusCode, contentType, responseStream, message: response, onResponseDisposed: () => availableConnections.Release()); } else { errorMessage = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); int statusInt = (int)response.StatusCode; bool shouldRetry = ShouldRetry(response.StatusCode); if (response.StatusCode == HttpStatusCode.Unauthorized && this.authentication.IsAnonymous) { shouldRetry = false; errorMessage = "Anonymous request was rejected with a 401"; } else if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.Redirect) { this.authentication.RejectCredentials(this.Tracer, authString); if (!this.authentication.IsBackingOff) { errorMessage = string.Format("Server returned error code {0} ({1}). Your PAT may be expired and we are asking for a new one. Original error message from server: {2}", statusInt, response.StatusCode, errorMessage); } else { errorMessage = string.Format("Server returned error code {0} ({1}) after successfully renewing your PAT. You may not have access to this repo. Original error message from server: {2}", statusInt, response.StatusCode, errorMessage); } } else { errorMessage = string.Format("Server returned error code {0} ({1}). Original error message from server: {2}", statusInt, response.StatusCode, errorMessage); } gitEndPointResponseData = new GitEndPointResponseData( response.StatusCode, new GitObjectsHttpException(response.StatusCode, errorMessage), shouldRetry, message: response, onResponseDisposed: () => availableConnections.Release()); } } catch (TaskCanceledException) { cancellationToken.ThrowIfCancellationRequested(); errorMessage = string.Format("Request to {0} timed out", requestUri); gitEndPointResponseData = new GitEndPointResponseData( HttpStatusCode.RequestTimeout, new GitObjectsHttpException(HttpStatusCode.RequestTimeout, errorMessage), shouldRetry: true, message: response, onResponseDisposed: () => availableConnections.Release()); } catch (HttpRequestException httpRequestException) when(httpRequestException.InnerException is System.Security.Authentication.AuthenticationException) { // This exception is thrown on OSX, when user declines to give permission to access certificate gitEndPointResponseData = new GitEndPointResponseData( HttpStatusCode.Unauthorized, httpRequestException.InnerException, shouldRetry: false, message: response, onResponseDisposed: () => availableConnections.Release()); } catch (WebException ex) { gitEndPointResponseData = new GitEndPointResponseData( HttpStatusCode.InternalServerError, ex, shouldRetry: true, message: response, onResponseDisposed: () => availableConnections.Release()); } finally { responseMetadata.Add("connectionWaitTimeMS", $"{connectionWaitTime.TotalMilliseconds:F4}"); responseMetadata.Add("responseWaitTimeMS", $"{responseWaitTime.TotalMilliseconds:F4}"); this.Tracer.RelatedEvent(EventLevel.Informational, "NetworkResponse", responseMetadata); if (gitEndPointResponseData == null) { // If gitEndPointResponseData is null there was an unhandled exception if (response != null) { response.Dispose(); } availableConnections.Release(); } } return(gitEndPointResponseData); }
public ModeloClientes() { this.urlapi = new Uri("http://localhost:63386/"); media = new MediaTypeWithQualityHeaderValue("application/json"); }
public async Task <IActionResult> Edit(long id, [Bind("Fohid,PaymentSourceAccountId,PaymentSourceAccountCode,Amount,Description,IsActive,DateAdded,DateUpdated,AddedBy,UpdatedBy")] FactoryOverheadExpenseVM factoryOverheadExpenseVM) { HttpClient client = _helperAPI.InitializeClient(); if (id != factoryOverheadExpenseVM.Fohid) { return(NotFound()); } if (ModelState.IsValid) { try { factoryOverheadExpenseVM.DateUpdated = DateTime.Now; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", HttpContext.Session.GetString("token")); var content = new StringContent(JsonConvert.SerializeObject(factoryOverheadExpenseVM), Encoding.UTF8, "application/json"); HttpResponseMessage res = await client.PutAsync("api/FactoryOverheadExpense/" + id, content); if (res.IsSuccessStatusCode) { return(RedirectToAction("Index")); } } catch (DbUpdateConcurrencyException) { //if (!RoleVMExists(roleVM.Id)) //{ // return NotFound(); //} //else //{ throw; //} } return(RedirectToAction(nameof(Index))); } List <TblAccountVM> tblAccountVM = new List <TblAccountVM>(); var contentType = new MediaTypeWithQualityHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(contentType); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", HttpContext.Session.GetString("token")); HttpResponseMessage tblAccountVMRes = await client.GetAsync("api/Account"); if (tblAccountVMRes.StatusCode == HttpStatusCode.Unauthorized) { ViewBag.Message = "Unauthorized!"; } //Checking the response is successful or not which is sent using HttpClient if (tblAccountVMRes.IsSuccessStatusCode) { //Storing the response details recieved from web api var result = tblAccountVMRes.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the role list tblAccountVM = JsonConvert.DeserializeObject <List <TblAccountVM> >(result); } //if (id != factoryOverheadExpenseVM.Fohid) //{ // return NotFound(); //} //if (ModelState.IsValid) //{ // try // { // _context.Update(factoryOverheadExpenseVM); // await _context.SaveChangesAsync(); // } // catch (DbUpdateConcurrencyException) // { // if (!FactoryOverheadExpenseVMExists(factoryOverheadExpenseVM.Fohid)) // { // return NotFound(); // } // else // { // throw; // } // } // return RedirectToAction(nameof(Index)); //} ViewData["PaymentSourceAccountId"] = new SelectList(_context.TblAccountVM, "AccountId", "AccountTitle", factoryOverheadExpenseVM.PaymentSourceAccountId); return(View(factoryOverheadExpenseVM)); }
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext) { return(Task.Factory.StartNew(() => { string callback; //This fixes a bug in javascript to do with returning json arrays //Instead of returning an array we simply return odata format which we'll need eventually anyhow. This lends itself to getting the count in the future for paging. // See here: http://haacked.com/archive/2009/06/25/json-hijacking.aspx var response = new BaseResponse <object>(); object responseToSerialize = response; if (value == null) { response.results = new object[] { }; } else if (value.AttributeExists <SkipJsonResultAttribute>()) { responseToSerialize = value; } else if (value.GetType() == typeof(HttpError)) { response.results = null; var errors = value as HttpError; response.errors = new ResponseError[] { new ResponseError { ErrorType = (errors.FirstOrDefault(e => e.Key == "ExceptionType").Value ?? "Message").ToStringEx(), Description = (errors.FirstOrDefault(e => e.Key == "ExceptionMessage").Value ?? errors.First().Value).ToStringEx() } }; } else if (type == typeof(IQueryable) || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IQueryable <>) || type.GetGenericTypeDefinition() == typeof(DbQuery <>)))) { response.results = ((IQueryable <object>)value).ToArray(); if (_request != null) { response.InlineCount = _request.ODataProperties().TotalCount; } } else if (type == typeof(IEnumerable) || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List <>) || type.GetGenericTypeDefinition() == typeof(IEnumerable <>)))) { response.results = ((IEnumerable <object>)value).ToArray(); if (_request != null) { response.InlineCount = _request.ODataProperties().TotalCount; } } else if (value is Guid[]) { var guids = value as Guid[]; List <object> objs = new List <object>(); foreach (var val in guids) { objs.Add(val); } response.results = objs.ToArray(); if (_request != null) { response.InlineCount = _request.ODataProperties().TotalCount; } } else if (value is Array) { response.results = (object[])value; if (_request != null) { response.InlineCount = _request.ODataProperties().TotalCount; } } else { var al = new List <object>(); al.Add(value); response.results = al.ToArray(); } var serializer = JsonSerializer.Create(SerializerSettings); if (_request != null && _request.Headers.Accept.Contains(MediaTypeWithQualityHeaderValue.Parse(mediaTypeHeaderTextBson))) { using (BinaryWriter streamWriter = new BinaryWriter(writeStream, encoding)) { callback = null; var jsonp = IsJsonpRequest(_request, out callback); if (jsonp) { streamWriter.Write(callback + "("); } using (BsonWriter bsonWriter = new BsonWriter(streamWriter) { CloseOutput = false }) { serializer.Serialize(bsonWriter, responseToSerialize); bsonWriter.Flush(); if (jsonp) { streamWriter.Write(")"); } } } } else { using (StreamWriter streamWriter = new StreamWriter(writeStream, encoding, 1024, true)) { callback = null; var jsonp = IsJsonpRequest(_request, out callback); if (jsonp) { streamWriter.Write(callback + "("); } using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter)) { serializer.Serialize(jsonTextWriter, responseToSerialize); if (jsonp) { streamWriter.Write(")"); } jsonTextWriter.Flush(); } } } })); }
public async Task CanHandleAbsoluteAndRelativeUrls() { // Arrange var requestUri = string.Format("{0}/UnbufferedBatch/$batch", this.BaseAddress); Uri address = new Uri(this.BaseAddress, UriKind.Absolute); string host = address.Host; string relativeToServiceRootUri = "UnbufferedBatchCustomer"; string relativeToHostUri = address.LocalPath.TrimEnd(new char[] { '/' }) + "/UnbufferedBatch/UnbufferedBatchCustomer"; string absoluteUri = this.BaseAddress + "/UnbufferedBatch/UnbufferedBatchCustomer"; // Act HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("multipart/mixed")); HttpContent content = new StringContent(@" --batch_abbe2e6f-e45b-4458-9555-5fc70e3aebe0 Content-Type: multipart/mixed; boundary=changeset_6c67825c-8938-4f11-af6b-a25861ee53cc --changeset_6c67825c-8938-4f11-af6b-a25861ee53cc Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 2 POST " + relativeToServiceRootUri + @" HTTP/1.1 OData-Version: 4.0;NetFx OData-MaxVersion: 4.0;NetFx Content-Type: application/json;odata.metadata=minimal Accept: application/json;odata.metadata=minimal Accept-Charset: UTF-8 {'Id':11,'Name':'MyName11'} --changeset_6c67825c-8938-4f11-af6b-a25861ee53cc Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 3 POST " + relativeToHostUri + @" HTTP/1.1 Host: " + host + @" OData-Version: 4.0;NetFx OData-MaxVersion: 4.0;NetFx Accept: application/json;odata.metadata=minimal Accept-Charset: UTF-8 Content-Type: application/json;odata.metadata=minimal {'Id':12,'Name':'MyName12'} --changeset_6c67825c-8938-4f11-af6b-a25861ee53cc Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 4 POST " + absoluteUri + @" HTTP/1.1 OData-Version: 4.0;NetFx OData-MaxVersion: 4.0;NetFx Accept: application/json;odata.metadata=minimal Accept-Charset: UTF-8 Content-Type: application/json;odata.metadata=minimal {'Id':13,'Name':'MyName13'} --changeset_6c67825c-8938-4f11-af6b-a25861ee53cc-- --batch_abbe2e6f-e45b-4458-9555-5fc70e3aebe0-- "); content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/mixed; boundary=batch_abbe2e6f-e45b-4458-9555-5fc70e3aebe0"); request.Content = content; HttpResponseMessage response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var stream = await response.Content.ReadAsStreamAsync(); IODataResponseMessage odataResponseMessage = new ODataMessageWrapper(stream, response.Content.Headers); int subResponseCount = 0; using (var messageReader = new ODataMessageReader(odataResponseMessage, new ODataMessageReaderSettings(), GetEdmModel(new ODataConventionModelBuilder()))) { var batchReader = messageReader.CreateODataBatchReader(); while (batchReader.Read()) { switch (batchReader.State) { case ODataBatchReaderState.Operation: var operationMessage = batchReader.CreateOperationResponseMessage(); subResponseCount++; Assert.Equal(201, operationMessage.StatusCode); break; } } } Assert.Equal(3, subResponseCount); }
public ActionResult Login(LoginViewModel model, string returnUrl) { try { if (!ModelState.IsValid) { ModelState.AddModelError("", "Usuario o Password Incorrectos"); return(View()); } else { clsUsuario Objusuario = new clsUsuario(); //var Encriptado = Seguridad.Encriptar(model.Password); //var Desencriptado = Seguridad.Desencriptar(Encriptado); var contraseña = Seguridad.Encriptar(model.Password); var usuario = Objusuario.ExisteUsuario(model.Usuario, contraseña).Where(x => x.Estado == true); if (usuario.Count() > 0) { Session["US"] = model.Usuario; Session["PW"] = model.Password; Session["ROLES"] = "Admin"; string baseUrl = ConfigurationManager.AppSettings["URL_API"]; //crea el el encabezado HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseUrl); var contentType = new MediaTypeWithQualityHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(contentType); Usuario userModel = new Usuario(); userModel.UserName = model.Usuario; userModel.Password = Seguridad.Encriptar(model.Password); string stringData = JsonConvert.SerializeObject(userModel); var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync("/api/login/authenticate", contentData).Result; var stringJWT = response.Content.ReadAsStringAsync().Result; JWT jwt = new JWT { Token = stringJWT.Replace("\"", "") }; //Aca se crea la sesion Session["token"] = jwt.Token; Session["US"] = model.Usuario.ToUpper(); string userData = "Datos específicos de aplicación para este usuario."; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.Usuario.ToUpper(), DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, userData, FormsAuthentication.FormsCookiePath); // Encryptar el ticket. string encTicket = FormsAuthentication.Encrypt(ticket); // Crea la cookie. Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("Error de Autenticación", "Usuario o Contaseña Invalida"); } } } catch (Exception ex) { ModelState.AddModelError("Error de Autenticación", "Usuario o Contaseña Invalida"); } return(View(model)); }
public void Quality_LessThanZero_Throw() { Assert.Throws <ArgumentOutOfRangeException>(() => { MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("application/xml", -0.01); }); }
private static string CreateAcceptHeader(MediaTypeWithQualityHeaderValue mediaTypeHeader, string dicomTransferSyntax) { string transferSyntaxHeader = dicomTransferSyntax == null ? string.Empty : $";{TransferSyntaxHeaderName}=\"{dicomTransferSyntax}\""; return($"{mediaTypeHeader}{transferSyntaxHeader}"); }
private void CheckValidParse(string input, MediaTypeWithQualityHeaderValue expectedResult) { MediaTypeWithQualityHeaderValue result = MediaTypeWithQualityHeaderValue.Parse(input); Assert.Equal(expectedResult, result); }
public void SelectFormatter_WithNoMatchingAcceptHeadersAndRequestContentType_PicksFormatterBasedOnObjectType (string acceptHeader) { // For no accept headers, // can write is called twice once for the request media type and once for the type match pass. // For each additional accept header, it is called once. // Arrange var acceptHeaderCollection = string.IsNullOrEmpty(acceptHeader) ? null : acceptHeader?.Split(',') .Select(header => MediaTypeWithQualityHeaderValue.Parse(header)) .ToArray(); var stream = new MemoryStream(); var httpResponse = new Mock <HttpResponse>(); httpResponse.SetupProperty <string>(o => o.ContentType); httpResponse.SetupGet(r => r.Body).Returns(stream); var actionContext = CreateMockActionContext(httpResponse.Object, requestAcceptHeader: acceptHeader, requestContentType: "application/xml"); var requestContentType = MediaTypeHeaderValue.Parse("application/xml"); var input = "testInput"; var result = new ObjectResult(input); var mockCountingFormatter = new Mock <IOutputFormatter>(); var context = new OutputFormatterContext() { ActionContext = actionContext, Object = input, DeclaredType = typeof(string) }; var mockCountingSupportedContentType = MediaTypeHeaderValue.Parse("application/text"); mockCountingFormatter.Setup(o => o.CanWriteResult(context, It.IsNotIn <MediaTypeHeaderValue>(mockCountingSupportedContentType))) .Returns(false); mockCountingFormatter.Setup(o => o.CanWriteResult(context, mockCountingSupportedContentType)) .Returns(true); mockCountingFormatter.Setup(o => o.GetSupportedContentTypes(context.DeclaredType, input.GetType(), It.IsAny <MediaTypeHeaderValue>())) .Returns(new List <MediaTypeHeaderValue> { mockCountingSupportedContentType }); // Set more than one formatters. The test output formatter throws on write. result.Formatters = new List <IOutputFormatter> { new CannotWriteFormatter(), mockCountingFormatter.Object, }; // Act var formatter = result.SelectFormatter(context, result.Formatters); // Assert Assert.Equal(mockCountingFormatter.Object, formatter); mockCountingFormatter.Verify(v => v.CanWriteResult(context, mockCountingSupportedContentType), Times.Once()); var callCount = (acceptHeaderCollection == null ? 0 : acceptHeaderCollection.Count()) + 1; mockCountingFormatter.Verify(v => v.CanWriteResult(context, It.IsNotIn <MediaTypeHeaderValue>(mockCountingSupportedContentType)), Times.Exactly(callCount)); }
public ServiceEmpleados(String url) { this.UrlApi = new Uri(url); this.Header = new MediaTypeWithQualityHeaderValue("application/json"); }
// Private helpers private static HttpRequestMessage ConstructRequest(HttpMethod httpMethod, string uri, MediaTypeWithQualityHeaderValue mediaType) => ConstructRequest( httpMethod, uri, new[] { mediaType });
public Ecommerce_socksService(String url) { this.UriApi = new Uri(url); this.Header = new MediaTypeWithQualityHeaderValue("application/json"); }
public IActionResult GetToken() { try { using (HttpClient client = new HttpClient()) { var Toke = _context.Parass.Where(x => x.Name == "Token").FirstOrDefault(); if (Toke == null) { MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(contentType); HttpResponseMessage response = client.GetAsync("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx998cfc2cc3850f9c&secret=22895edb0e22f7e46341e26b366fd258").Result; string stringData = response.Content.ReadAsStringAsync().Result; if (stringData == null) { return(BadRequest("没有数据")); } else { var jObject = JObject.Parse(stringData); var Token = jObject["access_token"].ToString(); var Paras = new Paras() { Name = "Token", Describe = Token, CreatDate = DateTime.Now }; _context.Parass.Add(Paras); _context.SaveChanges(); return(Ok(Paras)); } } else { var Time2 = Toke.CreatDate; var Time1 = DateTime.Now; TimeSpan ts1 = new TimeSpan(Time1.Ticks); TimeSpan ts2 = new TimeSpan(Time2.Ticks); TimeSpan ts = ts1.Subtract(ts2).Duration(); if (ts.Hours >= 2) { MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(contentType); HttpResponseMessage response = client.GetAsync("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx998cfc2cc3850f9c&secret=22895edb0e22f7e46341e26b366fd258").Result; string stringData = response.Content.ReadAsStringAsync().Result; var jObject = JObject.Parse(stringData); var Token1 = jObject["access_token"].ToString(); var Kind = _context.Parass.Where(x => x.Name == "Token").FirstOrDefault(); Kind.CreatDate = DateTime.Now; Kind.Describe = Token1; _context.SaveChanges(); return(Ok(Kind)); } else { var Token3 = _context.Parass.Where(x => x.Name == "Token").FirstOrDefault(); return(Ok(Token3)); } } } } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
public void GetFeedInODataJsonNoMetadataFormat() { // Arrange IEdmModel model = CreateModelForFullMetadata(sameLinksForIdAndEdit: false, sameLinksForEditAndRead: false); using (HttpConfiguration configuration = CreateConfiguration(model)) using (HttpServer host = new HttpServer(configuration)) using (HttpClient client = new HttpClient(host)) using (HttpRequestMessage request = CreateRequestWithDataServiceVersionHeaders("MainEntity", MediaTypeWithQualityHeaderValue.Parse("application/json;odata=nometadata"))) // Act using (HttpResponseMessage response = client.SendAsync(request).Result) { // Assert AssertODataVersion3JsonResponse(Resources.MainEntryFeedInJsonNoMetadata, response); } }
public void MatchAcceptHeader_ReturnsMatch(string[] acceptHeaders, string[] supportedMediaTypes, string expectedMediaType, double expectedQuality, int ranking) { // Arrange MockContentNegotiator negotiator = new MockContentNegotiator(); List <MediaTypeWithQualityHeaderValue> unsortedAcceptHeaders = acceptHeaders.Select(a => MediaTypeWithQualityHeaderValue.Parse(a)).ToList(); IEnumerable <MediaTypeWithQualityHeaderValue> sortedAcceptHeaders = negotiator.SortMediaTypeWithQualityHeaderValuesByQFactor(unsortedAcceptHeaders); MockMediaTypeFormatter formatter = new MockMediaTypeFormatter(); foreach (string supportedMediaType in supportedMediaTypes) { formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(supportedMediaType)); } // Act MediaTypeFormatterMatch match = negotiator.MatchAcceptHeader(sortedAcceptHeaders, formatter); // Assert if (expectedMediaType == null) { Assert.Null(match); } else { Assert.Same(formatter, match.Formatter); Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), match.MediaType); Assert.Equal(expectedQuality, match.Quality); Assert.Equal(ranking, (int)match.Ranking); } }
// GET: FactoryOverheadExpense/Edit/5 public async Task <IActionResult> Edit(long?id) { if (id == null) { return(NotFound()); } FactoryOverheadExpenseVM factoryOverheadExpenseVM = new FactoryOverheadExpenseVM(); HttpClient client = _helperAPI.InitializeClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", HttpContext.Session.GetString("token")); HttpResponseMessage res = await client.GetAsync("api/FactoryOverheadExpense/" + id); if (res.IsSuccessStatusCode) { var result = res.Content.ReadAsStringAsync().Result; factoryOverheadExpenseVM = JsonConvert.DeserializeObject <FactoryOverheadExpenseVM>(result); } if (factoryOverheadExpenseVM == null) { return(NotFound()); } List <TblAccountVM> tblAccountVM = new List <TblAccountVM>(); var contentType = new MediaTypeWithQualityHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(contentType); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", HttpContext.Session.GetString("token")); HttpResponseMessage tblAccountVMRes = await client.GetAsync("api/Account"); if (tblAccountVMRes.StatusCode == HttpStatusCode.Unauthorized) { ViewBag.Message = "Unauthorized!"; } //Checking the response is successful or not which is sent using HttpClient if (tblAccountVMRes.IsSuccessStatusCode) { //Storing the response details recieved from web api var result = tblAccountVMRes.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the role list tblAccountVM = JsonConvert.DeserializeObject <List <TblAccountVM> >(result); } //if (id == null) //{ // return NotFound(); //} //var factoryOverheadExpenseVM = await _context.FactoryOverheadExpenseVM.FindAsync(id); //if (factoryOverheadExpenseVM == null) //{ // return NotFound(); //} ViewData["PaymentSourceAccountId"] = new SelectList(tblAccountVM, "AccountId", "AccountTitle", factoryOverheadExpenseVM.PaymentSourceAccountId); return(View(factoryOverheadExpenseVM)); }
public static bool TryParse (string input, out MediaTypeWithQualityHeaderValue parsedValue) { throw new NotImplementedException (); }
public static bool TryParse (string input, out MediaTypeWithQualityHeaderValue parsedValue) { return TryParse (input, out parsedValue, () => new MediaTypeWithQualityHeaderValue ()); }