Example #1
6
        public static async Task<bool> ChangeUserProfile(String name, String url, String description, String location,
            UserAccountEntity userAccountEntity)
        {
            if (userAccountEntity.GetAccessToken().Equals("refresh"))
            {
                await Auth.RefreshAccessToken(userAccountEntity);
            }
            var param = new Dictionary<String, String>();
            if (!string.IsNullOrEmpty(name)) param.Add("name", name);
            if (!string.IsNullOrEmpty(url)) param.Add("url", url);
            if (!string.IsNullOrEmpty(location)) param.Add("location", location);
            if (!string.IsNullOrEmpty(description)) param.Add("description", description);

            var theAuthClient = new HttpClient();
            HttpContent header = new FormUrlEncodedContent(param);
            var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.ACCOUNT_UPDATE) {Content = header};
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
            try
            {
                HttpResponseMessage response = await theAuthClient.SendAsync(request);
                return response.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }
    protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {

      if (HttpContext.Current.User.Identity.IsAuthenticated) {
        return await base.SendAsync(request, cancellationToken);
      }
      if (!CanHandleAuthentication(request)) {
        return await base.SendAsync(request, cancellationToken);
      }
      bool isAuthenticated;
      try {
        isAuthenticated = Authenticate(request);
      }
      catch (Exception) {
        return CreateUnauthorizedResponse();
      }
      if (isAuthenticated) {
        var response = await base.SendAsync(request, cancellationToken);

        // add token cookie value
        IEnumerable<CookieHeaderValue> ccoll = new CookieHeaderValue[] { new CookieHeaderValue(_TokenName, _Token) };
        response.Headers.AddCookies(ccoll);
        
        return response.StatusCode == HttpStatusCode.Unauthorized ? CreateUnauthorizedResponse() : response;
      }
      return CreateUnauthorizedResponse();
    }
        public async Task AppendAuthenticationHeader_ExpiredAccountSession()
        {
            var cachedAccountSession = new AccountSession
            {
                AccessToken = "token",
            };

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;

            using (var httpRequestMessage = new HttpRequestMessage())
            {
                try
                {
                    await this.authenticationProvider.AppendAuthHeaderAsync(httpRequestMessage);
                }
                catch (OneDriveException oneDriveException)
                {
                    Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), oneDriveException.Error.Code, "Unexpected error code.");
                    Assert.AreEqual(
                        "Failed to retrieve a valid authentication token for the user.",
                        oneDriveException.Error.Message,
                        "Unexpected error message.");

                    throw;
                }
            }
        }
        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;
        }
        [InlineData("GET", "http://localhost/Customers(12)/NS.SpecialCustomer/NS.GetSalary()", "GetSalaryFromSpecialCustomer_12")] // call function on derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataAndServiceController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.MapODataServiceRoute("odata", "", model.Model);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
        public void ByPostShouldReturnCorrectResponse()
        {
            var controller = typeof(CategoriesController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
            );

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var httpServer = new HttpServer(config);
            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/categories/1"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;

                Assert.IsNotNull(result);
            }
        }
        public void Parameter_Constructor()
        {
            HttpRequestMessage[] requests = new HttpRequestMessage[0];
            ChangeSetRequestItem requestItem = new ChangeSetRequestItem(requests);

            Assert.Same(requests, requestItem.Requests);
        }
        public HttpResponseMessage Put(HttpRequestMessage request, int betId, int userId, [FromBody]BetUser betUser)
        {
            if (!ModelState.IsValid)
            {
                return request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (betId != betUser.BetId || userId != betUser.UserId)
            {
                return request.CreateResponse(HttpStatusCode.BadRequest);
            }

            try
            {
                this.dataService.UpdateBetUser(betUser);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (this.dataService.GetBetUser(betId, userId) == null)
                {
                    return request.CreateResponse(HttpStatusCode.NotFound);
                }
                else
                {
                    throw;
                }
            }

            //seriallize the object
            return request.CreateResponse<BetUser>(HttpStatusCode.OK, betUser);
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            string identifier = GetUserIdentifier(request);
            if (String.IsNullOrEmpty(identifier))
                return CreateResponse(request, HttpStatusCode.Forbidden, "Could not identify client.");

            string cacheKey = GetCacheKey(identifier);
            long requestCount = 0;
            using (IRedisClient client = _clientsManager.GetClient()) {
                requestCount = client.IncrementValueBy(cacheKey, 1);
                if (requestCount == 1)
                    client.ExpireEntryIn(cacheKey, _period);
            }

            Task<HttpResponseMessage> response = null;
            long maxRequests = _maxRequestsForUserIdentifier(identifier);
            if (requestCount > maxRequests)
                response = CreateResponse(request, HttpStatusCode.Conflict, _message);
            else
                response = base.SendAsync(request, cancellationToken);

            return response.ContinueWith(task => {
                long remaining = maxRequests - requestCount;
                if (remaining < 0)
                    remaining = 0;

                HttpResponseMessage httpResponse = task.Result;
                httpResponse.Headers.Add("RateLimit-Limit", maxRequests.ToString());
                httpResponse.Headers.Add("RateLimit-Remaining", remaining.ToString());

                return httpResponse;
            });
        }
        public async Task DataMember_RequiredPropertyProvided_Success()
        {
            // Arrange
            var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client = server.CreateClient();

            var url = "http://localhost/DataMemberRequired/EchoModelValues";
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            var formData = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("model.ImplicitlyOptionalProperty", "Hello"),
                new KeyValuePair<string, string>("model.ExplicitlyOptionalProperty", "World!"),
                new KeyValuePair<string, string>("model.RequiredProperty", "Required!"),
            };

            request.Content = new FormUrlEncodedContent(formData);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var body = await response.Content.ReadAsStringAsync();
            var model = JsonConvert.DeserializeObject<DataMemberRequiredModel>(body);

            Assert.Equal("Hello", model.ImplicitlyOptionalProperty);
            Assert.Equal("World!", model.ExplicitlyOptionalProperty);
            Assert.Equal("Required!", model.RequiredProperty);
        }
