Exemplo n.º 1
0
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task FromBodyTestAsync(GeoPoint location, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/FromBodyTest");
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(location, new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }));
 			content_.Headers.ContentType.MediaType = "application/json";
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "204") 
 			{
 				return;
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		}
 	}
Exemplo n.º 2
0
     /// <summary>Product Types</summary>
     /// <param name="latitude">Latitude component of location.</param>
     /// <param name="longitude">Longitude component of location.</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <returns>An array of products</returns>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<Product>> ProductsAsync(double latitude, double longitude, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}?", BaseUrl, "products");
 
         if (latitude == null)
             throw new System.ArgumentNullException("latitude");
         else
             url_ += string.Format("latitude={0}&", System.Uri.EscapeDataString(latitude.ToString()));
 
         if (longitude == null)
             throw new System.ArgumentNullException("longitude");
         else
             url_ += string.Format("longitude={0}&", System.Uri.EscapeDataString(longitude.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Method = new System.Net.Http.HttpMethod("GET");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				var result_ = default(System.Collections.ObjectModel.ObservableCollection<Product>); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.ObjectModel.ObservableCollection<Product>>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));                                
 					return result_; 
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 			}
 			else
 			{
 				var result_ = default(Error); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Error>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));
 
 				} 
 				catch (System.Exception exception_) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception_);
 				}
 
 				throw new SwaggerException<Error>("Unexpected error", status_, responseData_, result_, null);
 			}
 		
 			return default(System.Collections.ObjectModel.ObservableCollection<Product>);
 		}
 	}
Exemplo n.º 3
0
        /// <summary>
        /// status information to the smart things zone
        /// </summary>
        /// <param name="zoneInfo"></param>
        public static void UpdateZone(ZoneInfo zoneInfo)
        {
            try
            {
                OauthInfo authInfo = OauthRepository.Get();

                string url = authInfo.endpoints[0].uri + $"/UpdateZone";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
                parms.Add(new KeyValuePair<string, string>("Id", zoneInfo.Id.ToString()));
                parms.Add(new KeyValuePair<string, string>("Status", zoneInfo.Status));
                parms.Add(new KeyValuePair<string, string>("Name", zoneInfo.Name));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error updating smart things zone {zoneInfo.Id} with status {zoneInfo.Status}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error updating smart things zone {zoneInfo.Id} with status {zoneInfo.Status}.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
Exemplo n.º 4
0
        public static async Task<string> getHttpWebRequest(string api, List<KeyValuePair<String, String>> paramList = null, int PostORGet = 0, bool fulluri = false)
        {
            string content = "";
            return await Task.Run(() =>
            {
                if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    try
                    {
                        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                        string uri;
                        if (!fulluri)
                            uri = "http://hongyan.cqupt.edu.cn/" + api;
                        else
                            uri = api;
                        httpClient.DefaultRequestHeaders.Add("API_APP", "winphone");
                        httpClient.DefaultRequestHeaders.Add("API_TOKEN", "0zLUZA0j+OL77OsjXC0ulOz50KaI6yANZtkOk2vQIDg=");
                        System.Net.Http.HttpRequestMessage requst;
                        System.Net.Http.HttpResponseMessage response;
                        if (PostORGet == 0)
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(uri));
                            response = httpClient.PostAsync(new Uri(uri), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
                        }
                        else
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, new Uri(uri));
                            response = httpClient.GetAsync(new Uri(uri)).Result;
                        }
                        if (response.StatusCode == HttpStatusCode.OK)
                            content = response.Content.ReadAsStringAsync().Result;
                        //else if (response.StatusCode == HttpStatusCode.NotFound)
                        //    Utils.Message("Oh...服务器又跪了,给我们点时间修好它");

                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message + "网络请求异常");
                    }
                }
                else
                {
                }
                //if (content.IndexOf("{") != 0)
                //    return "";
                //else
                return content;

            });
        }
Exemplo n.º 5
0
     /// <summary>Update an existing pet</summary>
     /// <param name="body">Pet object that needs to be added to the store</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task UpdatePetAsync(Pet body, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "pet");
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body));
 			content_.Headers.ContentType.MediaType = "application/json";
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("PUT");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "400") 
 			{
 				throw new SwaggerException("Invalid ID supplied", status_, responseData_, null);
 			}
 			else
 			if (status_ == "404") 
 			{
 				throw new SwaggerException("Pet not found", status_, responseData_, null);
 			}
 			else
 			if (status_ == "405") 
 			{
 				throw new SwaggerException("Validation exception", status_, responseData_, null);
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		}
 	}
