Exemple #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);
 		}
 	}
Exemple #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>);
 		}
 	}
        /// <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)}");
            }
        }
        /// <returns>Success</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 ApiByVersionEndpointByEndpointEventPostAsync(string endpoint, string x_Congether_SIGN, EndpointMessageQueue eventQueue, System.Threading.CancellationToken cancellationToken)
        {
            if (endpoint == null)
            {
                throw new System.ArgumentNullException("endpoint");
            }

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

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

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

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    if (x_Congether_SIGN != null)
                    {
                        request_.Headers.TryAddWithoutValidation("X-Congether-SIGN", ConvertToString(x_Congether_SIGN, System.Globalization.CultureInfo.InvariantCulture));
                    }
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(eventQueue, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");

                    //SIGN CONTENT
                    if (x_Congether_SIGN == null)
                    {
                        request_.Headers.TryAddWithoutValidation("X-Congether-SIGN", ConvertToString(GetHMACSHA256(await content_.ReadAsStreamAsync(), _apiSecret), System.Globalization.CultureInfo.InvariantCulture));
                    }
                    //END SIGN CONTENT

                    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
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Init(Context context, string cdn = null, string downloadTitle = null, string downloadMessage = null)
        {
            if (_initialized)
            {
                return;
            }

            if (cdn != null)
            {
                CDNHost = cdn;
            }

            // do all initialization...
            var filesDir = context.FilesDir;

            _ffmpegFile = new Java.IO.File(filesDir + "/ffmpeg");

            FFMpegSource source = FFMpegSource.Get();

            await Task.Run(() =>
            {
                if (_ffmpegFile.Exists())
                {
                    try
                    {
                        if (source.IsHashMatch(System.IO.File.ReadAllBytes(_ffmpegFile.CanonicalPath)))
                        {
                            if (!_ffmpegFile.CanExecute())
                            {
                                _ffmpegFile.SetExecutable(true);
                            }
                            _initialized = true;
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($" Error validating file {ex}");
                    }

                    // file is not same...

                    // delete the file...

                    if (_ffmpegFile.CanExecute())
                    {
                        _ffmpegFile.SetExecutable(false);
                    }
                    _ffmpegFile.Delete();
                    System.Diagnostics.Debug.WriteLine($"ffmpeg file deleted at {_ffmpegFile.AbsolutePath}");
                }
            });

            if (_initialized)
            {
                // ffmpeg file exists...
                return;
            }

            if (_ffmpegFile.Exists())
            {
                _ffmpegFile.Delete();
            }

            // lets try to download
            var dialog = new ProgressDialog(context);

            dialog.SetTitle(downloadMessage ?? "Downloading Video Converter");
            //dlg.SetMessage(downloadMessage ?? "Downloading Video Converter");
            dialog.Indeterminate = false;
            dialog.SetProgressStyle(ProgressDialogStyle.Horizontal);
            dialog.SetCancelable(false);
            dialog.CancelEvent += (s, e) =>
            {
            };

            dialog.SetCanceledOnTouchOutside(false);
            dialog.Show();
            using (var c = new System.Net.Http.HttpClient())
            {
                using (var fout = System.IO.File.OpenWrite(_ffmpegFile.AbsolutePath))
                {
                    string url = source.Url;
                    var    g   = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);

                    var h = await c.SendAsync(g, System.Net.Http.HttpCompletionOption.ResponseHeadersRead);

                    var buffer = new byte[51200];

                    var s = await h.Content.ReadAsStreamAsync();

                    long total = h.Content.Headers.ContentLength.GetValueOrDefault();

                    IEnumerable <string> sl;
                    if (h.Headers.TryGetValues("Content-Length", out sl))
                    {
                        if (total == 0 && sl.Any())
                        {
                            long.TryParse(sl.FirstOrDefault(), out total);
                        }
                    }

                    int count    = 0;
                    int progress = 0;

                    dialog.Max = (int)total;

                    while ((count = await s.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        await fout.WriteAsync(buffer, 0, count);

                        progress += count;

                        //System.Diagnostics.Debug.WriteLine($"Downloaded {progress} of {total} from {url}");

                        dialog.Progress = progress;
                    }
                    dialog.Hide();
                }
            }

            System.Diagnostics.Debug.WriteLine($"ffmpeg file copied at {_ffmpegFile.AbsolutePath}");

            if (!_ffmpegFile.CanExecute())
            {
                _ffmpegFile.SetExecutable(true);
                System.Diagnostics.Debug.WriteLine($"ffmpeg file made executable");
            }

            _initialized = true;
        }
Exemple #6
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 DeleteShopAsync(System.Guid id, System.Collections.Generic.IEnumerable <string> additionalIds, System.Threading.CancellationToken cancellationToken)
        {
            if (id == null)
            {
                throw new System.ArgumentNullException("id");
            }

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

            urlBuilder_.Append(BaseUrl).Append("/api/SampleData?");
            urlBuilder_.Append("id=").Append(System.Uri.EscapeDataString(System.Convert.ToString(id, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            urlBuilder_.Length--;

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

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

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

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

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        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_ = 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);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #7
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);
 		}
 	}
Exemple #8
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, string value, 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/Values/{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(value, _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_ == "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
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #9
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[]);
 		}
 	}
Exemple #10
0
        // https://stackoverflow.com/questions/11414987/what-header-should-be-used-for-sending-gzip-compressed-json-from-android-client
        public async System.Threading.Tasks.Task <string> Post()
        {
            string text = null;

            byte[] data = System.IO.File.ReadAllBytes("10G.gzip");

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                client.DefaultRequestHeaders.Add("Content-Encoding", "gzip");

                using (System.IO.Stream ms = new System.IO.MemoryStream(data))
                {
                    using (System.Net.Http.StreamContent streamContent = new System.Net.Http.StreamContent(ms))
                    {
                        streamContent.Headers.Add("Content-Encoding", "gzip");
                        streamContent.Headers.ContentLength = ms.Length;

                        System.Uri target = new System.Uri("http://yourServer/yourPage");
                        using (System.Net.Http.HttpRequestMessage requestMessage = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, target))
                        {
                            requestMessage.Content = streamContent;
                            using (System.Net.Http.HttpResponseMessage response = await client.SendAsync(requestMessage))
                            {
                                text = await response.Content.ReadAsStringAsync();
                            } // End using response
                        }     // End Using requestMessage
                    }         // End Using streamContent
                }             // End Using ms
            }                 // End Using client

            return(text);
        } // End Sub Post