Example #11
1
 public async Task<HttpResponseMessage> SendEvent(string eventType, IDictionary<string, string> options) 
 {
     HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, endpointUrl);
     request.Content = GetRequestContent(eventType, options);
     var response = await HttpClient.SendAsync(request).ConfigureAwait(false);
     return response;
 }
        public void Mvc200RequestFW45BasicRequestSyntheticFiltering()
        {
            const string requestPath = "api/products";
            const string expectedRequestName = "GET products";
            string expectedRequestUrl = this.Config.ApplicationUri + "/" + requestPath;

            DateTimeOffset testStart = DateTimeOffset.UtcNow;

            //Call an applicaiton page
            var client = new HttpClient();
            var requestMessage = new HttpRequestMessage
            {
                RequestUri = new Uri(expectedRequestUrl),
                Method = HttpMethod.Get,
            };

            requestMessage.Headers.Add("User-Agent", "bingbot");

            var responseTask = client.SendAsync(requestMessage);
            responseTask.Wait(TimeoutInMs);
            var responseTextTask = responseTask.Result.Content.ReadAsStringAsync();
            responseTextTask.Wait(TimeoutInMs);
            Assert.IsTrue(responseTextTask.Result.StartsWith("[{"));

            var request = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(1, TimeoutInMs)[0];

            var testFinish = DateTimeOffset.UtcNow;

            this.TestWebApplicationHelper(expectedRequestName, expectedRequestUrl, "200", true, request, testStart, testFinish);
            Assert.AreEqual("Spider", request.OperationContext.SyntheticSource);
        }
Example #13
1
        public async Task NoRequestContentType_Throws_IfMultipleActionsWithConstraints()
        {
            // Arrange
            var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client = server.CreateClient();
            var request = new HttpRequestMessage(
                HttpMethod.Post,
                "http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct");

            // Act
            var response = await client.SendAsync(request);
            var exception = response.GetServerException();

            // Assert
            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
            Assert.Equal(typeof(AmbiguousActionException).FullName, exception.ExceptionType);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                "Multiple actions matched. The following actions matched route data and had all constraints " +
                "satisfied:" + PlatformNormalizer.GetNewLinesAsUnderscores(2) + "ActionConstraintsWebSite." +
                    "ConsumesAttribute_NoFallBackActionController." +
                "CreateProduct" + PlatformNormalizer.GetNewLinesAsUnderscores(1) + "ActionConstraintsWebSite." +
                    "ConsumesAttribute_NoFallBackActionController.CreateProduct",
                exception.ExceptionMessage);
        }
        public void TestRoute(string url, string verb, Type type, string actionName)
        {
            //Arrange
            url = url.Replace("{apiVersionNumber}", this.ApiVersionNumber);
            url = Host + url;

            //Act
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);

            IHttpControllerSelector controller = this.GetControllerSelector();
            IHttpActionSelector action = this.GetActionSelector();

            IHttpRouteData route = this.Config.Routes.GetRouteData(request);
            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;
            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = this.Config;

            HttpControllerDescriptor controllerDescriptor = controller.SelectController(request);

            HttpControllerContext context = new HttpControllerContext(this.Config, route, request)
            {
                ControllerDescriptor = controllerDescriptor
            };

            var actionDescriptor = action.SelectAction(context);

            //Assert
            Assert.NotNull(controllerDescriptor);
            Assert.NotNull(actionDescriptor);
            Assert.Equal(type, controllerDescriptor.ControllerType);
            Assert.Equal(actionName, actionDescriptor.ActionName);
        }
