Adding
This commit is contained in:
+141
@@ -0,0 +1,141 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.Exceptions;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.Utilities;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.Configuration;
|
||||
|
||||
namespace LCU.Library.Internal.CoreApiWrapperLib.CoreApiUtilities
|
||||
{
|
||||
public class CoreRequest : ICoreRequest
|
||||
{
|
||||
private const int DefaultAttempts = 0;
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
private readonly ICoreServiceConnection _coreServiceConnection;
|
||||
private readonly CoreConfiguration _coreConfiguration;
|
||||
private readonly CoreApiConfiguration _coreApiConfiguration;
|
||||
|
||||
public CoreRequest(IHttpClientFactory clientFactory,
|
||||
ICoreServiceConnection coreServiceConnection,
|
||||
CoreConfiguration coreConfiguration)
|
||||
{
|
||||
_clientFactory = clientFactory;
|
||||
_coreServiceConnection = coreServiceConnection;
|
||||
_coreConfiguration = coreConfiguration;
|
||||
_coreApiConfiguration = _coreConfiguration.CoreApiConfiguration;
|
||||
}
|
||||
|
||||
public async Task<T> GetRequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, string jsonBody = null)
|
||||
{
|
||||
return await RequestObject<T>(endpoint, endpointParameters, HttpMethod.Get, jsonBody);
|
||||
}
|
||||
|
||||
public async Task<T> PostRequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, string jsonBody)
|
||||
{
|
||||
return await RequestObject<T>(endpoint, endpointParameters, HttpMethod.Post, jsonBody);
|
||||
}
|
||||
|
||||
public async Task<T> PutRequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, string jsonBody)
|
||||
{
|
||||
return await RequestObject<T>(endpoint, endpointParameters, HttpMethod.Put, jsonBody);
|
||||
}
|
||||
|
||||
public async Task<T> DeleteRequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, string jsonBody)
|
||||
{
|
||||
return await RequestObject<T>(endpoint, endpointParameters, HttpMethod.Delete, jsonBody);
|
||||
}
|
||||
|
||||
private async Task<T> RequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, HttpMethod httpMethod, string jsonBody)
|
||||
{
|
||||
var finalEndpoint = HttpUtilities.BuildEndPointWithParams(endpoint, endpointParameters);
|
||||
var result = await RequestCoreJsonResponse(finalEndpoint, httpMethod, jsonBody);
|
||||
if (string.IsNullOrEmpty(result))
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
|
||||
return JsonConvert.DeserializeObject<T>(result);
|
||||
}
|
||||
|
||||
public async Task<string> RequestCoreJsonResponse(string endpoint, HttpMethod httpMethod, string body = null)
|
||||
{
|
||||
var attempts = DefaultAttempts;
|
||||
Exception exception = new Exception();
|
||||
while (attempts < _coreApiConfiguration.ReTryLimit)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await SendHttpRequest(endpoint, httpMethod, body);
|
||||
}
|
||||
catch (UnauthorizedRequestException uex)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(1));
|
||||
_coreServiceConnection.RefreshAccessCache();
|
||||
attempts++;
|
||||
exception = uex;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
attempts = _coreApiConfiguration.ReTryLimit;
|
||||
exception = ex;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception($"Failure to perform HTTP request. Exception: {exception.Message}");
|
||||
}
|
||||
|
||||
public async Task<string> SendHttpRequest(string endpoint, HttpMethod httpMethod, string body = null)
|
||||
{
|
||||
HttpRequestMessage request = CreateHttpRequestMessage(endpoint, httpMethod, body);
|
||||
var client = HttpUtilities.GetClient(request.RequestUri);
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
throw new UnauthorizedRequestException($"Unauthorized Request.");
|
||||
}
|
||||
|
||||
throw new Exception($"Unable to successfully send the HTTP request. " +
|
||||
$"StatusCode:{response.StatusCode}, ReasonPhrase:{response.ReasonPhrase}");
|
||||
}
|
||||
|
||||
return await response.Content.ReadAsStringAsync();
|
||||
}
|
||||
|
||||
public HttpRequestMessage CreateHttpRequestMessage(string endpoint, HttpMethod httpMethod, string body = null)
|
||||
{
|
||||
var accessToken = _coreServiceConnection.GetAccessToken();
|
||||
if (string.IsNullOrWhiteSpace(accessToken))
|
||||
{
|
||||
throw new UnauthorizedRequestException($"Unauthorized Request.");
|
||||
}
|
||||
|
||||
var uri = HttpUtilities.BuildHttpsUri(_coreApiConfiguration.HostName, endpoint);
|
||||
HttpRequestMessage request = new HttpRequestMessage
|
||||
{
|
||||
Method = httpMethod,
|
||||
RequestUri = uri,
|
||||
Headers = {
|
||||
{ HttpRequestHeader.Authorization.ToString(), accessToken },
|
||||
{ "X-ApiChannelId", _coreApiConfiguration.ServiceApiChannelId },
|
||||
{ "X-MessageId", Guid.NewGuid().ToString() },
|
||||
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
|
||||
}
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(body))
|
||||
{
|
||||
var content = new StringContent(body, Encoding.UTF8, "application/json");
|
||||
request.Content = content;
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Newtonsoft.Json;
|
||||
using Serilog;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.Utilities;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.Configuration;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.ConnectionModels;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace LCU.Library.Internal.CoreApiWrapperLib.CoreApiUtilities
|
||||
{
|
||||
public class CoreServiceConnection : ICoreServiceConnection
|
||||
{
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
private readonly CoreConfiguration _coreConfiguration;
|
||||
private readonly CoreApiConfiguration _coreApiConfiguration;
|
||||
private IMemoryCache _cache;
|
||||
private string _accessToken;
|
||||
|
||||
public CoreServiceConnection(IHttpClientFactory clientFactory,
|
||||
CoreConfiguration coreConfiguration,
|
||||
IMemoryCache cache)
|
||||
{
|
||||
_clientFactory = clientFactory;
|
||||
_coreConfiguration = coreConfiguration;
|
||||
_coreApiConfiguration = _coreConfiguration.CoreApiConfiguration;
|
||||
_accessToken = "";
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
public string GetAccessToken()
|
||||
{
|
||||
if (_cache.TryGetValue("accesstoken", out _accessToken))
|
||||
{
|
||||
return _accessToken;
|
||||
}
|
||||
|
||||
RefreshAccessCache();
|
||||
return _accessToken;
|
||||
}
|
||||
|
||||
public void RefreshAccessCache()
|
||||
{
|
||||
if (_cache.TryGetValue("accesstoken", out _accessToken))
|
||||
{
|
||||
_cache.Remove("accesstoken");
|
||||
}
|
||||
|
||||
SetAccessToken();
|
||||
if (!string.IsNullOrWhiteSpace(_accessToken))
|
||||
{
|
||||
_cache.Set("accesstoken", _accessToken);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetAccessToken()
|
||||
{
|
||||
try
|
||||
{
|
||||
_accessToken = "";
|
||||
var body = new ServiceAccessRequest()
|
||||
{
|
||||
Grant_Type = _coreApiConfiguration.GrantType,
|
||||
Scope = _coreApiConfiguration.Scope,
|
||||
Service_Account_Id = _coreApiConfiguration.SeviceAccountId,
|
||||
Device_Name = _coreApiConfiguration.DeviceName
|
||||
};
|
||||
var encoded = JsonConvert.SerializeObject(body);
|
||||
var content = new StringContent(encoded, Encoding.UTF8, "application/json");
|
||||
var uri = HttpUtilities.BuildHttpsUri(_coreApiConfiguration.HostName, _coreApiConfiguration.CoreEndPointConfiguration.ServiceToken);
|
||||
var client = HttpUtilities.GetClient(uri);
|
||||
var authenticationString = $"{_coreApiConfiguration.SeviceAccountId}:{_coreApiConfiguration.RelyingPassword}";
|
||||
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
|
||||
var basicAthentication = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
|
||||
|
||||
HttpRequestMessage request = new HttpRequestMessage()
|
||||
{
|
||||
Method = HttpMethod.Post,
|
||||
RequestUri = uri,
|
||||
Content = content,
|
||||
Headers = {
|
||||
{ HttpRequestHeader.Authorization.ToString(), basicAthentication.ToString() },
|
||||
{ HttpRequestHeader.ContentType.ToString(), "application/json" },
|
||||
{ HttpRequestHeader.Accept.ToString(), "application/json;version=2" }
|
||||
}
|
||||
};
|
||||
|
||||
var response = client.SendAsync(request).Result;
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
Log.Error("Unsuccessful response status code, unable to set the access token.");
|
||||
return;
|
||||
}
|
||||
|
||||
var result = response.Content.ReadAsStringAsync().Result;
|
||||
var accessResponse = JsonConvert.DeserializeObject<ServiceAccessResponse>(result);
|
||||
_accessToken = $"Bearer {accessResponse.Access_Token}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "Failure to set access token");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Newtonsoft.Json;
|
||||
using Serilog;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.Utilities;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.Configuration;
|
||||
using LCU.Library.Internal.CoreApiWrapperModel.ConnectionModels;
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.ConnectionModels;
|
||||
|
||||
namespace LCU.Library.Internal.CoreApiWrapperLib.CoreApiUtilities
|
||||
{
|
||||
[Obsolete("User connection only, 09/08/2021, will be removed in future release")]
|
||||
public class CoreUserConnection : ICoreUserConnection
|
||||
{
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
private readonly CoreConfiguration _coreConfiguration;
|
||||
private readonly CoreApiConfiguration _coreApiConfiguration;
|
||||
private IMemoryCache _cache;
|
||||
private CoreApiUserConnection _coreApiUserConnection;
|
||||
|
||||
public CoreUserConnection(IHttpClientFactory clientFactory,
|
||||
CoreConfiguration coreConfiguration,
|
||||
IMemoryCache cache)
|
||||
{
|
||||
_clientFactory = clientFactory;
|
||||
_coreConfiguration = coreConfiguration;
|
||||
_coreApiConfiguration = _coreConfiguration.CoreApiConfiguration;
|
||||
_coreApiUserConnection = new CoreApiUserConnection();
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
public CoreApiUserConnection GetCoreApiConnection()
|
||||
{
|
||||
var coreApiConnection = new CoreApiUserConnection();
|
||||
if (_cache.TryGetValue("coreapiuserconnection", out coreApiConnection))
|
||||
{
|
||||
return coreApiConnection;
|
||||
}
|
||||
|
||||
RefreshConnectionCache();
|
||||
return _coreApiUserConnection;
|
||||
}
|
||||
|
||||
public void RefreshConnectionCache()
|
||||
{
|
||||
var coreApiConnection = new CoreApiUserConnection();
|
||||
if (_cache.TryGetValue("coreapiuserconnection", out coreApiConnection))
|
||||
{
|
||||
_cache.Remove("coreapiuserconnection");
|
||||
}
|
||||
|
||||
SetStsToken();
|
||||
SetPreLoginDetails();
|
||||
SetDnaToken();
|
||||
_cache.Set("coreapiuserconnection", _coreApiUserConnection);
|
||||
}
|
||||
|
||||
private void SetStsToken()
|
||||
{
|
||||
try
|
||||
{
|
||||
var body = new StsTokenConnection(_coreApiConfiguration);
|
||||
var encoded = JsonConvert.SerializeObject(body);
|
||||
var content = new StringContent(encoded, Encoding.UTF8, "application/json");
|
||||
var uri = HttpUtilities.BuildHttpsUri(_coreApiConfiguration.HostName, _coreApiConfiguration.CoreEndPointConfiguration.StsToken);
|
||||
var client = HttpUtilities.GetClient(uri);
|
||||
|
||||
var response = client.PostAsync(uri, content).Result;
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
Log.Error("Unable to set the STS Token.");
|
||||
throw new Exception($"Unable to set the STS Token. StatusCode:{response.StatusCode}, ReasonPhrase:{response.ReasonPhrase}");
|
||||
}
|
||||
|
||||
var stsToken = response.Content.ReadAsStringAsync().Result;
|
||||
_coreApiUserConnection.StsToken = $"Bearer {stsToken.Replace("\"", "")}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Failure to SetStsToken. Exception: {ex.InnerException}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void SetPreLoginDetails()
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = HttpUtilities.BuildHttpsUri(_coreApiConfiguration.HostName, _coreApiConfiguration.CoreEndPointConfiguration.Prelogin);
|
||||
var client = HttpUtilities.GetClient(uri);
|
||||
HttpRequestMessage request = new HttpRequestMessage()
|
||||
{
|
||||
Method = HttpMethod.Post,
|
||||
RequestUri = uri,
|
||||
Headers = {
|
||||
|
||||
{ HttpRequestHeader.Authorization.ToString(), _coreApiUserConnection.StsToken },
|
||||
{ HttpRequestHeader.ContentType.ToString(), "application/json" },
|
||||
{ "X-ApiChannelId", _coreApiConfiguration.ApiChannelId },
|
||||
{ "X-MessageId", Guid.NewGuid().ToString() }
|
||||
}
|
||||
};
|
||||
|
||||
var response = client.SendAsync(request).Result;
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
Log.Error("Unable to set the Pre Login Details");
|
||||
throw new Exception($"Unable to set the Pre Login Details. StatusCode:{response.StatusCode}, ReasonPhrase:{response.ReasonPhrase}");
|
||||
}
|
||||
|
||||
var result = response.Content.ReadAsStringAsync().Result;
|
||||
var preloginConnection = JsonConvert.DeserializeObject<PreloginConnection.PreloginResponse>(result);
|
||||
AddPrelogin(preloginConnection);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Failure to SetPreLoginDetails. Exception: {ex.InnerException}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void AddPrelogin(PreloginConnection.PreloginResponse preloginResponse)
|
||||
{
|
||||
_coreApiUserConnection.EffectiveDate = preloginResponse.MessageBody.PostingDate;
|
||||
_coreApiUserConnection.PostingDate = preloginResponse.MessageBody.PostingDate;
|
||||
|
||||
if (preloginResponse.MessageBody.CashBoxes.Length <= 0 ||
|
||||
preloginResponse.MessageBody.CashBoxes[0] == null)
|
||||
{
|
||||
Log.Error("Core API user does not have a cashbox.");
|
||||
throw new Exception("Core API user does not have a cashbox.");
|
||||
}
|
||||
|
||||
_coreApiUserConnection.CashBoxNumber = preloginResponse.MessageBody.CashBoxes[0].CashboxNumber.ToString();
|
||||
}
|
||||
|
||||
private void SetDnaToken()
|
||||
{
|
||||
try
|
||||
{
|
||||
var body = new DnaTokenConnection.DnaTokenRequest(_coreApiUserConnection);
|
||||
var encoded = JsonConvert.SerializeObject(body);
|
||||
var content = new StringContent(encoded, Encoding.UTF8, "application/json");
|
||||
var uri = HttpUtilities.BuildHttpsUri(_coreApiConfiguration.HostName, _coreApiConfiguration.CoreEndPointConfiguration.DnaToken);
|
||||
var client = HttpUtilities.GetClient(uri);
|
||||
HttpRequestMessage request = new HttpRequestMessage()
|
||||
{
|
||||
Method = HttpMethod.Post,
|
||||
RequestUri = uri,
|
||||
Content = content,
|
||||
Headers = {
|
||||
{ HttpRequestHeader.Authorization.ToString(), _coreApiUserConnection.StsToken },
|
||||
{ "X-ApiChannelId", _coreApiConfiguration.ApiChannelId },
|
||||
{ "X-MessageId", Guid.NewGuid().ToString() },
|
||||
{ HttpRequestHeader.ContentType.ToString(), "application/json" },
|
||||
{ "X-BusinessTaskId", _coreApiConfiguration.BusinessTaskId }
|
||||
}
|
||||
};
|
||||
|
||||
var response = client.SendAsync(request).Result;
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
Log.Error("Unable to set the DNA Token");
|
||||
throw new Exception($"Unable to set the DNA Token. StatusCode:{response.StatusCode}, ReasonPhrase:{response.ReasonPhrase}");
|
||||
}
|
||||
|
||||
var result = response.Content.ReadAsStringAsync().Result;
|
||||
var dnaTokenResponse = JsonConvert.DeserializeObject<DnaTokenConnection.DnaTokenResponse>(result);
|
||||
_coreApiUserConnection.DnaToken = $"Bearer {dnaTokenResponse.MessageBody.Dnatoken}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Failure to SetDnaToken. Exception: {ex.InnerException}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.ConnectionModels;
|
||||
|
||||
namespace LCU.Library.Internal.CoreApiWrapperLib.CoreApiUtilities
|
||||
{
|
||||
public interface ICoreConnection
|
||||
{
|
||||
CoreApiConnection GetCoreApiConnection();
|
||||
void RefreshConnectionCache();
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LCU.Library.Internal.CoreApiWrapperLib.CoreApiUtilities
|
||||
{
|
||||
public interface ICoreRequest
|
||||
{
|
||||
Task<T> GetRequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, string jsonBody = null);
|
||||
Task<T> PostRequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, string jsonBody);
|
||||
Task<T> PutRequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, string jsonBody);
|
||||
Task<T> DeleteRequestObject<T>(string endpoint, Dictionary<string, string> endpointParameters, string jsonBody);
|
||||
Task<string> RequestCoreJsonResponse(string body, HttpMethod httpMethod, string endpoint);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.ConnectionModels;
|
||||
|
||||
namespace LCU.Library.Internal.CoreApiWrapperLib.CoreApiUtilities
|
||||
{
|
||||
public interface ICoreServiceConnection
|
||||
{
|
||||
string GetAccessToken();
|
||||
void RefreshAccessCache();
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using LCU.Library.Internal.CoreApiWrapperLib.ConnectionModels;
|
||||
|
||||
namespace LCU.Library.Internal.CoreApiWrapperLib.CoreApiUtilities
|
||||
{
|
||||
public interface ICoreUserConnection
|
||||
{
|
||||
CoreApiUserConnection GetCoreApiConnection();
|
||||
void RefreshConnectionCache();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user