using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
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()
};
}
}
///
/// Post Request Async
///
///
/// - Initial.
///
///
///
///
///
///
public static String PostRequestAsync(String url, Double timeoutMs, out HttpStatusCode httpStatus, Object json = null)
{
try
{
var httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.Timeout = TimeSpan.FromMilliseconds(timeoutMs);
var postedJson = JsonConvert.SerializeObject(json, Formatting.Indented);
var postedBody = new StringContent(postedJson);
postedBody.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
var posted = httpClient
.PostAsync(url, postedBody)
.Result;
httpStatus = posted.StatusCode;
return posted.Content.ReadAsStringAsync().Result;
}
catch (Exception error)
{
httpStatus = HttpStatusCode.ServiceUnavailable;
return error.Message;
}
}
///
/// 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);
client.AddDefaultHeader("Accept", "application/json");
//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 DeleteRequest(String url, Int32? timeoutMs = null, Dictionary header = null, Boolean isRetry = false)
{
Int32 temp;
var ret = DeleteRequestWithError(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 DeleteRequestWithError(String url, out Int32 errorCode, Int32? timeoutMs = null, Dictionary header = null, Boolean isRetry = false)
{
var client = new RestClient(url);
var request = new RestRequest(Method.DELETE);
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.Execute(request);
errorCode = r.StatusCode.GetHashCode();
if (r.StatusCode == HttpStatusCode.OK)
{
return r.Content;
}
if (r.StatusCode != 0)
return r.Content;
return !isRetry ? DeleteRequest(url, timeoutMs, header, true) : r.Content;
}
///
/// 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);
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;
return !isRetry ? GetRequest(url, timeoutMs, header, true) : r.Content;
}
private static HttpResponse AsJson(this Method method, String url, Action headersHandler = null, Object model = null, Int32? timeoutMs = null)
{
var httpResponse = new HttpResponse();
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;
var 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;
}
}
}