Exemple #11
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();
                }
            }
        }
Exemple #12
0
     /// <summary>Updated user</summary>
     /// <param name="username">name that need to be updated</param>
     /// <param name="body">Updated user object</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 UpdateUserAsync(string username, User body, 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_);
 			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 user 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);
 		}
 	}
        /// <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)}");
            }
        }
Exemple #14
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);
 		}
 	}
Exemple #15
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();
 
 		}
 	}
Exemple #16
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();
 
 		}
 	}
        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));
        }
Exemple #18
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();
                }
            }
        }
Exemple #19
0
 public virtual Task <System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage httpRequestMessage)
 {
     return(Client.SendAsync(httpRequestMessage));
 }
        private async Task <System.Collections.ObjectModel.ObservableCollection <MetaData2017> > GetResponse(string url_, System.Threading.CancellationToken cancellationToken)
        {
            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_.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;
                        }

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

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

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

                        return(default(System.Collections.ObjectModel.ObservableCollection <MetaData2017>));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #21
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);
 		}
 	}
Exemple #22
0
        /// <returns>Success</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 <TicketInfoViewModel> GetValidTicketAsync(int ticketnumber, string cstusercode, System.Threading.CancellationToken cancellationToken)
        {
            if (ticketnumber == null)
            {
                throw new System.ArgumentNullException("ticketnumber");
            }

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

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/TechServ/GetValidTicket/{ticketnumber}?");
            urlBuilder_.Replace("{ticketnumber}", System.Uri.EscapeDataString(ConvertToString(ticketnumber, System.Globalization.CultureInfo.InvariantCulture)));
            if (cstusercode != null)
            {
                urlBuilder_.Append("cstusercode=").Append(System.Uri.EscapeDataString(ConvertToString(cstusercode, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            urlBuilder_.Length--;

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

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

                            var result_ = default(TicketInfoViewModel);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <TicketInfoViewModel>(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_ == "400")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(ProblemDetails);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <ProblemDetails>(responseData_, _settings.Value);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                            throw new SwaggerException <ProblemDetails>("Bad Request", (int)response_.StatusCode, responseData_, headers_, result_, 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);
                        }

                        return(default(TicketInfoViewModel));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #23
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);
 		}
 	}
Exemple #24
0
        public async System.Threading.Tasks.Task ApiTasksPostAsync(WeeklyPlanner.DTO.ScheduledTaskDTO task = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var urlBuilder_ = new System.Text.StringBuilder();

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

            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(task, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    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);
                        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_ = 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);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
        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);

        }