Example #15
1
        public string Translate(string text, string from, string to)
        {
            using (var client = new HttpClient())
            {
                var url = string.Format(
                        _translatorApiUrlFormat,
                        HttpUtility.UrlEncode(text),
                        HttpUtility.UrlEncode(from),
                        HttpUtility.UrlEncode(to));

                using (var message = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken());

                    using (var result = client.SendAsync(message).Result)
                    {
                        if (!result.IsSuccessStatusCode)
                        {
                            throw new TrosiTranslationException(result.Content.ReadAsStringAsync().Result);
                        }

                        using (var responseStream = result.Content.ReadAsStreamAsync().Result)
                        {
                            var serializer = new DataContractSerializer(typeof(string));

                            return serializer.ReadObject(responseStream) as string;
                        }
                    }
                }
            }
        }
        public void SendRequestAsync_ReturnsSingleErrorResponse()
        {
            HttpRequestMessage[] requests = new HttpRequestMessage[]
                {
                    new HttpRequestMessage(HttpMethod.Get, "http://example.com"),
                    new HttpRequestMessage(HttpMethod.Post, "http://example.com"),
                    new HttpRequestMessage(HttpMethod.Put, "http://example.com")
                };
            ChangeSetRequestItem requestItem = new ChangeSetRequestItem(requests);

            Mock<HttpMessageInvoker> invoker = new Mock<HttpMessageInvoker>(new HttpServer());
            invoker.Setup(i => i.SendAsync(It.IsAny<HttpRequestMessage>(), CancellationToken.None))
                .Returns<HttpRequestMessage, CancellationToken>((req, c) =>
                {
                    if (req.Method == HttpMethod.Post)
                    {
                        return Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest));
                    }
                    return Task.FromResult(new HttpResponseMessage());
                });

            var response = requestItem.SendRequestAsync(invoker.Object, CancellationToken.None).Result;

            var changesetResponse = Assert.IsType<ChangeSetResponseItem>(response);
            Assert.Equal(1, changesetResponse.Responses.Count());
            Assert.Equal(HttpStatusCode.BadRequest, changesetResponse.Responses.First().StatusCode);
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url = new Java.Net.URL(java_uri);

            var body = default(RequestBody);
            if (request.Content != null) {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                body = RequestBody.Create(MediaType.Parse(request.Content.Headers.ContentType.MediaType), bytes);
            }

            var builder = new Request.Builder()
                .Method(request.Method.Method.ToUpperInvariant(), body)
                .Url(url);

            var keyValuePairs = request.Headers
                .Union(request.Content != null ?
                    (IEnumerable<KeyValuePair<string, IEnumerable<string>>>)request.Content.Headers :
                    Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>());

            foreach (var kvp in keyValuePairs) builder.AddHeader(kvp.Key, String.Join(",", kvp.Value));

            cancellationToken.ThrowIfCancellationRequested();

            var rq = builder.Build();
            var call = client.NewCall(rq);
            cancellationToken.Register(() => call.Cancel());

            var resp = default(Response);
            try {
                resp = await call.EnqueueAsync().ConfigureAwait(false);
            } catch (IOException ex) {
                if (ex.Message.ToLowerInvariant().Contains("canceled")) {
                    throw new OperationCanceledException();
                }

                throw;
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());
            if (respBody != null) {
                var content = new ProgressStreamContent(respBody.ByteStream(), cancellationToken);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content = content;
            } else {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();
            foreach (var k in respHeaders.Names()) {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return ret;
        }
Example #18
1
        public HttpResponseMessageWrapper<Suggestion> GetSuggestion(HttpRequestMessage req, Guid id)
        {
            Operation operation = null;
            HttpStatusCode code = AuthenticateUser(req);
            if (code != HttpStatusCode.OK)
            {   // user not authenticated
                return ReturnResult<Suggestion>(req, operation, code);
            }

            try
            {
                Suggestion suggestion = this.SuggestionsStorageContext.Suggestions.Single<Suggestion>(s => s.ID == id);
                if (!ValidateEntityOwnership(suggestion.EntityID, suggestion.EntityType))
                {   // entity associated with suggestions does not belong to the authenticated user, return 403 Forbidden
                    TraceLog.TraceError("Associated entity does not belong to current user)");
                    return ReturnResult<Suggestion>(req, operation, HttpStatusCode.Forbidden);
                }
                var response = ReturnResult<Suggestion>(req, operation, suggestion, HttpStatusCode.OK);
                response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true };
                return response;
            }
            catch (Exception ex)
            {   // suggestion not found - return 404 Not Found
                TraceLog.TraceException("Resource not found", ex);
                return ReturnResult<Suggestion>(req, operation, HttpStatusCode.NotFound);
            }
        }
Example #19
0
        public async static Task<bool> Ping(ConnectionItem connectionItem)
        {
            JObject requestObject = new JObject(
                new JProperty("jsonrpc", "2.0"),
                new JProperty("id", 234),
                new JProperty("method", "JSONRPC.ping"));
                
            string requestData = requestObject.ToString();

            HttpClientHandler handler = new HttpClientHandler();
            HttpClient httpClient = new HttpClient(handler);
            string uriString = "http://" + connectionItem.IpAddress + ":" + connectionItem.Port.ToString() + "/jsonrpc?request=";
            httpClient.BaseAddress = new Uri(uriString);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");

            request.Content = new StringContent(requestData);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //Required to be recognized as valid JSON request.

            HttpResponseMessage response = await httpClient.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();
            if (responseString.Length == 0)
                return false;
            dynamic responseObject = JObject.Parse(responseString);
            bool isSuccessful = responseObject.result == "pong";
            return isSuccessful;
        }
        public async Task<IList<JeuForain>> GetJeuxForainsAsync()
        {
            try
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, JEUXFORAINSURL);
                HttpClient httpClient = new HttpClient();

                HttpResponseMessage httpResponse = await httpClient.SendAsync(request);

                string content = await httpResponse.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(content))
                {
                    var json = JObject.Parse(content);

                    var records = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIJeuxForainsRecord>>(json["records"].ToString());

                    IList<JeuForain> values = new List<JeuForain>();

                    foreach (var jeux in records)
                        values.Add(jeux.Value);

                    return values;
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetJeuxForainsAsync : " + ex);
            }
            return null;
        }
        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            var controllers = GetControllerMapping(); //Will ignore any controls in same name even if they are in different namepsace

            var routeData = request.GetRouteData();
            if (string.IsNullOrWhiteSpace(routeData.Route.RouteTemplate))
            {
                return base.SelectController(request);
            }
            var controllerName = routeData.Values["controller"].ToString();

            HttpControllerDescriptor controllerDescriptor;

            if (controllers.TryGetValue(controllerName, out controllerDescriptor))
            {

                //var version = GetVersionFromQueryString(request);
                //var version = GetVersionFromHeader(request);
                var version = GetVersionFromAcceptHeaderVersion(request);

                var versionedControllerName = string.Concat(controllerName, "V", version);

                HttpControllerDescriptor versionedControllerDescriptor;
                if (controllers.TryGetValue(versionedControllerName, out versionedControllerDescriptor))
                {
                    return versionedControllerDescriptor;
                }

                return controllerDescriptor;
            }

            return null;
        }
