using Newtonsoft.Json; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Net; namespace Xylem.Common.Logic.SoftwareAccessHelper { /// /// Web request /// public static class LocalWebRequest { /// /// Web request with asynchronous operation and response code or exception response, json object input and/or dictionary /// /// /// /// /// /// /// /// public static Boolean PostRequestAsync(String url, ref Int32 responseCode, ref Exception ex, Int32? timeoutMs = null, Object json = null, Dictionary header = null) { try { var r = PostRequestAndGetResponseAsync(url, timeoutMs, json, header); responseCode = r.StatusCode.GetHashCode(); if (r.StatusCode == HttpStatusCode.OK) { return true; } if (r.StatusCode == HttpStatusCode.InternalServerError) { ex = new Exception(r.Content); } } catch (Exception error) { ex = error; } return false; } /// /// Web request with asynchronous operation and true/false return, json object input and/or dictionary /// /// /// /// /// /// public static Boolean PostRequestAsync(String url, Int32? timeoutMs = null, Object json = null, Dictionary header = null) { try { var r = PostRequestAndGetResponseAsync(url, timeoutMs, json, header); if (r.StatusCode == HttpStatusCode.OK) { return true; } } catch (Exception) { // Log } return false; } /// /// Web request with asynchronous operation with string return, json object input and/or dictionary /// /// /// /// /// /// public static String PostRequestAsyncAndGetContent(String url, Int32? timeoutMs = null, Object json = null, Dictionary header = null) { try { var r = PostRequestAndGetResponseAsync(url, timeoutMs, json, header); if (r.StatusCode == HttpStatusCode.OK) { return r.Content; } } catch (Exception) { // Log } return string.Empty; } /// /// Web request with asynchronous operation, binary file byte array input, response string output /// /// /// /// /// /// /// public static Boolean PostBinaryFileRequestAsync(String url, String fileName, Byte[] content, out String response, Int32? timeoutMs = null) { try { var client = new RestClient(url); //WebRequest.DefaultWebProxy = null; var request = new RestRequest(Method.POST); ServicePointManager.Expect100Continue = false; request.AddHeader("Content-Type", "multipart/form-data"); request.Files.Add(new FileParameter { Name = "file", Writer = (s) => { var stream = new MemoryStream(content); stream.CopyTo(s); stream.Dispose(); }, FileName = fileName, ContentType = "multipart/form-data", ContentLength = content.Length }); var r = client.ExecuteAsPost(request, Method.POST.ToString()); response = r.Content; return r.StatusCode == HttpStatusCode.OK; } catch (Exception) { response = string.Empty; return false; } } /// /// Web request with asynchronous operation, binary file input /// /// /// /// /// /// public static Boolean PostBinaryFileRequestAsync(String url, String fileName, Byte[] content, Int32? timeoutMs = null) { try { var client = new RestClient(url); // WebRequest.DefaultWebProxy = null; var request = new RestRequest(Method.POST); ServicePointManager.Expect100Continue = false; request.AddHeader("Content-Type", "multipart/form-data"); request.Files.Add(new FileParameter { Name = "file", Writer = (s) => { var stream = new MemoryStream(content); stream.CopyTo(s); stream.Dispose(); }, FileName = fileName, ContentType = "multipart/form-data", ContentLength = content.Length }); var r = client.ExecuteAsPost(request, Method.POST.ToString()); return r.StatusCode == HttpStatusCode.OK; } catch (Exception) { return false; } } /// /// Web request with asynchronous operation /// /// /// /// /// /// public static IRestResponse PostBinaryRequestAndGetResponseAsync(String url, Int32? timeoutMs = null, Dictionary files = null, Dictionary header = null) { try { var client = new RestClient(url); //WebRequest.DefaultWebProxy = null; var request = new RestRequest(Method.POST); ServicePointManager.Expect100Continue = false; if (header != null) { foreach (var item in header) { if (item.Key != "Content-Type" && item.Key != "Accept") { request.AddHeader(item.Key, item.Value); } } } request.AddHeader("Content-Type", "multipart/form-data"); if (files != null) { foreach (var item in files) { request.AddFile(item.Key, item.Value); } } var r = client.ExecuteAsPost(request, Method.POST.ToString()); return r; } catch (Exception error) { return new RestResponse { StatusCode = HttpStatusCode.InternalServerError, Content = error.ToString() }; } } /// /// Web request with asynchronous operation /// /// /// /// /// /// public static IRestResponse PostRequestAndGetResponseAsync(String url, Int32? timeoutMs = null, Object json = null, Dictionary header = null) { try { var client = new RestClient(url); //WebRequest.DefaultWebProxy = null; ServicePointManager.Expect100Continue = false; var request = new RestRequest(Method.POST); if (header != null) { foreach (var item in header) { if (item.Key != "Content-Type" && item.Key != "Accept") { request.AddHeader(item.Key, item.Value); } } } request.AddHeader("Content-Type", "application/json"); request.AddHeader("Accept", "application/json"); if (json != null) { request.AddJsonBody(json); } var r = client.ExecuteAsPost(request, Method.POST.ToString()); return r; } catch (Exception error) { return new RestResponse { StatusCode = HttpStatusCode.InternalServerError, Content = error.ToString() }; } } #region HTTP String extensions public static HttpResponse DeleteAsJson(this String url, Object json = null, Action headersHandler = null, Int32? timeoutMs = null) { return Method.DELETE.AsJson(url, headersHandler, json, timeoutMs); } public static HttpResponse GetAsJson(this String url, Object json = null, Action headersHandler = null, Int32? timeoutMs = null) { return Method.GET.AsJson(url, headersHandler, json, timeoutMs); } public static HttpResponse PostAsJson(this String url, Object json = null, Action headersHandler = null, Int32? timeoutMs = null) { return Method.POST.AsJson(url, headersHandler, json, timeoutMs); } public static HttpResponse PutAsJson(this String url, Object json = null, Action headersHandler = null, Int32? timeoutMs = null) { return Method.PUT.AsJson(url, headersHandler, json, timeoutMs); } #endregion HTTP String extensions #region HTTP Object extensions public static HttpResponse DeleteAsJson(this Object json, String url, Action headersHandler = null, Int32? timeoutMs = null) { return Method.DELETE.AsJson(url, headersHandler, json, timeoutMs); } public static HttpResponse GetAsJson(this Object json, String url, Action headersHandler = null, Int32? timeoutMs = null) { return Method.GET.AsJson(url, headersHandler, json, timeoutMs); } public static HttpResponse PostAsJson(this Object json, String url, Action headersHandler = null, Int32? timeoutMs = null) { return Method.POST.AsJson(url, headersHandler, json, timeoutMs); } public static HttpResponse PutAsJson(this Object json, String url, Action headersHandler = null, Int32? timeoutMs = null) { return Method.PUT.AsJson(url, headersHandler, json, timeoutMs); } #endregion HTTP Object extensions /// /// Web request /// /// /// /// /// /// public static String GetRequest(String url, Int32? timeoutMs = null, Dictionary header = null, Boolean isRetry = false) { Int32 temp; var ret = GetRequestWithError(url, out temp, timeoutMs, header, isRetry); if (temp != 200) { throw new ApplicationException($"WebRequest Status {temp}"); } return ret; } /// /// Web request with asynchronous operation, error code response /// /// /// /// /// /// /// public static String GetRequestWithError(String url, out Int32 errorCode, Int32? timeoutMs = null, Dictionary header = null, Boolean isRetry = false) { var client = new RestClient(url); //WebRequest.DefaultWebProxy = null; var request = new RestRequest(Method.GET); ServicePointManager.Expect100Continue = false; if (!timeoutMs.HasValue) { timeoutMs = 800; } request.Timeout = timeoutMs.Value; if (header != null) { foreach (var item in header) { if (item.Key != "Accept") { request.AddHeader(item.Key, item.Value); } } } request.AddHeader("Accept", "application/json"); var r = client.Get(request); errorCode = r.StatusCode.GetHashCode(); if (r.StatusCode == HttpStatusCode.OK) { return r.Content; } if (r.StatusCode != 0) return r.Content; // Changed logic as it seems to be an endless loop THW 25-Mar-2021 //if (presult.Status == IPStatus.Success || !isRetry) if (!isRetry) { return GetRequest(url, timeoutMs, header, true); } // Removed throwing of exception as the caller cannot evaluate the result THW 25-Mar-2021 //throw new ApplicationException($"Timeout { r.StatusDescription} {Environment.NewLine} PingState: {presult.Status} {Environment.NewLine} RoundtripTime: {presult.RoundtripTime} "); return r.Content; } private static HttpResponse AsJson(this Method method, String url, Action headersHandler = null, Object model = null, Int32? timeoutMs = null) { var httpResponse = new HttpResponse(); var response = default(IRestResponse); try { var client = new RestClient(url); var request = new RestRequest(method); var headers = new RestRequestHeaders(request) { ContentType = "application/json", Accept = "application/json" }; headersHandler?.Invoke(headers); if (model != null) { if (method == Method.GET) { request.AddObject(model); } else { request.AddJsonBody(model); } } ServicePointManager.Expect100Continue = false; response = client.Execute(request); httpResponse.HttpStatusCode = response.StatusCode; if (HttpStatusCode.OK <= response.StatusCode && response.StatusCode < HttpStatusCode.BadRequest) { if (!string.IsNullOrWhiteSpace(response.Content)) { httpResponse.Value = JsonConvert.DeserializeObject(response.Content); } else { httpResponse.Errors = new Dictionary() { { nameof(response.Content), $"{response.Content}" }, }; } } else { httpResponse.Errors = JsonConvert.DeserializeObject>(response.Content); if (httpResponse.Errors is null) { httpResponse.Errors = new Dictionary() { { nameof(response.ErrorException), $"{response.ErrorException}" }, { nameof(response.ErrorMessage), $"{response.ErrorMessage}" }, { nameof(response.Content), $"{response.Content}" }, }; } } } catch (Exception error) { httpResponse.HttpStatusCode = HttpStatusCode.InternalServerError; httpResponse.Errors = new Dictionary() { { nameof(Exception), $"{error}" } }; } return httpResponse; } } }