Exemple #26
0
        public async System.Threading.Tasks.Task ApiTasksMoveByIdPostAsync(int id, System.DateTime date, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (id == null)
            {
                throw new System.ArgumentNullException("id");
            }

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

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

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/tasks/move/{id}?");
            urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(System.Convert.ToString(id, System.Globalization.CultureInfo.InvariantCulture)));
            urlBuilder_.Append("date=").Append(System.Uri.EscapeDataString(date.ToString("s", System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            urlBuilder_.Length--;

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

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Content = new System.Net.Http.StringContent(string.Empty);
                    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);
                        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_ = 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);
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #27
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);
 		}
 	}
Exemple #28
0
        /// <summary>
        /// Runs the queued task
        /// </summary>
        /// <param name="e">The task to run</param>
        /// <returns>An awaitable task</returns>
        private async Task RunTaskAsync(QueueEntry e)
        {
            // Start the task
            var t = await this.RunInTransactionAsync(db => {
                // Mark the task itself as running
                var now     = DateTime.Now;
                e.LastTried = now;
                e.Status    = QueueEntryStatus.Running;
                db.Update <QueueEntry>(new { e.LastTried, e.Status }, x => x.ID == e.ID);

                // Create a runner entry
                return(db.InsertItem <QueueRunLog>(
                           new QueueRunLog()
                {
                    QueueName = Name,
                    TaskID = e.ID,
                    Method = e.Method,
                    Url = e.Url,
                    ContentType = e.ContentType,
                    Started = now
                }
                           ));
            });

            using (var c = new System.Net.Http.HttpClient())
                using (var rq = new System.Net.Http.HttpRequestMessage())
                    try
                    {
                        rq.Method = new System.Net.Http.HttpMethod(e.Method);
                        var isSelfRequest = e.Url.StartsWith("/");
                        var targeturl     = e.Url;

                        if (isSelfRequest)
                        {
                            targeturl = this.SelfUrl + targeturl;
                        }

                        rq.RequestUri = new Uri(targeturl);
                        if (!string.IsNullOrWhiteSpace(e.Headers))
                        {
                            var headers = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(e.Headers);
                            foreach (var h in headers)
                            {
                                rq.Headers.Remove(h.Key);
                                rq.Headers.Add(h.Key, h.Value);
                            }
                        }

                        if (isSelfRequest)
                        {
                            rq.Headers.Remove(SecureHeaderName);
                            rq.Headers.Add(SecureHeaderName, SecureHeaderValue);
                        }

                        switch (e.ContentType)
                        {
                        case "multipart/form-data":
                            var mp = new System.Net.Http.MultipartFormDataContent();
                            foreach (var item in Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(e.Payload))
                            {
                                mp.Add(new System.Net.Http.StringContent(item.Value), item.Key);
                            }
                            rq.Content = mp;
                            break;

                        case "application/x-www-form-urlencoded":
                        case "application/json":
                        case "text/plan":
                        case "text/html":
                            rq.Content = new System.Net.Http.StringContent(e.Payload, System.Text.Encoding.UTF8, e.ContentType);
                            break;

                        case "application/octet-stream":
                            rq.Content = new System.Net.Http.ByteArrayContent(Convert.FromBase64String(e.Payload));
                            break;

                        default:
                            throw new ArgumentException($"Cannot send request with content type: {e.ContentType}");
                        }

                        using (var resp = await c.SendAsync(rq, m_cancelSource.Token))
                        {
                            t.Finished      = DateTime.Now;
                            t.StatusCode    = (int)resp.StatusCode;
                            t.StatusMessage = resp.ReasonPhrase;
                            t.Result        = await resp.Content.ReadAsStringAsync();

                            resp.EnsureSuccessStatusCode();
                            await this.RunInTransactionAsync(db => db.UpdateItem(t));
                        }
                    }
                    catch (Exception ex)
                    {
                        t.Result = string.Join(
                            Environment.NewLine,
                            new string[] {
                            t.Result,
                            "Exception: " + ex.ToString()
                        }.Where(x => !string.IsNullOrWhiteSpace(x))
                            );

                        throw;
                    }
            finally
            {
                t.Finished = DateTime.Now;
                await this.RunInTransactionAsync(db => db.UpdateItem(t));

                // Make sure the runner picks up on out results
                // But make sure the runner task has finished before we signal
                Task.Delay(TimeSpan.FromMilliseconds(500)).ContinueWith(_ => SignalRunner());
            }
        }