Example #22
0
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            var record = new TraceRecord(request, category, level);
            traceAction(record);

            var sb = new StringBuilder();
            if (record.Request != null)
            {
                if (record.Request.Method != null)
                {
                    sb.Append(" ");
                    sb.Append(request.Method.ToString());
                }
                if (record.Request.RequestUri != null)
                {
                    sb.Append(" ");
                    sb.Append(record.Request.RequestUri.ToString());
                }
                if (!string.IsNullOrWhiteSpace(record.Category))
                {
                    sb.Append(" ");
                    sb.Append(record.Category);
                }
                sb.Append(" ");
                sb.Append(record.Message);

                if (record.Exception != null)
                {
                    sb.Append(record.Exception.ToString());
                }
            }
            Console.WriteLine(sb.ToString());
        }
Example #23
0
        public void Create_New_Customer()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "Customers");
                request.Content = new StringContent("Id = 7; Name = NewCustomer7");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.Created, response.StatusCode, "The status code should have been 'Created'.");
                    Assert.IsNotNull(response.Headers.Location, "The location header should not have been null.");
                    Assert.AreEqual(new Uri("http://localhost:8080/Customers?id=7"), response.Headers.Location, "The location header should have beeen 'http://localhost:8080/Customers?id=7'.");
                    Assert.AreEqual("Id = 7; Name = NewCustomer7", response.Content.ReadAsString(), "The response content should have been 'Id = 7; Name = NewCustomer7'.");
                }

                // Put server back in original state
                request = new HttpRequestMessage(HttpMethod.Delete, "Customers?id=7");
                client.Send(request);
            }
        }
        public async Task DataMember_MissingRequiredProperty_ValidationError()
        {
            // Arrange
            var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client = server.CreateClient();

            var url = "http://localhost/DataMemberRequired/EchoModelValues";
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            var formData = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("model.ExplicitlyOptionalProperty", "Hi"),
            };

            request.Content = new FormUrlEncodedContent(formData);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

            var body = await response.Content.ReadAsStringAsync();
            var errors = JsonConvert.DeserializeObject<SerializableError>(body);

            Assert.Equal(1, errors.Count);

            var error = Assert.Single(errors, kvp => kvp.Key == "model.RequiredProperty");
            Assert.Equal(
                "A value for the 'RequiredProperty' property was not provided.",
                ((JArray)error.Value)[0].Value<string>());
        }
        public string CanonicalizeHttpRequest(HttpRequestMessage request, string accountName)
        {
            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method.Method, ExpectedCanonicalizedStringLength);

            // Add the Content-* HTTP headers. Empty values are allowed.
            if (request.Content != null)
            {
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentMD5 == null) ? null :
                    Convert.ToBase64String(request.Content.Headers.ContentMD5));
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentType == null) ? null :
                    request.Content.Headers.ContentType.ToString());
            }
            else
            {
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
            }

            // Add the Date HTTP header (or the x-ms-date header if it is being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request, true);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName, true);
            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return canonicalizedString.ToString();
        }
 private static void AddHeaderToHttpRequestMessage(HttpRequestMessage httpRequestMessage, string headerName, string[] headerValues)
 {
     if (!httpRequestMessage.Headers.TryAddWithoutValidation(headerName, headerValues))
     {
         httpRequestMessage.Content.Headers.TryAddWithoutValidation(headerName, headerValues);
     }
 }
        // GET api/LotteryRecords
        public DataSourceResult Get(HttpRequestMessage requestMessage)
        {
            DataSourceRequest request = JsonConvert.DeserializeObject<DataSourceRequest>(
                // The request is in the format GET api/products?{take:10,skip:0} and ParseQueryString treats it as a key without value
                requestMessage.RequestUri.ParseQueryString().GetKey(0)
            );

            return db.LotteryRecords
                //Entity Framework can page only sorted data
                .OrderBy(LotteryRecord => LotteryRecord.id)
                .Select(LotteryRecord => new
                {
                    // Skip the EntityState and EntityKey properties inherited from EF. It would break model binding.
                    LotteryRecord.id,
                    LotteryRecord.types,
                    LotteryRecord.dates,
                    LotteryRecord.a1,
                    LotteryRecord.a2,
                    LotteryRecord.a3,
                    LotteryRecord.a4,
                    LotteryRecord.b,
                    LotteryRecord.c,
                    LotteryRecord.d
                })
            .ToDataSourceResult(request.Take, request.Skip, request.Sort, request.Filter);
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var requestUri = request.RequestUri;
            var authority = string.Empty;
            var targetUri = requestUri;

            // NOTE: The KmsNetworkUrl setting is purely for development testing on the
            //       Microsoft Azure Development Fabric and should not be used outside that environment.
            string networkUrl = TestConfigurationManager.TryGetEnvironmentOrAppSetting("KmsNetworkUrl");

            if (!string.IsNullOrEmpty(networkUrl))
            {
                authority = targetUri.Authority;
                targetUri = new Uri(new Uri(networkUrl), targetUri.PathAndQuery);

                request.Headers.Add("Host", authority);
                request.RequestUri = targetUri;
            }

            return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(response =>
            {
                return response.Result;
            });
        }
        /// <summary>
        /// Performs Membership Authentication of the on going request. Turns Membership authentication into mandatory.
        /// </summary>
        /// <param name="request">Ongoing request</param>
        /// <param name="cancellationToken">Async Cancellation token</param>
        /// <returns>The HTTP request message that was processed</returns>
        protected override HttpRequestMessage ProcessRequestHandler(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                var principal = PrincipalHelper.GetPrincipalFromHttpRequest(request);
                if (principal == null)
                {
                    this.Unauthorized();
                }

                var user = Membership.GetUser(principal.Identity.Name);
                if (user == null)
                {
                    this.Unauthorized();
                }

                PrincipalHelper.SetPrincipal(request, principal);
            }
            catch
            {
                this.Unauthorized();
            }

            return request;
        }
        public void Create_Throws_And_Traces_When_Inner_Throws()
        {
            // Arrange
            Mock<ApiController> mockController = new Mock<ApiController>();
            Mock<IHttpControllerActivator> mockActivator = new Mock<IHttpControllerActivator>() { CallBase = true };
            InvalidOperationException exception = new InvalidOperationException("test");
            mockActivator.Setup(b => b.Create(It.IsAny<HttpRequestMessage>(), It.IsAny<HttpControllerDescriptor>(), It.IsAny<Type>())).Throws(exception);
            HttpRequestMessage request = new HttpRequestMessage();
            TestTraceWriter traceWriter = new TestTraceWriter();
            HttpControllerActivatorTracer tracer = new HttpControllerActivatorTracer(mockActivator.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "Create" },
                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "Create" }
            };

            // Act & Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpControllerActivator)tracer).Create(request, controllerDescriptor: null, controllerType: mockController.Object.GetType()));

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
        /// <summary>
        /// Update products
        /// </summary>
        /// <remarks>
        /// Resets products.
        /// </remarks>
        /// <param name='subscriptionId'>
        /// Subscription ID.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Resource Group ID.
        /// </param>
        /// <param name='productArrayOfDictionary'>
        /// Array of dictionary of products
        /// </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>
        /// <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 <CatalogArrayInner> > UpdateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, IList <IDictionary <string, ProductInner> > productArrayOfDictionary = default(IList <IDictionary <string, ProductInner> >), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (subscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            string apiVersion = "2014-04-01-preview";
            CatalogArrayOfDictionary bodyParameter = new CatalogArrayOfDictionary();

            if (productArrayOfDictionary != null)
            {
                bodyParameter.ProductArrayOfDictionary = productArrayOfDictionary;
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("subscriptionId", subscriptionId);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("bodyParameter", bodyParameter);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (bodyParameter != null)
            {
                _requestContent      = SafeJsonConvert.SerializeObject(bodyParameter, 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 (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // 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 AzureOperationResponse <CatalogArrayInner>();

            _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 = SafeJsonConvert.DeserializeObject <CatalogArrayInner>(_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>
        /// Validates body parameters on the method. See swagger for details.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+.
        /// </param>
        /// <param name='id'>
        /// Required int multiple of 10 from 100 to 1000.
        /// </param>
        /// <param name='body'>
        /// </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 <HttpOperationResponse <Product> > ValidationOfBodyWithHttpMessagesAsync(string resourceGroupName, int id, Product body = default(Product), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (resourceGroupName != null)
            {
                if (resourceGroupName.Length > 10)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 10);
                }
                if (resourceGroupName.Length < 3)
                {
                    throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 3);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
                }
            }
            if (id > 1000)
            {
                throw new ValidationException(ValidationRules.InclusiveMaximum, "id", 1000);
            }
            if (id < 100)
            {
                throw new ValidationException(ValidationRules.InclusiveMinimum, "id", 100);
            }
            if (id % 10 != 0)
            {
                throw new ValidationException(ValidationRules.MultipleOf, "id", 10);
            }
            if (body != null)
            {
                body.Validate();
            }
            if (ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion");
            }
            if (ApiVersion != null)
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(ApiVersion, "\\d{2}-\\d{2}-\\d{4}"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "ApiVersion", "\\d{2}-\\d{2}-\\d{4}");
                }
            }
            // 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("id", id);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ValidationOfBody", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "fakepath/{subscriptionId}/{resourceGroupName}/{id}").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"')));
            List <string> _queryParameters = new List <string>();

            if (ApiVersion != null)
            {
                _queryParameters.Add(string.Format("apiVersion={0}", System.Uri.EscapeDataString(ApiVersion)));
            }
            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("PUT");
            _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 (body != null)
            {
                _requestContent      = SafeJsonConvert.SerializeObject(body, 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);
        }
        /// <param name='body'>
        /// </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 <Product> > PostWithConstantInBodyWithHttpMessagesAsync(Product body = default(Product), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (body != null)
            {
                body.Validate();
            }
            string constantParam = "constant";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("constantParam", constantParam);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "PostWithConstantInBody", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "validation/constantsInPath/{constantParam}/value").ToString();

            _url = _url.Replace("{constantParam}", System.Uri.EscapeDataString(constantParam));
            // 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 (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 (body != null)
            {
                _requestContent      = SafeJsonConvert.SerializeObject(body, 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 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 <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);
        }