Exemplo n.º 6
0
        public static void Run()
        {
            /*
             * An example that composes a HttpRequest Message and sends it via the RestBus RabbitMQ client.
             *
             * For more examples, see the https://github.com/tenor/RestBus.Examples repo
             *
             */

            BasicMessageMapper msgMapper = new BasicMessageMapper("amqp://localhost:5672", "test");
            RestBusClient client = new RestBusClient(msgMapper);

            var msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, "/test/my_api")
            {
                Content = new System.Net.Http.StringContent("{\"Val\":10}", new UTF8Encoding(), "application/json")
            };

            msg.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01, */*; q=0.01");

            var res = client.SendAsync(msg, System.Threading.CancellationToken.None).Result;

            Console.ReadKey();
            client.Dispose();
        }
Exemplo n.º 7
0
 partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url);
Exemplo n.º 8
0
        /// <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 <string> UploadAsync(AccountDump accountDump, System.Threading.CancellationToken cancellationToken)
        {
            if (accountDump == null)
            {
                throw new System.ArgumentNullException("accountDump");
            }

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

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

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(accountDump, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");
                    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 <string>(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
            {
            }
        }
Exemplo n.º 9
0
     /// <summary>Get user by user name</summary>
     /// <param name="username">The name that needs to be fetched. Use user1 for testing.</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <returns>successful operation</returns>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task<User> GetUserByNameAsync(string username, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "user/{username}");
 
         if (username == null)
             throw new System.ArgumentNullException("username");
         url_ = url_.Replace("{username}", System.Uri.EscapeDataString(username.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Method = new System.Net.Http.HttpMethod("GET");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				var result_ = default(User); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<User>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));                                
 					return result_; 
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 			}
 			else
 			if (status_ == "400") 
 			{
 				throw new SwaggerException("Invalid username supplied", status_, responseData_, null);
 			}
 			else
 			if (status_ == "404") 
 			{
 				throw new SwaggerException("User not found", status_, responseData_, null);
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		
 			return default(User);
 		}
 	}
 protected override System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
 {
     throw null;
 }
Exemplo n.º 11
0
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<Person>> Find2Async(Gender? gender, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}?", BaseUrl, "api/Persons/find2");
 
         if (gender != null)
             url_ += string.Format("gender={0}&", System.Uri.EscapeDataString(gender.Value.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.StringContent(string.Empty);
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				var result_ = default(System.Collections.ObjectModel.ObservableCollection<Person>); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.ObjectModel.ObservableCollection<Person>>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() });                                
 					return result_; 
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		
 			return default(System.Collections.ObjectModel.ObservableCollection<Person>);
 		}
 	}
Exemplo n.º 12
0
     /// <summary>User Activity</summary>
     /// <param name="offset">Offset the list of returned results by this amount. Default is zero.</param>
     /// <param name="limit">Number of items to retrieve. Default is 5, maximum is 100.</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <returns>History information for the given user</returns>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task<Activities> HistoryAsync(int? offset, int? limit, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}?", BaseUrl, "history");
 
         if (offset != null)
             url_ += string.Format("offset={0}&", System.Uri.EscapeDataString(offset.Value.ToString()));
 
         if (limit != null)
             url_ += string.Format("limit={0}&", System.Uri.EscapeDataString(limit.Value.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Method = new System.Net.Http.HttpMethod("GET");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				var result_ = default(Activities); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Activities>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));                                
 					return result_; 
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 			}
 			else
 			{
 				var result_ = default(Error); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Error>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));
 
 				} 
 				catch (System.Exception exception_) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception_);
 				}
 
 				throw new SwaggerException<Error>("Unexpected error", status_, responseData_, result_, null);
 			}
 		
 			return default(Activities);
 		}
 	}
Exemplo n.º 13
0
        /// <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="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParametersInner parameterGroupingPostRequiredParameters, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (parameterGroupingPostRequiredParameters == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.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  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("body", body);
                tracingParameters.Add("customHeader", customHeader);
                tracingParameters.Add("query", query);
                tracingParameters.Add("path", path);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.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));
            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (query != null)
            {
                _queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _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 (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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, this.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 (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.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, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.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)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Exemplo n.º 14
0
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task UploadFilesAsync(System.Collections.Generic.IEnumerable<FileParameter> files, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/UploadFiles");
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.MultipartFormDataContent();
 			if (files != null)
 				foreach(var item_ in files) { content_.Add(new System.Net.Http.StreamContent(item_.Data), "files", item_.FileName ?? "files"); }
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "204") 
 			{
 				return;
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		}
 	}
Exemplo n.º 15
0
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task SetBaseAsync(int num, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (num == null)
            {
                throw new System.ArgumentNullException("num");
            }

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

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

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "application/json");
                    request_.Method  = new System.Net.Http.HttpMethod("POST");

                    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).ToString();
                        if (status_ == "200")
                        {
                            return;
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Creates an instance of an HTTP response message based on the information
 /// provided in the HTTP request message as an operation that will not block.
 /// </summary>
 protected override SystemTasks.Task <SystemHttpResponseMessage> SendAsync(SystemHttpRequestMessage request,
                                                                           SystemCancellationToken cancellationToken) =>
 base.SendAsync(HttpRequestMessage.WithRuntimeHeaders(request), cancellationToken);
Exemplo n.º 17
0
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task PutAsync(int id, Funcionario funcionario, 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/Funcionarios/{id}");
            urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));

            var client_ = new System.Net.Http.HttpClient();

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(funcionario, _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).ToString();
                        if (status_ == "204")
                        {
                            return;
                        }
                        else
                        if (status_ == "404")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("A server side error occurred.", (int)response_.StatusCode, responseData_, headers_, null);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemplo n.º 18
0
        public async System.Threading.Tasks.Task <TestRunInputResult> PostPublishAsync(TestRunInputData body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var urlBuilder_ = new System.Text.StringBuilder();

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

            var client_ = new System.Net.Http.HttpClient();

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("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);
                        foreach (var item_ in response_.Content.Headers)
                        {
                            headers_[item_.Key] = item_.Value;
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(TestRunInputResult);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <TestRunInputResult>(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ == "400")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("Invalid input", status_, responseData_, headers_, null);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        return(default(TestRunInputResult));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemplo n.º 19
0
        public async System.Threading.Tasks.Task <string> GetTestOutputAsync(string projectName, string testSuiteName, string buildNumber, string testFullName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (projectName == null)
            {
                throw new System.ArgumentNullException("projectName");
            }

            if (testSuiteName == null)
            {
                throw new System.ArgumentNullException("testSuiteName");
            }

            if (buildNumber == null)
            {
                throw new System.ArgumentNullException("buildNumber");
            }

            if (testFullName == null)
            {
                throw new System.ArgumentNullException("testFullName");
            }

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

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/testOutput/{projectName}/{testSuiteName}/{buildNumber}/{testFullName}");
            urlBuilder_.Replace("{projectName}", System.Uri.EscapeDataString(System.Convert.ToString(projectName, System.Globalization.CultureInfo.InvariantCulture)));
            urlBuilder_.Replace("{testSuiteName}", System.Uri.EscapeDataString(System.Convert.ToString(testSuiteName, System.Globalization.CultureInfo.InvariantCulture)));
            urlBuilder_.Replace("{buildNumber}", System.Uri.EscapeDataString(System.Convert.ToString(buildNumber, System.Globalization.CultureInfo.InvariantCulture)));
            urlBuilder_.Replace("{testFullName}", System.Uri.EscapeDataString(System.Convert.ToString(testFullName, System.Globalization.CultureInfo.InvariantCulture)));

            var client_ = new System.Net.Http.HttpClient();

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("GET");
                    request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("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);
                        foreach (var item_ in response_.Content.Headers)
                        {
                            headers_[item_.Key] = item_.Value;
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(string);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        return(default(string));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemplo n.º 20
0
 public static System.ServiceModel.Security.SecurityMessageProperty GetSecurityMessageProperty(this System.Net.Http.HttpRequestMessage request)
 {
     throw null;
 }
Exemplo n.º 21
0
 public async System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request)
 {
     return(await _client.SendAsync(request));
 }
Exemplo n.º 22
0
     /// <summary>Creates list of users with given input array</summary>
     /// <param name="body">List of user object</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <returns>successful operation</returns>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task CreateUsersWithListInputAsync(System.Collections.Generic.IEnumerable<User> body, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "user/createWithList");
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body));
 			content_.Headers.ContentType.MediaType = "application/json";
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 		}
 	}
Exemplo n.º 23
0
        /// <summary>Time Estimates</summary>
        /// <param name="start_latitude">Latitude component of start location.</param>
        /// <param name="start_longitude">Longitude component of start location.</param>
        /// <param name="customer_uuid">Unique customer identifier to be used for experience customization.</param>
        /// <param name="product_id">Unique identifier representing a specific product for a given latitude & longitude.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>An array of products</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <System.Collections.ObjectModel.ObservableCollection <Product> > TimeAsync(double start_latitude, double start_longitude, System.Guid?customer_uuid, string product_id, System.Threading.CancellationToken cancellationToken)
        {
            if (start_latitude == null)
            {
                throw new System.ArgumentNullException("start_latitude");
            }

            if (start_longitude == null)
            {
                throw new System.ArgumentNullException("start_longitude");
            }

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

            urlBuilder_.Append(BaseUrl).Append("/estimates/time?");
            urlBuilder_.Append("start_latitude=").Append(System.Uri.EscapeDataString(start_latitude.ToString())).Append("&");
            urlBuilder_.Append("start_longitude=").Append(System.Uri.EscapeDataString(start_longitude.ToString())).Append("&");
            if (customer_uuid != null)
            {
                urlBuilder_.Append("customer_uuid=").Append(System.Uri.EscapeDataString(customer_uuid.Value.ToString())).Append("&");
            }
            if (product_id != null)
            {
                urlBuilder_.Append("product_id=").Append(System.Uri.EscapeDataString(product_id.ToString())).Append("&");
            }
            urlBuilder_.Length--;

            var client_ = new System.Net.Http.HttpClient();

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    PrepareRequest(client_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    PrepareRequest(client_, url_);

                    request_.Method     = new System.Net.Http.HttpMethod("GET");
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    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);
                        foreach (var item_ in response_.Content.Headers)
                        {
                            headers_[item_.Key] = item_.Value;
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(System.Collections.ObjectModel.ObservableCollection <Product>);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.ObjectModel.ObservableCollection <Product> >(responseData_);
                                return(result_);
                            }
                            catch (System.Exception exception)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception);
                            }
                        }
                        else
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(Error);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <Error>(responseData_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception_);
                            }

                            throw new SwaggerException <Error>("Unexpected error", status_, responseData_, headers_, result_, null);
                        }

                        return(default(System.Collections.ObjectModel.ObservableCollection <Product>));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemplo n.º 24
0
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task<byte[]> GetUploadedFileAsync(int id, bool? @override, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}?", BaseUrl, "api/Geo/GetUploadedFile/{id}");
 
         if (id == null)
             throw new System.ArgumentNullException("id");
         url_ = url_.Replace("{id}", System.Uri.EscapeDataString(id.ToString()));
 
         if (@override == null)
             throw new System.ArgumentNullException("@override");
         else
             url_ += string.Format("override={0}&", System.Uri.EscapeDataString(@override.Value.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Method = new System.Net.Http.HttpMethod("GET");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				return responseData_; 
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		
 			return default(byte[]);
 		}
 	}
Exemplo n.º 25
0
        /// <summary>User Activity</summary>
        /// <param name="offset">Offset the list of returned results by this amount. Default is zero.</param>
        /// <param name="limit">Number of items to retrieve. Default is 5, maximum is 100.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>History information for the given user</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <Activities> HistoryAsync(int?offset, int?limit, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl).Append("/history?");
            if (offset != null)
            {
                urlBuilder_.Append("offset=").Append(System.Uri.EscapeDataString(offset.Value.ToString())).Append("&");
            }
            if (limit != null)
            {
                urlBuilder_.Append("limit=").Append(System.Uri.EscapeDataString(limit.Value.ToString())).Append("&");
            }
            urlBuilder_.Length--;

            var client_ = new System.Net.Http.HttpClient();

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    PrepareRequest(client_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    PrepareRequest(client_, url_);

                    request_.Method     = new System.Net.Http.HttpMethod("GET");
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    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);
                        foreach (var item_ in response_.Content.Headers)
                        {
                            headers_[item_.Key] = item_.Value;
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(Activities);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <Activities>(responseData_);
                                return(result_);
                            }
                            catch (System.Exception exception)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception);
                            }
                        }
                        else
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(Error);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <Error>(responseData_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception_);
                            }

                            throw new SwaggerException <Error>("Unexpected error", status_, responseData_, headers_, result_, null);
                        }

                        return(default(Activities));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemplo n.º 26
0
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task FromUriTestAsync(double? latitude, double? longitude, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}?", BaseUrl, "api/Geo/FromUriTest");
 
         if (latitude == null)
             throw new System.ArgumentNullException("latitude");
         else
             url_ += string.Format("Latitude={0}&", System.Uri.EscapeDataString(latitude.Value.ToString()));
 
         if (longitude == null)
             throw new System.ArgumentNullException("longitude");
         else
             url_ += string.Format("Longitude={0}&", System.Uri.EscapeDataString(longitude.Value.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.StringContent(string.Empty);
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "204") 
 			{
 				return;
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		}
 	}
Exemplo n.º 27
0
 public ModelFactory(System.Net.Http.HttpRequestMessage request, ApplicationUserManager appUserManager)
 {
     _UrlHelper      = new UrlHelper(request);
     _AppUserManager = appUserManager;
 }
Exemplo n.º 28
0
        public IActionResult Authorized(string code)
        {
            OauthInfo oai = OauthRepository.Get();

            if (code == null)
                return View(oai);

            oai.authCode = code;

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            var url = "https://graph.api.smartthings.com/oauth/token";

            List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
            parms.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
            parms.Add(new KeyValuePair<string, string>("code", oai.authCode));
            parms.Add(new KeyValuePair<string, string>("client_id", oai.clientKey));
            parms.Add(new KeyValuePair<string, string>("client_secret", oai.secretKey));
            string authorizedUrl = "http://" + this.Request.Host.Value + this.Url.Content("~/OAuth/Authorized");
            parms.Add(new KeyValuePair<string, string>("redirect_uri", authorizedUrl));

            var content = new System.Net.Http.FormUrlEncodedContent(parms);
            var response = client.PostAsync(url, content);
            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get Auth Code Error: " + response.Result.StatusCode.ToString());
                return View(oai);
            }

            // Save the interim result
            var val = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Result.Content.ReadAsStringAsync().Result);
            oai.accessToken = val["access_token"];
            oai.expiresInSeconds = Convert.ToInt32(val["expires_in"]);
            oai.tokenType = val["token_type"];
            OauthRepository.Save(oai);

            // Get the endpoint info
            client = new System.Net.Http.HttpClient();
            url = "https://graph.api.smartthings.com/api/smartapps/endpoints";

            System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
            msg.Headers.Add("Authorization", $"Bearer {oai.accessToken}");

            response = client.SendAsync(msg);
            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get EndPoints Error: " + response.Result.StatusCode.ToString());
                return View(oai);
            }

            string jsonString = response.Result.Content.ReadAsStringAsync().Result;
            oai.endpoints = JsonConvert.DeserializeObject<List<OauthEndpoint>>(jsonString);

            OauthRepository.Save(oai);

            // Install the Zones
            SmartThingsRepository.InstallDevices(this.Request.Host.Value);
            return View(oai);

        }
Exemplo n.º 29
0
 partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url)
 {
     CredentialProvider.AddCredentials(request);
 }
Exemplo n.º 30
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <summary>CancelInvoice cancels a currently open invoice. If the invoice is already
        /// <br/>canceled, this call will succeed. If the invoice is already settled, it will
        /// <br/>fail.</summary>
        /// <returns>A successful response.</returns>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async Task <InvoicesrpcCancelInvoiceResp> CancelInvoiceAsync(InvoicesrpcCancelInvoiceMsg body,
                                                                            CancellationToken cancellationToken)
        {
            if (body == null)
            {
                throw new System.ArgumentNullException("body");
            }

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

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/v2/invoices/cancel");

            var client_        = _httpClient;
            var disposeClient_ = false;

            try
            {
                using var request_ = new System.Net.Http.HttpRequestMessage();
                var content_ =
                    new System.Net.Http.StringContent(
                        Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value));
                content_.Headers.ContentType =
                    System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                request_.Content = content_;
                request_.Method  = new System.Net.Http.HttpMethod("POST");
                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);

                var disposeResponse_ = true;
                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 responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                        var result_ = default(InvoicesrpcCancelInvoiceResp);
                        try
                        {
                            result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <InvoicesrpcCancelInvoiceResp>(
                                responseData_, _settings.Value);
                            return(result_);
                        }
                        catch (System.Exception exception)
                        {
                            throw new SwaggerException("Could not deserialize the response body.",
                                                       status_.ToString(), responseData_, headers_, exception);
                        }
                    }
                    else
                    {
                        var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                        throw new SwaggerException(
                                  "The HTTP status code of the response was not expected (" +
                                  (int)response_.StatusCode + ").", status_.ToString(), responseData_, headers_,
                                  null);
                    }
                }
                finally
                {
                    if (disposeResponse_)
                    {
                        response_.Dispose();
                    }
                }
            }
            finally
            {
                if (disposeClient_)
                {
                    client_.Dispose();
                }
            }
        }
Exemplo n.º 31
0
 internal void Trace(System.Net.Http.HttpRequestMessage Request, string p1, System.Diagnostics.TraceLevel traceLevel, string p2, string p3)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 32
0
        /// <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 <AccountDump> GetAsync(string id, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Account?");
            if (id != null)
            {
                urlBuilder_.Append(System.Uri.EscapeDataString("id") + "=").Append(System.Uri.EscapeDataString(ConvertToString(id, 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 <AccountDump>(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
            {
            }
        }
Exemplo n.º 33
0
 public object GetInstance(Type serviceType, InstanceContext instanceContext, System.Net.Http.HttpRequestMessage request)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 34
0
 partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
Exemplo n.º 35
0
        /// <summary>
        /// Return 501 status code - should be represented in the client as an error
        /// </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 System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <Error> > Head501WithHttpMessagesAsync(System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head501", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString();

            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("HEAD");
            _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)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.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, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.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, this.Client.DeserializationSettings);
            }
            catch (Newtonsoft.Json.JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Get method with unencoded query parameter with value
        /// 'value1&amp;q2=value2&amp;q3=value3'
        /// </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 System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse> GetSwaggerQueryValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            string q1 = "value1&q2=value2&q3=value3";
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("q1", q1);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerQueryValid", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/swagger/query/valid").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (q1 != null)
            {
                _queryParameters.Add(string.Format("q1={0}", q1));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _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 (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.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, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.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)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Exemplo n.º 37
0
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <OptimalConsumptionPrognosis> OptimalConsumptionTimeAsync(string region, int?hours, string earliestConsumptionTime, string latestConsumptionTime, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Prognosis/suggest?");
            if (region != null)
            {
                urlBuilder_.Append("region=").Append(System.Uri.EscapeDataString(ConvertToString(region, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (hours != null)
            {
                urlBuilder_.Append("hours=").Append(System.Uri.EscapeDataString(ConvertToString(hours, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (earliestConsumptionTime != null)
            {
                urlBuilder_.Append("earliestConsumptionTime=").Append(System.Uri.EscapeDataString(ConvertToString(earliestConsumptionTime, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (latestConsumptionTime != null)
            {
                urlBuilder_.Append("latestConsumptionTime=").Append(System.Uri.EscapeDataString(ConvertToString(latestConsumptionTime, 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).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(OptimalConsumptionPrognosis);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <OptimalConsumptionPrognosis>(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        return(default(OptimalConsumptionPrognosis));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
        /// <summary>
        /// Install or Update Devices in the SmartThings App
        /// </summary>
        public static void InstallDevices(string hostString)
        {
            try
            {
                var alarm = AlarmSystemRepository.Get();
                if (string.IsNullOrEmpty(alarm.j64Server) || string.IsNullOrEmpty(alarm.j64Port))
                    Determinej64ServerAddress(hostString);

                OauthInfo authInfo = OauthRepository.Get();

                if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    MyLogger.LogError("OAuth endpoints have not been created. Cannot update smart things at this time");
                    return;
                }
                string url = authInfo.endpoints[0].uri + $"/installDevices";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
                parms.Add(new KeyValuePair<string, string>("j64Server", alarm.j64Server));
                parms.Add(new KeyValuePair<string, string>("j64Port", alarm.j64Port));
                parms.Add(new KeyValuePair<string, string>("j64UserName", "admin"));
                parms.Add(new KeyValuePair<string, string>("j64Password", "Admin_01"));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error installing smart things devices.  StatusCode was {response.Result.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error installing smart things devices.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
Exemplo n.º 39
0
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <System.Collections.Generic.ICollection <EmissionDataDTO> > GetMostRecentEmissionsAsync(System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

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

            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).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(System.Collections.Generic.ICollection <EmissionDataDTO>);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.Generic.ICollection <EmissionDataDTO> >(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        return(default(System.Collections.Generic.ICollection <EmissionDataDTO>));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Exemplo n.º 40
0
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task<bool> UploadFileAsync(FileParameter file, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/UploadFile");
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.MultipartFormDataContent();
 			if (file != null)
 				content_.Add(new System.Net.Http.StreamContent(file.Data), "file", file.FileName ?? "file");
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				var result_ = default(bool); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<bool>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() });                                
 					return result_; 
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		
 			return default(bool);
 		}
 	}
Exemplo n.º 41
0
        /// <param name="payload">JSON with WatchlistItem ExternalId (if item does not exist then it will be created), </br>
        /// ImageData with base64 encoded images of single face with MIME type, <br>
        /// Watchlist ExternalIds which will be linked to WatchlistItem (if watchlists do not exists then they will be created with default threshold).</param>
        /// <returns>NoContent</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <FileResponse> RegisterAsync(RegisterWlItemData payload, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/rpc/WatchlistItems/Register");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");
                    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).ToString();
                        if (status_ == "204" || status_ == "206")
                        {
                            var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        return(default(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Exemplo n.º 42
0
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task SaveItemsAsync(GenericRequestOfAddressAndPerson request, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/SaveItems");
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(request, new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }));
 			content_.Headers.ContentType.MediaType = "application/json";
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "204") 
 			{
 				return;
 			}
 			else
 			if (status_ == "450") 
 			{
 				var result_ = default(System.Exception); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Exception>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() });                                
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 				if (result_ == null)
 					result_ = new System.Exception();
 				result_.Data.Add("HttpStatus", status_);
 				result_.Data.Add("ResponseData", System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));
 				throw new SwaggerException<System.Exception>("A custom error occured.", status_, responseData_, result_, result_);
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		}
 	}
 public static string GetToken(System.Net.Http.HttpRequestMessage httpRequest)
 {
     return(httpRequest.Headers.Authorization?.Parameter);
 }
Exemplo n.º 44
0
     /// <summary>Place an order for a pet</summary>
     /// <param name="body">order placed for purchasing the pet</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <returns>successful operation</returns>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task<Order> PlaceOrderAsync(Order body, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "store/order");
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body));
 			content_.Headers.ContentType.MediaType = "application/json";
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				var result_ = default(Order); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));                                
 					return result_; 
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 			}
 			else
 			if (status_ == "400") 
 			{
 				throw new SwaggerException("Invalid Order", status_, responseData_, null);
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		
 			return default(Order);
 		}
 	}
Exemplo n.º 45
0
        /// <summary>
        /// Install or Update Devices in the SmartThings App
        /// </summary>
        public static void InstallDevices(string hostString)
        {
            try
            {
                string[] h = hostString.Split(':');
                string j64Server = h[0];
                int j64Port = 80;
                if (h.Length > 1)
                    j64Port = Convert.ToInt32(h[1]);

                var hostName = System.Net.Dns.GetHostEntryAsync(System.Net.Dns.GetHostName());
                hostName.Wait();
                foreach (var i in hostName.Result.AddressList)
                {
                    if (i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        j64Server = i.ToString();
                        break;
                    }
                }

                OauthInfo authInfo = OauthRepository.Get();

                if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    MyLogger.LogError("OAuth endpoints have not been created. Cannot update smart things at this time");
                    return;
                }
                string url = authInfo.endpoints[0].uri + $"/installDevices";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
                parms.Add(new KeyValuePair<string, string>("j64Server", j64Server));
                parms.Add(new KeyValuePair<string, string>("j64Port", j64Port.ToString()));
                parms.Add(new KeyValuePair<string, string>("j64UserName", "admin"));
                parms.Add(new KeyValuePair<string, string>("j64Password", "Admin_01"));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error installing smart things devices.  StatusCode was {response.Result.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error installing smart things devices.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
Exemplo n.º 46
0
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task DeleteAsync(System.Guid id, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "api/Persons/{id}");
 
         if (id == null)
             throw new System.ArgumentNullException("id");
         url_ = url_.Replace("{id}", System.Uri.EscapeDataString(id.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Method = new System.Net.Http.HttpMethod("DELETE");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "204") 
 			{
 				return;
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		}
 	}
Exemplo n.º 47
0
        /// <summary>
        /// status information to the smart things zone
        /// </summary>
        /// <param name="zoneInfo"></param>
        public static void UpdatePartition(PartitionInfo partitionInfo)
        {
            try
            {
                OauthInfo authInfo = OauthRepository.Get();

                if (authInfo == null || authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    MyLogger.LogError($"OAuth endpoints have not been created.  Cannot update smart things at this time");
                    return;
                }
                string url = authInfo.endpoints[0].uri + $"/UpdatePartition";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
                parms.Add(new KeyValuePair<string, string>("Id", partitionInfo.Id.ToString()));
                parms.Add(new KeyValuePair<string, string>("Name", partitionInfo.Name));
                parms.Add(new KeyValuePair<string, string>("ReadyToArm", partitionInfo.ReadyToArm.ToString()));
                parms.Add(new KeyValuePair<string, string>("IsArmed", partitionInfo.IsArmed.ToString()));
                parms.Add(new KeyValuePair<string, string>("ArmingMode", partitionInfo.ArmingMode));
                parms.Add(new KeyValuePair<string, string>("AlarmOn", partitionInfo.AlarmOn.ToString()));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error updating smart things partition {partitionInfo.Id} with status {partitionInfo.ArmingMode}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error updating smart things partition {partitionInfo.Id} with status {partitionInfo.ArmingMode}.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
Exemplo n.º 48
0
     /// <summary>Gets the name of a person.</summary>
     /// <param name="id">The person ID.</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <returns>The person's name.</returns>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task<string> GetNameAsync(System.Guid id, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "api/Persons/{id}/Name");
 
         if (id == null)
             throw new System.ArgumentNullException("id");
         url_ = url_.Replace("{id}", System.Uri.EscapeDataString(id.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Method = new System.Net.Http.HttpMethod("GET");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				var result_ = default(string); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() });                                
 					return result_; 
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 			}
 			else
 			if (status_ == "500") 
 			{
 				var result_ = default(PersonNotFoundException); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<PersonNotFoundException>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length), new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() });                                
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 				if (result_ == null)
 					result_ = new PersonNotFoundException();
 				result_.Data.Add("HttpStatus", status_);
 				result_.Data.Add("ResponseData", System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));
 				throw new SwaggerException<PersonNotFoundException>("A server side error occurred.", status_, responseData_, result_, result_);
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		
 			return default(string);
 		}
 	}
Exemplo n.º 49
0
     /// <summary>Updates a pet in the store with form data</summary>
     /// <param name="petId">ID of pet that needs to be updated</param>
     /// <param name="name">Updated name of the pet</param>
     /// <param name="status">Updated status of the pet</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task UpdatePetWithFormAsync(int petId, string name, string status, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "pet/{petId}");
 
         if (petId == null)
             throw new System.ArgumentNullException("petId");
         url_ = url_.Replace("{petId}", System.Uri.EscapeDataString(petId.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			var content_ = new System.Net.Http.MultipartFormDataContent();
 			if (name != null)
 				content_.Add(new System.Net.Http.StringContent(name.ToString()), "name");
 			if (status != null)
 				content_.Add(new System.Net.Http.StringContent(status.ToString()), "status");
 			request_.Content = content_;
 			request_.Method = new System.Net.Http.HttpMethod("POST");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "405") 
 			{
 				throw new SwaggerException("Invalid input", status_, responseData_, null);
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		}
 	}
Exemplo n.º 50
0
     /// <summary>Deletes a pet</summary>
     /// <param name="petId">Pet id to delete</param>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task DeletePetAsync(string api_key, int petId, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "pet/{petId}");
 
         if (petId == null)
             throw new System.ArgumentNullException("petId");
         url_ = url_.Replace("{petId}", System.Uri.EscapeDataString(petId.ToString()));
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Headers.TryAddWithoutValidation("api_key", api_key);
 			request_.Method = new System.Net.Http.HttpMethod("DELETE");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "400") 
 			{
 				throw new SwaggerException("Invalid ID supplied", status_, responseData_, null);
 			}
 			else
 			if (status_ == "404") 
 			{
 				throw new SwaggerException("Pet not found", status_, responseData_, null);
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		}
 	}
Exemplo n.º 51
0
        /// <summary>Runtime makes this request in order to submit an error response. It can be either a function error, or a runtime error. Error will be served in response to the invoke.</summary>
        /// <returns>Accepted</returns>
        /// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <SwaggerResponse <StatusResponse> > Error2Async(string awsRequestId, string lambda_Runtime_Function_Error_Type, string errorJson, System.Threading.CancellationToken cancellationToken)
        {
            if (awsRequestId == null)
            {
                throw new System.ArgumentNullException("awsRequestId");
            }

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

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/runtime/invocation/{AwsRequestId}/error");
            urlBuilder_.Replace("{AwsRequestId}", System.Uri.EscapeDataString(ConvertToString(awsRequestId, System.Globalization.CultureInfo.InvariantCulture)));

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    if (lambda_Runtime_Function_Error_Type != null)
                    {
                        request_.Headers.TryAddWithoutValidation("Lambda-Runtime-Function-Error-Type", ConvertToString(lambda_Runtime_Function_Error_Type, System.Globalization.CultureInfo.InvariantCulture));
                    }
                    using (var content_ = new System.Net.Http.StringContent(errorJson))
                    {
                        content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(ErrorContentType);
                        request_.Content             = content_;
                        request_.Method = new System.Net.Http.HttpMethod("POST");
                        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).ToString();
                            if (status_ == "202")
                            {
                                var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                                var result_ = default(StatusResponse);
                                try
                                {
                                    result_ = ThirdParty.Json.LitJson.JsonMapper.ToObject <StatusResponse>(responseData_);
                                    return(new SwaggerResponse <StatusResponse>((int)response_.StatusCode, headers_, result_));
                                }
                                catch (System.Exception exception_)
                                {
                                    throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                                }
                            }
                            else
                            if (status_ == "400")
                            {
                                var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                                var result_ = default(ErrorResponse);
                                try
                                {
                                    result_ = ThirdParty.Json.LitJson.JsonMapper.ToObject <ErrorResponse>(responseData_);
                                }
                                catch (System.Exception exception_)
                                {
                                    throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                                }
                                throw new RuntimeApiClientException <ErrorResponse>("Bad Request", (int)response_.StatusCode, responseData_, headers_, result_, null);
                            }
                            else
                            if (status_ == "403")
                            {
                                var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                                var result_ = default(ErrorResponse);
                                try
                                {
                                    result_ = ThirdParty.Json.LitJson.JsonMapper.ToObject <ErrorResponse>(responseData_);
                                }
                                catch (System.Exception exception_)
                                {
                                    throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                                }
                                throw new RuntimeApiClientException <ErrorResponse>("Forbidden", (int)response_.StatusCode, responseData_, headers_, result_, null);
                            }
                            else
                            if (status_ == "500")
                            {
                                var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                                throw new RuntimeApiClientException("Container error. Non-recoverable state. Runtime should exit promptly.\n", (int)response_.StatusCode, responseData_, headers_, null);
                            }
                            else
                            if (status_ != "200" && status_ != "204")
                            {
                                var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                            return(new SwaggerResponse <StatusResponse>((int)response_.StatusCode, headers_, default(StatusResponse)));
                        }
                        finally
                        {
                            if (response_ != null)
                            {
                                response_.Dispose();
                            }
                        }
                    }
                }
            }
            finally
            {
            }
        }
Exemplo n.º 52
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="searchDate">Date in yyyy-MM-dd format</param>
        /// <param name="searchTime">Time in HH:mm military format</param>
        /// <returns></returns>
        public static async Task <Availability[]> GetTimesAsync(string searchDate, string searchTime)
        {
            var token = await GetAccessToken();

            var partySize = 2;

            var uri     = $"https://disneyworld.disney.go.com/api/wdpro/explorer-service/public/finder/dining-availability/80007798;entityType=destination?searchDate={searchDate}&partySize={partySize}&searchTime={searchTime}";//22%3A00";
            var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, new Uri(uri));

            request.Headers.Add("Authorization", "BEARER " + token.access_token);
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add("Referer", "https://disneyworld.disney.go.com/dining/");
            request.Headers.Add("type", "dining");

            var agentString = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";

            var client = new System.Net.Http.HttpClient();

            client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
            client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
            client.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");
            client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-us");
            client.DefaultRequestHeaders.UserAgent.ParseAdd(agentString);
            try
            {
                var test = await client.SendAsync(request);

                var content     = test.Content.ToString();
                var restaurants = Restaurant.GetRestaurants();


                var avail = (from each in JObject.Parse(content)["availability"]
                             where ((JProperty)each).Name.Contains("rest")
                             orderby((JProperty)each).Name ascending
                             select new Availability
                {
                    Restaurant = restaurants.FirstOrDefault(x => x.EntityId == int.Parse(((JProperty)each).Name.Split(';')[0])),
                    Offers = (from eachAvail in each.Values("availableTimes")
                              from eachOffer in eachAvail.Values("offers").Values()
                              select new Offer
                    {
                        TimeString = eachOffer["time"].Value <string>(),
                        DateAndTime = eachOffer["dateTime"].Value <DateTime>(),
                    }).ToList()
                    ,
                }).OrderBy(x => x.Restaurant.Name).ToArray();


                return(avail);
            }
            //Catch exception if trying to add a restricted header.
            catch (ArgumentException e1)
            {
                // Console.WriteLine(e.Message);
            }
            catch (Exception e1)
            {
                // Console.WriteLine("Exception is thrown. Message is :" + e.Message);
            }

            return(null);
        }
Exemplo n.º 53
0
     /// <summary>Logs out current logged in user session</summary>
     /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
     /// <returns>successful operation</returns>
     /// <exception cref="SwaggerException">A server side error occurred.</exception>
     public async System.Threading.Tasks.Task LogoutUserAsync(System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}", BaseUrl, "user/logout");
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Method = new System.Net.Http.HttpMethod("GET");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 		}
 	}
Exemplo n.º 54
0
            protected override async System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
            {
                // Replace the RequestUri so it's not malformed
                if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
                {
                    request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
                }

                return(await base.SendAsync(request, cancellationToken));
            }
Exemplo n.º 55
0
        /// <summary>Runtime makes this HTTP request when it is ready to receive and process a new invoke.</summary>
        /// <returns>This is an iterator-style blocking API call. Response contains event JSON document, specific to the invoking service.</returns>
        /// <exception cref="RuntimeApiClientException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <SwaggerResponse <System.IO.Stream> > NextAsync(System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/runtime/invocation/next");

            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).ToString();
                        if (status_ == "200")
                        {
                            var inputBuffer = response_.Content == null ? null : await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                            return(new SwaggerResponse <System.IO.Stream>((int)response_.StatusCode, headers_, new System.IO.MemoryStream(inputBuffer)));
                        }
                        else
                        if (status_ == "403")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(ErrorResponse);
                            try
                            {
                                result_ = ThirdParty.Json.LitJson.JsonMapper.ToObject <ErrorResponse>(responseData_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new RuntimeApiClientException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                            throw new RuntimeApiClientException <ErrorResponse>("Forbidden", (int)response_.StatusCode, responseData_, headers_, result_, null);
                        }
                        else
                        if (status_ == "500")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new RuntimeApiClientException("Container error. Non-recoverable state. Runtime should exit promptly.\n", (int)response_.StatusCode, responseData_, headers_, null);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        return(new SwaggerResponse <System.IO.Stream>((int)response_.StatusCode, headers_, new System.IO.MemoryStream(0)));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Exemplo n.º 56
0
 public void SetUp()
 {
     var encoding = new UTF8Encoding(false);
     _sampleBody = encoding.GetBytes("Action=ListUsers&Version=2010-05-08");
     #if NETCOREAPP1_0
     var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://iam.amazonaws.com/");
     request.Content = new System.Net.Http.ByteArrayContent(_sampleBody);
     request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
     request.Headers.TryAddWithoutValidation("X-Amz-Date", "20110909T233600Z");
     _sampleRequest = new HttpRequestMessageAdapter(request);
     #elif NET451
     var request = System.Net.WebRequest.CreateHttp("https://iam.amazonaws.com/");
     request.Method = "POST";
     request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
     request.Headers["X-Amz-Date"] = "20110909T233600Z";
     _sampleRequest = new HttpWebRequestAdapter(request);
     #endif
 }
Exemplo n.º 57
0
     public async System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<Pet>> FindPetsByTagsAsync(System.Collections.Generic.IEnumerable<string> tags, System.Threading.CancellationToken cancellationToken)
     {
         var url_ = string.Format("{0}/{1}?", BaseUrl, "pet/findByTags");
 
         if (tags == null)
             throw new System.ArgumentNullException("tags");
         else
             foreach(var item_ in tags) { url_ += string.Format("tags={0}&", System.Uri.EscapeDataString(item_.ToString())); }
 
         using (var client_ = new System.Net.Http.HttpClient())
 		{
 			var request_ = new System.Net.Http.HttpRequestMessage();
 			PrepareRequest(client_, ref url_);
 			request_.Method = new System.Net.Http.HttpMethod("GET");
 			request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 			var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
 			ProcessResponse(client_, response_);
 
 			var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 
 			var status_ = ((int)response_.StatusCode).ToString();
 
 			if (status_ == "200") 
 			{
 				var result_ = default(System.Collections.ObjectModel.ObservableCollection<Pet>); 
 				try
 				{
 					if (responseData_.Length > 0)
 						result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.ObjectModel.ObservableCollection<Pet>>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));                                
 					return result_; 
 				} 
 				catch (System.Exception exception) 
 				{
 					throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
 				}
 			}
 			else
 			if (status_ == "400") 
 			{
 				throw new SwaggerException("Invalid tag value", status_, responseData_, null);
 			}
 			else
 			if (status_ != "200" && status_ != "204")
 				throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
 		
 			return default(System.Collections.ObjectModel.ObservableCollection<Pet>);
 		}
 	}