Exemple #29
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 <FileType> > ReverseQueryEnumListAsync(System.Collections.Generic.IEnumerable <FileType> fileTypes, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl).Append("/api/Enumeration/ReverseQueryEnumList?");
            if (fileTypes != null)
            {
                foreach (var item_ in fileTypes)
                {
                    urlBuilder_.Append("fileTypes=").Append(System.Uri.EscapeDataString(System.Convert.ToString(item_, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
                }
            }
            urlBuilder_.Length--;

            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(System.Collections.ObjectModel.ObservableCollection <FileType>);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.ObjectModel.ObservableCollection <FileType> >(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(System.Collections.ObjectModel.ObservableCollection <FileType>));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
        /// <summary>attemps a log in with post body</summary>
        /// <param name="body">Login form data</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>successful login, token returned</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <string> LoginAsync(LoginModel body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl).Append("/auth/login");

            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.MediaType = "application/json";
                    request_.Content = content_;
                    request_.Method  = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/plain"));

                    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_ == "400")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(string);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(responseData_, _settings.Value);
                            }
                            catch (System.Exception exception)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception);
                            }
                            throw new SwaggerException <string>("unsuccessful login / bad request", status_, responseData_, headers_, result_, 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(string));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #31
0
        private async void btnCheck_Click(object sender, EventArgs e)
        {
            startStopWaiting(true);
            var url = getBaseUrl(txtBaseUrl.Text);

            if (!url.EndsWith("/"))
            {
                url += "/";
            }

            url += "api/info/version";

            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"));

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

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

                    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;
                        }

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

                            string result_;
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(responseData_);
                                SetConnectionResult(true, result_);
                            }
                            catch (System.Exception)
                            {
                                SetConnectionResult(false, "");
                            }
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            SetConnectionResult(false, "");
                        }
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SetConnectionResult(false, "");
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
                startStopWaiting(false);
            }
        }
        /// <summary>gets all lessons used by user</summary>
        /// <param name="x_AuthToken">User auth token.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>successful query</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <System.Collections.ObjectModel.ObservableCollection <Language> > GetLanguagesAsync(string x_AuthToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl).Append("/lessons/languages-list");

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

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Headers.TryAddWithoutValidation("X-AuthToken", x_AuthToken != null ? System.Convert.ToString(x_AuthToken, System.Globalization.CultureInfo.InvariantCulture) : null);
                    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(System.Collections.ObjectModel.ObservableCollection <Language>);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.ObjectModel.ObservableCollection <Language> >(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_ == "403")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("auth token failed to validate", 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(System.Collections.ObjectModel.ObservableCollection <Language>));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #33
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="ApiExceptions">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <SwaggerResponse <Activity> > GetActivityAsync(int?id = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var urlBuilder_ = new System.Text.StringBuilder();

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

            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(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 objectResponse_ = await ReadObjectResponseAsync <Activity>(response_, headers_).ConfigureAwait(false);

                            return(new SwaggerResponse <Activity>((int)response_.StatusCode, headers_, objectResponse_.Object));
                        }
                        else
                        if (status_ == "400")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <ProblemDetails>(response_, headers_).ConfigureAwait(false);

                            throw new ApiExceptions <ProblemDetails>("A server side error occurred.", (int)response_.StatusCode, objectResponse_.Text, headers_, objectResponse_.Object, null);
                        }
                        else
                        if (status_ == "404")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <ProblemDetails>(response_, headers_).ConfigureAwait(false);

                            throw new ApiExceptions <ProblemDetails>("A server side error occurred.", (int)response_.StatusCode, objectResponse_.Text, headers_, objectResponse_.Object, null);
                        }
                        else
                        if (status_ == "500")
                        {
                            string responseText_ = (response_.Content == null) ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

                        return(new SwaggerResponse <Activity>((int)response_.StatusCode, headers_, default(Activity)));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #34
0
        /// <returns>Success</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 <BlogPost> ApiBlogByIdGetAsync(int id, System.Threading.CancellationToken cancellationToken)
        {
            if (id == null)
            {
                throw new System.ArgumentNullException("id");
            }

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

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Blog/{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())
                {
                    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(BlogPost);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <BlogPost>(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_ == "404")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(BlogPost);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <BlogPost>(responseData_, _settings.Value);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception_);
                            }
                            throw new SwaggerException <BlogPost>("Not Found", status_, responseData_, headers_, result_, 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(BlogPost));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #35
0
        /// <returns>Success</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 <System.Collections.ObjectModel.ObservableCollection <Pets> > ApiPetsGetAsync(System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

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

            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);
                        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.ObjectModel.ObservableCollection <Pets>);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.ObjectModel.ObservableCollection <Pets> >(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.ObjectModel.ObservableCollection <Pets>));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <summary>Log in into OneBoard with a login / password.</summary>
        /// <param name="body">Credential information.</param>
        /// <returns>Success</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <int> ApiV1AuthLoginAsync(LoginApi body, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

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

            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-patch+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_ == "200")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <int>(response_, headers_).ConfigureAwait(false);

                            return(objectResponse_.Object);
                        }
                        else
                        if (status_ == "400")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <ResponseErrorApi>(response_, headers_).ConfigureAwait(false);

                            throw new SwaggerException <ResponseErrorApi>("Bad Request", (int)response_.StatusCode, objectResponse_.Text, headers_, objectResponse_.Object, null);
                        }
                        else
                        if (status_ == "404")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <ResponseErrorApi>(response_, headers_).ConfigureAwait(false);

                            throw new SwaggerException <ResponseErrorApi>("Not Found", (int)response_.StatusCode, objectResponse_.Text, headers_, objectResponse_.Object, 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);
                        }

                        return(default(int));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
        private async Task <List <string> > GetServerListFromEndpointAsync()
        {
            var list   = new List <string>();
            var result = new List <string>();

            try
            {
                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
                {
                    client.Timeout = TimeSpan.FromMilliseconds(3000);

                    var req = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, _addressServerUrl);

                    var resp = await client.SendAsync(req);

                    if (resp.IsSuccessStatusCode)
                    {
                        var str = await resp.Content.ReadAsStringAsync();

                        using (StringReader sr = new StringReader(str))
                        {
                            while (true)
                            {
                                var line = await sr.ReadLineAsync();

                                if (line == null || line.Length <= 0)
                                {
                                    break;
                                }

                                list.Add(line.Trim());
                            }
                        }

                        foreach (var item in list)
                        {
                            if (!string.IsNullOrWhiteSpace(item))
                            {
                                var ipPort = item.Trim().Split(':');
                                var ip     = ipPort[0].Trim();
                                if (ipPort.Length == 1)
                                {
                                    result.Add($"{ip}:8848");
                                }
                                else
                                {
                                    result.Add(item);
                                }
                            }
                        }
                    }
                    else
                    {
                        return(null);
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(null);
            }
        }
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>Success</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <UserApi> ApiV1UserGetAsync(int userId, System.Threading.CancellationToken cancellationToken)
        {
            if (userId == null)
            {
                throw new System.ArgumentNullException("userId");
            }

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

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/User/Get/{userId}");
            urlBuilder_.Replace("{userId}", System.Uri.EscapeDataString(ConvertToString(userId, 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(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain"));

                    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 objectResponse_ = await ReadObjectResponseAsync <UserApi>(response_, headers_).ConfigureAwait(false);

                            return(objectResponse_.Object);
                        }
                        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(UserApi));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Exemple #39
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);
 		}
 	}
Exemple #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<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>);
 		}
 	}