Example #34
0
 public static dynamic ReturnResponseJsonMessageAndData(System.Net.Http.HttpRequestMessage request, dynamic message)
 {
     return(ReturnResponseJsonMessageAndData(request, message.ToString(), "", false));
 }
Example #35
0
 public static dynamic ReturnResponseJsonMessageAndData(System.Net.Http.HttpRequestMessage request, dynamic message, bool isError)
 {
     return(ReturnResponseJsonMessageAndData(request, ReturnMessage(message), "", isError));
 }
Example #36
0
        /// <summary>
        /// Get a basic complex type while the server doesn't provide a response
        /// payload
        /// </summary>
        /// <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 <AzureOperationResponse <Basic> > GetNotProvidedWithHttpMessagesAsync(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, "GetNotProvided", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = Client.BaseUri.AbsoluteUri;
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").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 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 <Basic>();

            _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 <Basic>(_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);
        }
 partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
Example #38
0
        /// <summary>
        /// Lists supported cloud appliance models and supported configurations.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The resource group name
        /// </param>
        /// <param name='managerName'>
        /// The manager name
        /// </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 <IEnumerable <CloudApplianceConfiguration> > > ListSupportedConfigurationsWithHttpMessagesAsync(string resourceGroupName, string managerName, 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 (managerName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
            }
            if (managerName != null)
            {
                if (managerName.Length > 50)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
                }
                if (managerName.Length < 2)
                {
                    throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
                }
            }
            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("managerName", managerName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ListSupportedConfigurations", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/cloudApplianceConfigurations").ToString();

            _url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
            _url = _url.Replace("{resourceGroupName}", resourceGroupName);
            _url = _url.Replace("{managerName}", managerName);
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", 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 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 <IEnumerable <CloudApplianceConfiguration> >();

            _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 <Page1 <CloudApplianceConfiguration> >(_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);
        }