Exemple #41
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);
 		}
 	}
Exemple #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 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);
 		}
 	}
Exemple #43
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>));
            }
        }
Exemple #44
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);
 		}
 	}
Exemple #45
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);
 		}
 	}
Exemple #46
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));
            }
        }
Exemple #47
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);
 		}
 	}
        /// <summary>
        /// Initializes the FFmpeg library and download it if necessary
        /// </summary>
        /// <param name="context">Context</param>
        /// <exception cref="FFmpegNotInitializedException"></exception>
        /// <exception cref="FFmpegNotDownloadedException"></exception>
        /// <returns></returns>
        public async Task Init(Context context)
        {
            if (_initialized)
            {
                return;
            }

            if (SourceFolder != null)
            {
                _ffmpegFile = new Java.IO.File(SourceFolder + "/ffmpeg");
            }
            else
            {
                var filesDir = context.FilesDir;

                _ffmpegFile = new Java.IO.File(filesDir + "/ffmpeg");
            }

            FFmpegSource source = FFmpegSource.Get();

            if (source == null)
            {
                throw new FFmpegNotInitializedException();
            }

            if (Url != null)
            {
                source.SetUrl(Url);
            }

            await Task.Run(() =>
            {
                if (_ffmpegFile.Exists())
                {
                    try
                    {
                        if (source.IsHashMatch(System.IO.File.ReadAllBytes(_ffmpegFile.CanonicalPath)))
                        {
                            if (!_ffmpegFile.CanExecute())
                            {
                                _ffmpegFile.SetExecutable(true);
                            }

                            _initialized = true;

                            return;
                        }
                    }
                    catch (Exception)
                    {
                        // Não implementado
                    }

                    if (_ffmpegFile.CanExecute())
                    {
                        _ffmpegFile.SetExecutable(false);
                    }

                    _ffmpegFile.Delete();
                }
            });

            if (_initialized)
            {
                // Ffmpeg file exists...
                return;
            }

            if (_ffmpegFile.Exists())
            {
                _ffmpegFile.Delete();
            }

            // Download
            var dialog = new ProgressDialog(context);

            dialog.SetTitle(DownloadTitle ?? "Realizando download da biblioteca FFmpeg");
            dialog.Indeterminate = false;
            dialog.SetProgressStyle(ProgressDialogStyle.Horizontal);
            dialog.SetCancelable(false);
            dialog.SetCanceledOnTouchOutside(false);
            dialog.Show();

            try
            {
                using (var c = new System.Net.Http.HttpClient())
                {
                    using (var fout = System.IO.File.OpenWrite(_ffmpegFile.AbsolutePath))
                    {
                        string url = source.Url;

                        var g = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);

                        var h = await c.SendAsync(g, System.Net.Http.HttpCompletionOption.ResponseHeadersRead);

                        var buffer = new byte[51200];

                        var s = await h.Content.ReadAsStreamAsync();

                        long total = h.Content.Headers.ContentLength.GetValueOrDefault();

                        IEnumerable <string> sl;

                        if (h.Headers.TryGetValues("Content-Length", out sl))
                        {
                            if (total == 0 && sl.Any())
                            {
                                long.TryParse(sl.FirstOrDefault(), out total);
                            }
                        }

                        int count    = 0;
                        int progress = 0;

                        dialog.Max = (int)total;

                        while ((count = await s.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            await fout.WriteAsync(buffer, 0, count);

                            progress += count;

                            dialog.Progress = progress;
                        }

                        dialog.Hide();
                        dialog.Dispose();
                    }
                }
            }
            catch (Exception)
            {
                _initialized = false;

                dialog.Hide();
                dialog.Dispose();

                throw new FFmpegNotDownloadedException();
            }

            if (!_ffmpegFile.CanExecute())
            {
                _ffmpegFile.SetExecutable(true);
            }

            _initialized = true;
        }
Exemple #49
0
        //https://stackoverflow.com/questions/13260951/how-to-proxy-a-rest-api-with-net-4
        //public async System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> Proxy(Microsoft.AspNetCore.Http.HttpRequest Request)

/*
 *      [HttpHead("{db?}/{id?}/{rev?}")]
 *      [HttpGet("{db?}/{id?}/{rev?}")]
 *      [HttpPost("{db?}/{id?}/{rev?}")]
 *      [HttpPut("{db?}/{id?}/{rev?}")]
 *      [HttpDelete("{db?}/{id?}/{rev?}")]
 */

        public async System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> Proxy(Microsoft.AspNetCore.Http.HttpRequest Request)

        {
            System.Net.Http.HttpResponseMessage result = null;

            // Grab the path from /api/*
            var path   = Request.Path.ToString().Replace("/couch", "");
            var target = new UriBuilder("http", "localhost", 5984);
            var method = Request.Method;

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

            client.BaseAddress = target.Uri;

            // Needs to get filled with response.
            string content;

            System.IO.StreamReader reader;
            string jsonInput;

            System.Net.Http.HttpRequestMessage request_message;

            System.Console.WriteLine($"\nmethod:{method} Path: {Request.Path.ToString()} new_path:{path}");
            //System.Net.Http.HttpResponseMessage response;
            switch (method)
            {
            case "POST":
                reader    = new System.IO.StreamReader(Request.Body);
                jsonInput = reader.ReadToEnd();

                // Totally lost here.
                result = await client.PostAsync(path, new System.Net.Http.StringContent(jsonInput, System.Text.Encoding.UTF8, "application/json"));

                break;

            case "PUT":
                reader    = new System.IO.StreamReader(Request.Body);
                jsonInput = reader.ReadToEnd();

                // Totally lost here.
                result = await client.PutAsync(path, new System.Net.Http.StringContent(jsonInput, System.Text.Encoding.UTF8, "application/json"));

                break;

            case "DELETE":
                result = await client.DeleteAsync(path);

                break;

            case "GET":
                // need to capture client data
                //result = await client.GetAsync(path);
                request_message = new System.Net.Http.HttpRequestMessage
                                  (
                    System.Net.Http.HttpMethod.Get,
                    path
                                  );
                result = await client.SendAsync(request_message);

                break;

            case "HEAD":
                request_message = new System.Net.Http.HttpRequestMessage
                                  (
                    System.Net.Http.HttpMethod.Head,
                    path
                                  );
                result = await client.SendAsync(request_message);

                break;

            default:
                System.Console.WriteLine($"\nmethod:{method} Path: {Request.Path.ToString()} new_path:{path} - missing manual.");
                result = await client.GetAsync(path);

                break;
            }

/*
 *          content = await result.Content.ReadAsStringAsync();
 *
 *          foreach (var header in result.Headers)
 *          {
 *              //content.Headers.Add(header.Key, header.Value);
 *              Request.HttpContext.Response.Headers.Add(header.Key, header.Value.ToString());
 *          }
 *          Request.HttpContext.Response.Headers.ContentLength = result.ContentLength;
 */

            //content.Headers.ContentLength = oldContent.Length;
            //response.Content = content;



            //return Content(content, "application/json");
            return(result);
        }
Exemple #50
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <summary>Get all lenders</summary>
        /// <returns>Success</returns>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <System.Collections.Generic.ICollection <Lender> > LendersAllAsync(System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

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

            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(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_ == "500")
                        {
                            string responseText_ = (response_.Content == null) ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("Server Error", (int)response_.StatusCode, responseText_, headers_, null);
                        }
                        else
                        if (status_ == "200")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <System.Collections.Generic.ICollection <Lender> >(response_, headers_).ConfigureAwait(false);

                            return(objectResponse_.Object);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        return(default(System.Collections.Generic.ICollection <Lender>));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
        /// <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)}");
            }
        }
Exemple #52
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 <FileResponse> GetFileAsync(string fileName, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl).Append("/api/File/GetFile?");
            if (fileName != null)
            {
                urlBuilder_.Append("fileName=").Append(System.Uri.EscapeDataString(System.Convert.ToString(fileName, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            urlBuilder_.Length--;

            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" || status_ == "206")
                        {
                            var responseStream_ = await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse(status_, headers_, responseStream_, client_, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        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(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
        /// <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)}");
            }
        }
Exemple #54
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>);
 		}
 	}