Example #39
0
        public async Task <IEnumerable <FilmesResponse> > GetFilmesAsync(CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(_baseUrl != null ? _baseUrl.TrimEnd('/') : "").Append("/filmes");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("GET");

                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    var url_ = urlBuilder_.ToString();

                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);

                        if (response_.Content != null && response_.Content.Headers != null)

                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        var status_ = ((int)response_.StatusCode).ToString();

                        if (status_ == "200")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <IEnumerable <FilmesResponse> >(response_, headers_).ConfigureAwait(false);

                            return(objectResponse_.Object);
                        }

                        else

                        if (status_ == "404")

                        {
                            string responseText_ = (response_.Content == null) ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("Not found", (int)response_.StatusCode, responseText_, headers_, null);
                        }

                        else

                        if (status_ != "200" && status_ != "204")

                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }



                        return(default);
                    }
Example #40
0
        private void LogRequest(System.Net.Http.HttpRequestMessage request)
        {
            if (Convert.ToBoolean(System.Web.Configuration.WebConfigurationManager.AppSettings["APILoggerRequest"].ToString()) == true)
            {
                try
                {
                    if (!request.Content.IsMimeMultipartContent())
                    {
                        (request.Content ?? new StringContent("")).ReadAsStringAsync().ContinueWith(x =>
                        {
                            var requestMessage = request.Content.ReadAsByteArrayAsync();

                            if (request.Method.ToString() == "GET")
                            {
                                LogHelper.CreateAPILog(""
                                                       + request.Method + " "
                                                       + request.GetCorrelationId() + " "
                                                       + " REQUEST: " + request.RequestUri
                                                       , " " + request.RequestUri.ToString()
                                                       , BytesToStringConverted(requestMessage.Result)
                                                       , ErrorType.APILog);
                            }
                            else
                            {
                                try
                                {
                                    LogHelper.CreateAPILog(""
                                                           + request.Method + " "
                                                           + request.GetCorrelationId() + " "
                                                           + " REQUEST: " + request.RequestUri
                                                           , " " + request.RequestUri.ToString()
                                                           , JObject.Parse(BytesToStringConverted(requestMessage.Result)).ToString()
                                                           , ErrorType.APILog);
                                }
                                catch (Exception ex)
                                {
                                    var a    = BytesToStringConverted(requestMessage.Result).ToString();
                                    var dict = HttpUtility.ParseQueryString(a);
                                    var json = new JavaScriptSerializer().Serialize(
                                        dict.AllKeys.ToDictionary(k => k, k => dict[k])
                                        );

                                    LogHelper.CreateAPILog(""
                                                           + request.Method + " "
                                                           + request.GetCorrelationId() + " "
                                                           + " REQUEST: " + request.RequestUri
                                                           , request.RequestUri.ToString()
                                                           , JObject.Parse(json).ToString()
                                                           , ErrorType.APILog);
                                }
                            }
                        });
                    }
                    //});
                }
                catch (Exception ex)
                {
                    LogHelper.CreateLog(ex);
                }
            }
        }
Example #41
0
        /// <summary>
        /// Return 504 status code, then 200 after retry
        /// </summary>
        /// <param name='booleanValue'>
        /// Simple boolean value true
        /// </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>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> Put504WithHttpMessagesAsync(bool?booleanValue = default(bool?), 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("booleanValue", booleanValue);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Put504", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/504").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("PUT");
            _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 (booleanValue != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, 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 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);
        }
Example #42
0
        public static async ValueTask <Stream> ConnectAsync(Func <SocketsHttpConnectionContext, CancellationToken, ValueTask <Stream> > callback, DnsEndPoint endPoint, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
        {
            Stream stream;

            try
            {
                stream = await callback(new SocketsHttpConnectionContext(endPoint, requestMessage), cancellationToken).ConfigureAwait(false);
            }
            catch (OperationCanceledException ex) when(ex.CancellationToken == cancellationToken)
            {
                throw CancellationHelper.CreateOperationCanceledException(innerException: null, cancellationToken);
            }
            catch (Exception ex)
            {
                throw CreateWrappedException(ex, endPoint.Host, endPoint.Port, cancellationToken);
            }

            if (stream == null)
            {
                throw new HttpRequestException(SR.net_http_null_from_connect_callback);
            }

            return(stream);
        }
 partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url);
        /// <summary>
        /// Post a bunch of required parameters grouped
        /// </summary>
        /// <param name='parameterGroupingPostRequiredParameters'>
        /// 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 <AzureOperationResponse> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParametersInner parameterGroupingPostRequiredParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (parameterGroupingPostRequiredParameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameterGroupingPostRequiredParameters");
            }
            if (parameterGroupingPostRequiredParameters != null)
            {
                parameterGroupingPostRequiredParameters.Validate();
            }
            int body = default(int);

            if (parameterGroupingPostRequiredParameters != null)
            {
                body = parameterGroupingPostRequiredParameters.Body;
            }
            string customHeader = default(string);

            if (parameterGroupingPostRequiredParameters != null)
            {
                customHeader = parameterGroupingPostRequiredParameters.CustomHeader;
            }
            int?query = default(int?);

            if (parameterGroupingPostRequiredParameters != null)
            {
                query = parameterGroupingPostRequiredParameters.Query;
            }
            string path = default(string);

            if (parameterGroupingPostRequiredParameters != null)
            {
                path = parameterGroupingPostRequiredParameters.Path;
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("body", body);
                tracingParameters.Add("customHeader", customHeader);
                tracingParameters.Add("query", query);
                tracingParameters.Add("path", path);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postRequired/{path}").ToString();

            _url = _url.Replace("{path}", System.Uri.EscapeDataString(path));
            List <string> _queryParameters = new List <string>();

            if (query != null)
            {
                _queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"'))));
            }
            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("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 (customHeader != null)
            {
                if (_httpRequest.Headers.Contains("customHeader"))
                {
                    _httpRequest.Headers.Remove("customHeader");
                }
                _httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
            }
            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;

            _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, 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);
        }
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task DeleteAsync(int id, System.Threading.CancellationToken cancellationToken)
        {
            if (id == null)
            {
                throw new System.ArgumentNullException("id");
            }

            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Products/{id}");
            urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("DELETE");

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = (int)response_.StatusCode;
                        if (status_ == 200)
                        {
                            return;
                        }
                        else
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <System.Collections.Generic.ICollection <ProductDto> > GetByNameAsync(string name, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Products/GetByName?");
            if (name != null)
            {
                urlBuilder_.Append(System.Uri.EscapeDataString("name") + "=").Append(System.Uri.EscapeDataString(ConvertToString(name, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            urlBuilder_.Length--;

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("GET");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = (int)response_.StatusCode;
                        if (status_ == 200)
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <System.Collections.Generic.ICollection <ProductDto> >(response_, headers_).ConfigureAwait(false);

                            if (objectResponse_.Object == null)
                            {
                                throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
                            }
                            return(objectResponse_.Object);
                        }
                        else
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Example #47
0
 public static dynamic ReturnResponseJsonMessageAndData(System.Net.Http.HttpRequestMessage request, dynamic message, dynamic data)
 {
     return(ReturnResponseJsonMessageAndData(request, message, data, false));
 }
Example #48
0
        public IHttpRequestMessage CreateRequestMessage(HttpMethod method, Uri requestUri)
        {
            var message = new Http.HttpRequestMessage(HttpRequestMessage.GetMethod(method), requestUri);

            return(new HttpRequestMessage(message));
        }
Example #49
0
 public static dynamic ReturnResponseJsonMessageAndData(System.Net.Http.HttpRequestMessage request, Exception ex)
 {
     return(ReturnResponseJsonMessageAndData(request, ReturnMessage(ex), "", true));
 }
Example #50
0
        public IHttpRequestMessage CreateRequestMessage()
        {
            var message = new Http.HttpRequestMessage();

            return(new HttpRequestMessage(message));
        }
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task PutAsync(ProductDto editedProduct, System.Threading.CancellationToken cancellationToken)
        {
            if (editedProduct == null)
            {
                throw new System.ArgumentNullException("editedProduct");
            }

            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Products");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(editedProduct, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("PUT");

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = (int)response_.StatusCode;
                        if (status_ == 200)
                        {
                            return;
                        }
                        else
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
        /// <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> GetWithConstantInPathWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            string constantParam = "constant";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("constantParam", constantParam);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetWithConstantInPath", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "validation/constantsInPath/{constantParam}/value").ToString();

            _url = _url.Replace("{constantParam}", System.Uri.EscapeDataString(constantParam));
            // 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 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);
        }
Example #53
0
 public HttpRequestMessage(Http.HttpRequestMessage message)
 {
     this.message = message;
 }
Example #54
0
        /// <summary>
        /// Test implicitly optional query parameter
        /// </summary>
        /// <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>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <Error> > GetOptionalGlobalQueryWithHttpMessagesAsync(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, "GetOptionalGlobalQuery", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = Client.BaseUri.AbsoluteUri;
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/optional/query").ToString();
            List <string> _queryParameters = new List <string>();

            if (Client.OptionalGlobalQuery != null)
            {
                _queryParameters.Add(string.Format("optional-global-query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(Client.OptionalGlobalQuery, 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 (!_httpResponse.IsSuccessStatusCode)
            {
                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 <Error>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            try
            {
                _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_defaultResponseContent, Client.DeserializationSettings);
            }
            catch (Newtonsoft.Json.JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Gets the OData routing conventions to use for controller and action selection.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>The OData routing conventions to use for controller and action selection associated with this request,
        /// or <c>null</c> if there aren't any.</returns>
        public static IEnumerable<IODataRoutingConvention> GetODataRoutingConventions(this HttpRequestMessage request)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            object routingConventions;
            if (request.Properties.TryGetValue(ODataRoutingConventionsKey, out routingConventions))
            {
                return routingConventions as IEnumerable<IODataRoutingConvention>;
            }

            return null;
        }
        // TODO:: Uncomment this code when using Mobile Services and inheriting from IServiceFilter
        #region implemented abstract members of HttpMessageHandler

        protected override async Task <System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            Busy(true);
            var response = await base.SendAsync(request, cancellationToken);

            Busy(false);
            return(response);
        }
Example #57
0
        public virtual async Task <IHttpCallResultCGHT <T> > MakeWebApiFromBodyCall <T>(
            Enums.HttpVerb httpVerb, ILogger log, HttpClient client, string requestUri, T item) where T : class
        {
            T retValData = default(T);

            System.Net.Http.HttpResponseMessage response = null;
            HttpCallResult <T> retVal = new HttpCallResult <T>();

            try
            {
                string serializedItem = JsonConvert.SerializeObject(item);
                var    inputMessage   = new System.Net.Http.HttpRequestMessage
                {
                    Content = new System.Net.Http.StringContent(serializedItem, System.Text.Encoding.UTF8, "application/json")
                };

                inputMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                if (httpVerb == Enums.HttpVerb.Post)
                {
                    response = await client.PostAsync(requestUri, inputMessage.Content);
                }
                else if (httpVerb == Enums.HttpVerb.Put)
                {
                    response = await client.PutAsync(requestUri, inputMessage.Content);
                }
                else
                {
                    throw new NotImplementedException();
                }

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = response.Content.ReadAsStringAsync();
                    retValData = JsonConvert.DeserializeObject <T>(responseContent.Result);
                }
                else
                {
                    log.LogWarning(eventId: (int)coreEnums.EventId.Warn_WebApiClient,
                                   message: "Failure during WebApiClient to Web API {HttpVerb} operation with {ReturnTypeName}. HttpResponseStatusCode: {HttpResponseStatusCode} from RequestUri {RequestUri}",
                                   Enum.GetName(typeof(Enums.HttpVerb), httpVerb),
                                   retVal?.GetType().Name,
                                   (int)response.StatusCode,
                                   requestUri);
                }

                retVal = new HttpCallResult <T>(
                    retValData, requestUri,
                    response.IsSuccessStatusCode, response.StatusCode, response.ReasonPhrase);
            }
            catch (Exception ex)
            {
                log.LogError(eventId: (int)coreEnums.EventId.Exception_WebApiClient,
                             exception: ex,
                             message: "Failure during WebApiClient to Web API {HttpVerb} operation with {ReturnTypeName}. HttpResponseStatusCode: {HttpResponseStatusCode} from RequestUri {RequestUri}",
                             Enum.GetName(typeof(Enums.HttpVerb), httpVerb),
                             retVal?.GetType().Name,
                             response == null ? 0 : (int)response.StatusCode,
                             requestUri);

                retVal = new HttpCallResult <T>(data: null, requestUri: requestUri, isSuccessStatusCode: response != null ? response.IsSuccessStatusCode : false,
                                                statusCode: response != null ? response.StatusCode : System.Net.HttpStatusCode.InternalServerError,
                                                reasonPhrase: response != null ? response.ReasonPhrase : ex.Message, exception: ex);
            }

            return(retVal);
        }
Example #58
0
        /// <summary>
        /// Get underflow date value
        /// </summary>
        /// <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 <System.DateTime?> > GetUnderflowDateWithHttpMessagesAsync(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, "GetUnderflowDate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/underflowdate").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 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, 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 HttpOperationResponse <System.DateTime?>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <System.DateTime?>(_responseContent, new DateJsonConverter());
                }
                catch (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);
        }
Example #59
0
        protected override System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            //LogRequest(request);

            return(base.SendAsync(request, cancellationToken).ContinueWith(task =>
            {
                var response = task.Result;

                LogResponse(response);

                return response;
            }));
        }
Example #60
0
        private static async Task <RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, RTHttpRequestHeaderCollection rtHeaderCollection)
        {
            HttpContent content = request.Content;

            RTIHttpContent      rtContent;
            ArraySegment <byte> buffer;

            // If we are buffered already, it is more efficient to send the data directly using the buffer with the
            // WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by
            // a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter.
            Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false);

            if (contentStream is RTIInputStream)
            {
                rtContent = new RTHttpStreamContent((RTIInputStream)contentStream);
            }
            else if (contentStream is MemoryStream)
            {
                var memStream = contentStream as MemoryStream;
                if (memStream.TryGetBuffer(out buffer))
                {
                    rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count);
                }
                else
                {
                    byte[] byteArray = memStream.ToArray();
                    rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint)byteArray.Length);
                }
            }
            else
            {
                rtContent = new RTHttpStreamContent(contentStream.AsInputStream());
            }

            // RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not.
            // Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now
            // and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the
            // .NET HttpRequestMessage and Content header collections.
            rtContent.Headers.ContentLength = null;

            // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
            // Desktop System.Net allows both headers to be specified but ends up stripping out
            // 'Content-Length' and using chunked semantics.  The WinRT APIs throw an exception so
            // we need to manually strip out the conflicting header to maintain app compatibility.
            if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value)
            {
                content.Headers.ContentLength = null;
            }
            else
            {
                // Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding
                content.Headers.ContentLength = content.Headers.ContentLength;
            }

            foreach (KeyValuePair <string, IEnumerable <string> > headerPair in content.Headers)
            {
                foreach (string value in headerPair.Value)
                {
                    if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value))
                    {
                        // rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers
                        // will allow custom headers.  If something is not successfully added to the content headers, try adding them to the standard headers.
                        bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value);
                        Debug.Assert(success);
                    }
                }
            }
            return(rtContent);
        }