
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\Configurations\XHttpServiceConfiguration.cs

namespace xHttpService.Configurations {
    public partial class XHttpServiceConfiguration {
        /// <summary>
        /// Determines Http Handler Check SSL or not ...
        /// </summary>
        /// <value></value>
        public bool DisableSSLCheck { get; set; }
        public int DefaultClientTimeout { get; set; } = 360;
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\Constants\ConfigurationNodeNames.cs

namespace xHttpService.Constants {
    public partial struct ConfigurationNodeNames {
        public const string HTTP_SERVICE_NODE_NAME = "HttpServiceConfiguration";
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\Constants\XHttpMethod.cs

using xExceptions.Attributes;

namespace xHttpService.Constants {
    public enum XHttpMethod {
        [StringValue ("GET")]
        GET,

        [StringValue ("POST")]
        POST,

        [StringValue ("PUT")]
        PUT,

        [StringValue ("DELETE")]
        DELETE
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\Constants\XSSEConstants.cs

namespace xHttpService.Constants
{
    public struct XSSEConstants
    {
        public const string DataIdentifier = "data:";
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\DI\XDIHelperExtension.cs

using System;
using xCommons.Extensions;
using xHttpService.Constants;
using xHttpService.Providers;
using xHttpService.Interfaces;
using xHttpService.Configurations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace xHttpService.DI {
    public static partial class XDIHelperExtension {
        /// <summary>
        /// Retrieve XHttpService Configuration from AppSettings
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static XHttpServiceConfiguration GetXHttpServiceConfiguration (this IConfiguration configuration) {
            //
            var xHttpSection = configuration.GetSection (ConfigurationNodeNames.HTTP_SERVICE_NODE_NAME);
            return xHttpSection.Get<XHttpServiceConfiguration> ();
        }

        /// <summary>
        /// Register XHttpService Configuration
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddXHttpServiceConfiguration (
            this IServiceCollection services,
            IConfiguration configuration
        ) {
            //
            var httpServiceConfiguration = configuration.GetXHttpServiceConfiguration ();
            services.AddXHttpServiceConfiguration(httpServiceConfiguration);
        }

        /// <summary>
        /// Register XHttpService Configuration
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddXHttpServiceConfiguration (
            this IServiceCollection services,
            XHttpServiceConfiguration configuration
        ) {
            //
            if (configuration.IsNull ()) {
                Console.WriteLine($"xHttpService: there is no provided configurations, using default ...");
                configuration = new XHttpServiceConfiguration ();
            }

            //
            services.AddSingleton<XHttpServiceConfiguration> (configuration);
        }

        /// <summary>
        /// Register XHttpService on DI ...
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddXHttpService (
            this IServiceCollection services,
            IConfiguration configuration
        ) {
            //
            // Register Service Configuration ...
            if (services.GetRegisteredService<XHttpServiceConfiguration> ().IsNull ()) {
                services.AddXHttpServiceConfiguration (configuration);
            }

            //
            // Register Service ...
            services.AddSingleton<IXHttpProvider, XHttpProvider> ();
        }

        /// <summary>
        /// Register XHttpService on DI ...
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddXHttpService (
            this IServiceCollection services,
            XHttpServiceConfiguration configuration
        ) {
            //
            // Register Service Configuration ...
            if (services.GetRegisteredService<XHttpServiceConfiguration> ().IsNull ()) {
                services.AddXHttpServiceConfiguration (configuration);
            }

            //
            // Register Service ...
            services.AddSingleton<IXHttpProvider, XHttpProvider> ();
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\Extensions\RestSharpExtensions.cs

using RestSharp;
using xModels.Dtos;
using xCommons.Constants;
using xCommons.Extensions;

namespace xHttpService.Extensions
{
    public static partial class RestSharpExtensions
    {
        /// <summary>
        /// Attach an instance of XQuery to a RestRequest object
        /// </summary>
        /// <param name="source"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static RestRequest AttachXQuery(
            this RestRequest source,
            XQuery query
        )
        {
            //
            if (query.IsNull())
            {
                return source;
            }

            //
            // ContainsDetail ...
            //
            var containsDetailKey = System.Uri.EscapeDataString(nameof(query.ContainsDetail));
            var containsDetailValue = query.ContainsDetail.AsHttpParamString();
            source.AddQueryParameter(containsDetailKey, containsDetailValue);

            //
            // IsAscending ...
            var isAscendingKey = System.Uri.EscapeDataString(nameof(query.IsAscending));
            var isAscendingValue = query.IsAscending.AsHttpParamString();
            source.AddQueryParameter(isAscendingKey, isAscendingValue);

            //
            // Filter ...
            if (!query.Filter.IsNullOrEmpty())
            {
                //
                var key = System.Uri.EscapeDataString(nameof(query.Filter));
                var value = query.Filter.AsHttpParamString();
                source.AddQueryParameter(key, value);
            }

            //
            // SortBy ...
            if (!query.SortBy.IsNullOrEmpty())
            {
                //
                var key = System.Uri.EscapeDataString(nameof(query.SortBy));
                var value = query.SortBy.AsHttpParamString();
                source.AddQueryParameter(key, value);
            }

            //
            // Page ...
            if (query.Page > 0)
            {
                //
                var key = System.Uri.EscapeDataString(nameof(query.Page));
                var value = query.Page.AsHttpParamString();
                source.AddQueryParameter(key, value);
            }

            //
            // PageSize ...
            if (query.PageSize > 0)
            {
                //
                var key = System.Uri.EscapeDataString(nameof(query.PageSize));
                var value = query.PageSize.AsHttpParamString();
                source.AddQueryParameter(key, value);
            }

            //
            return source;
        }

        /// <summary>
        /// Add Dest User to Query Strings ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destUser"></param>
        /// <returns></returns>
        public static RestRequest AttachDestUser(
            this RestRequest source,
            string destUser
        )
        {
            //
            if (destUser.IsNullOrEmpty())
            {
                return source;
            }

            //
            var destUserKey = System.Uri.EscapeDataString(nameof(destUser));
            var destUserValue = destUser.AsHttpParamString();
            source.AddQueryParameter(destUserKey, destUserValue);

            //
            return source;
        }

        /// <summary>
        /// Add XPoweredBy Header to specific RestRequest Headers ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="poweredByValue"></param>
        /// <returns></returns>
        public static RestRequest AddXPoweredBy(
            this RestRequest source,
            string poweredByValue
        )
        {
            //
            source.AddHeader(
                XAuthorization.XPoweredBy,
                poweredByValue
            );

            //
            return source;
        }

        /// <summary>
        /// Add XAccessToken Header to specific RestRequest Headers ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static RestRequest AddXAccessToken(
            this RestRequest source,
            string token
        )
        {
            //
            token = $"{XAuthentication.BEARER} {token}";

            //
            source.AddHeader(
                XAuthorization.Header,
                token
            );

            //
            return source;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\Extensions\XSseExtensions.cs

using System;
using System.Text;
using System.Threading;
using xCommons.Extensions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

namespace xHttpService.Extensions
{
    /// <summary>
    /// Server-Sent Events (SSE) Helpers ...
    /// Format (per Spec): [event: name\n] data: line\n ... \n
    /// </summary>
    public static class XSseExtensions
    {
        //
        // Event Names ...
        public const string SseDoneEvent = "done";
        public const string SseErrorEvent = "error";
        public const string SseContentType = "text/event-stream; charset=utf-8";

        /// <summary>
        /// Configure Response for SSE (Headers + Disable Buffering) ...
        /// Must be Called before any Write ...
        /// </summary>
        /// <param name="source"></param>
        public static void PrepareSseResponse(
            this HttpResponse source
        )
        {
            //
            if (source.IsNull() || source.HasStarted)
            {
                return;
            }

            //
            source.StatusCode = StatusCodes.Status200OK;
            source.ContentType = SseContentType;
            source.Headers["Cache-Control"] = "no-cache, no-store";
            source.Headers["X-Accel-Buffering"] = "no";

            //
            // Disable Response Buffering ...
            source.HttpContext.Features
                .Get<IHttpBufferingFeature>()?
                .DisableResponseBuffering();
        }

        /// <summary>
        /// Write an Object as JSON (camelCase) SSE Event ...
        /// </summary>
        public static Task WriteSseEventAsync<T>(
            this HttpResponse source,
            T data,
            string eventName = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var payload = data.IsNull()
                ? "null"
                : data.ToJSON(camelCase: true);

            //
            return source.WriteSseRawAsync(payload, eventName, cancellationToken);
        }

        /// <summary>
        /// Write Raw Text as SSE Event (Multi Line Text is Split into Multiple data: Lines) ...
        /// </summary>
        public static async Task WriteSseRawAsync(
            this HttpResponse source,
            string payload,
            string eventName = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var builder = new StringBuilder();
            if (!eventName.IsNullOrEmpty())
            {
                builder.Append("event: ").Append(eventName).Append('\n');
            }

            //
            var normalized = (payload ?? string.Empty)
                .Replace("\r\n", "\n")
                .Replace('\r', '\n');
            foreach (var line in normalized.Split('\n'))
            {
                builder.Append("data: ").Append(line).Append('\n');
            }
            builder.Append('\n');

            //
            await source.WriteAsync(builder.ToString(), Encoding.UTF8, cancellationToken);
            await source.Body.FlushAsync(cancellationToken);
        }

        /// <summary>
        /// Write Terminating "done" Event ...
        /// </summary>
        public static Task WriteSseDoneAsync(
            this HttpResponse source,
            CancellationToken cancellationToken = default
        )
        {
            return source.WriteSseRawAsync("[DONE]", SseDoneEvent, cancellationToken);
        }

        /// <summary>
        /// Write "error" Event (Never Throws; Used when Stream has Already Started) ...
        /// </summary>
        public static async Task WriteSseErrorAsync(
            this HttpResponse source,
            string message
        )
        {
            //
            try
            {
                await source.WriteSseEventAsync(
                    data: new { error = message ?? "Stream Failed" },
                    eventName: SseErrorEvent,
                    cancellationToken: CancellationToken.None
                );
            }
            catch
            {
                // Client Gone ...
            }
        }

        /// <summary>
        /// Is Exception Caused by Client Disconnect / Cancellation ...
        /// </summary>
        public static bool IsClientCancellation(
            this Exception source,
            CancellationToken cancellationToken
        )
        {
            return source is OperationCanceledException && cancellationToken.IsCancellationRequested;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\Interfaces\IXHttpProvider.cs

using RestSharp;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using xHttpService.Constants;
using xIdentityModels.Models;
using System.Collections.Generic;

namespace xHttpService.Interfaces
{
    public partial interface IXHttpProvider
    {
        /// <summary>
        /// Get an Instance of Http Client 
        /// </summary>
        /// <returns></returns>
        HttpClient GetHttpClient();

        /// <summary>
        /// Retrieve Rest Client ...
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <param name="tokens"></param>
        /// <returns></returns>
        RestClient GetRestClient(
            string baseUrl = null,
            XTokenResponse tokens = null
        );

        /// <summary>
        /// Prepare and Retrieve a Rest Request ...
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="poweredValue"></param>
        /// <param name="params"></param>
        /// <param name="headers"></param>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        RestRequest GetRestRequet(
            string endpoint,
            string poweredValue = null,
            IDictionary<string, string> @params = null,
            IDictionary<string, string> headers = null,
            IDictionary<string, string> queryStrings = null
        );

        /// <summary>
        /// Handle Call Specific Request and retrieve Response
        /// </summary>
        /// <param name="client"></param>
        /// <param name="request"></param>
        /// <param name="method"></param>
        /// <param name="cancellationToken"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        Task<T> RunRestRequest<T>(
            RestClient client,
            RestRequest request,
            XHttpMethod method,
            CancellationToken cancellationToken = default
        );
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xHttpService\Providers\XHttpProvider.cs

using System;
using RestSharp;
using System.Net.Http;
using System.Threading;
using xCommons.Constants;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using xHttpService.Constants;
using xIdentityModels.Models;
using xHttpService.Interfaces;
using RestSharp.Authenticators;
using System.Collections.Generic;
using xHttpService.Configurations;
using Microsoft.Extensions.Logging;

namespace xHttpService.Providers {
    public partial class XHttpProvider : IXHttpProvider {
        //
        private readonly ILogger<XHttpProvider> logger;
        private readonly XHttpServiceConfiguration configuration;

        public XHttpProvider (
            ILogger<XHttpProvider> logger,
            XHttpServiceConfiguration configuration
        )  
        {
            this.logger = logger;
            this.configuration = configuration;
        }

        //
        #region Actions ...
        /// <summary>
        /// Get an Instance of Http Client 
        /// </summary>
        /// <returns></returns>
        public HttpClient GetHttpClient()
        {
            //
            HttpClient httpClient = null;

            //
            // httpClient = new HttpClient ();
            var httpClientHandler = new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
                {
                    //
                    logger.LogInformation(
                        $"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}"
                    );

                    //
                    return true;
                },
                ClientCertificateOptions = ClientCertificateOption.Manual,
            };
            httpClient = new HttpClient(httpClientHandler);

            //
            return httpClient;
        }

        /// <summary>
        /// Retrieve Rest Client ...
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <param name="tokens"></param>
        /// <returns></returns>
        public RestClient GetRestClient(
            string baseUrl = null,
            XTokenResponse tokens = null            
        )
        {
            //
            var client = new RestClient(baseUrl);

            //
            // Set Authenticator ...
            if (!tokens.IsNull() &&
                !tokens.AccessToken.IsNullOrEmpty())
            {
                client.Authenticator = new JwtAuthenticator(tokens.AccessToken);
            }

            //
            // Refresh Token ...
            if (!tokens.IsNull() &&
                !tokens.RefreshToken.IsNullOrEmpty())
            {
                client.AddDefaultHeader(XAuthorization.RefreshToken, tokens.RefreshToken);
            }

            //
            // ExpiresAt ...
            if (!tokens.IsNull() &&
                tokens.ExpiresAt > 0)
            {
                client.AddDefaultHeader(XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString());
            }

            //
            // Set Default Timeout ...
            client.Timeout = configuration.DefaultClientTimeout;

            //
            // SSL Validation Handler ...
            client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
            {
                //
                logger.LogInformation(
                    $"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}"
                );

                //
                return true;
            };

            //
            return client;
        }

        /// <summary>
        /// Prepare and Retrieve a Rest Request ...
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="poweredValue"></param>
        /// <param name="params"></param>
        /// <param name="headers"></param>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        public RestRequest GetRestRequet(
            string endpoint,
            string poweredValue = null,
            IDictionary<string, string> @params = null,
            IDictionary<string, string> headers = null,
            IDictionary<string, string> queryStrings = null
        )
        {
            //
            var url = endpoint;

            //
            // Add Route Payloads ...
            if (!@params.IsNull() && @params.Count > 0)
            {
                //
                var enumerator = @params.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    //
                    var item = enumerator.Current;

                    //
                    url = url.Replace(item.Key, item.Value.ToUrlEncoded());
                }
            }

            //
            // Add Query Strings ...
            if (!queryStrings.IsNull() && queryStrings.Count > 0)
            {
                //
                url = $"{url}?";
                var enumerator = queryStrings.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    //
                    var item = enumerator.Current;

                    //
                    url += $"{item.Key}={item.Value.ToUrlEncoded()}&";
                }

                //
                // remove lates & ...
                if (url.EndsWith("&"))
                {
                    url = url.Substring(0, url.Length - 1);
                }
            }

            //
            // Create request ...
            var request = new RestRequest(url, DataFormat.Json);

            //
            if (!poweredValue.IsNullOrEmpty())
            {
                //
                request.AddHeader(
                    XAuthorization.XPoweredBy, 
                    poweredValue
                );
            }

            //
            // Add Headers to request ...
            if (!headers.IsNull() && headers.Count > 0)
            {
                //
                var enumerator = headers.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    //
                    var item = enumerator.Current;
                    request.AddHeader(item.Key, item.Value);
                }
            }

            //
            return request;
        }

        /// <summary>
        /// Handle Call Specific Request and retrieve Response
        /// </summary>
        /// <param name="client"></param>
        /// <param name="request"></param>
        /// <param name="method"></param>
        /// <param name="cancellationToken"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public async Task<T> RunRestRequest<T>(
            RestClient client,
            RestRequest request,
            XHttpMethod method,
            CancellationToken cancellationToken = default
        )
        {
            //
            var response = await Task.Run(async () =>
            {
                //
                IRestResponse resp = null;

                //
                // Call Endpoint Service using Specified Method ...
                switch (method)
                {
                    //
                    // Get ...
                    case XHttpMethod.GET:
                        resp = client.Get(request);
                        break;

                    //
                    // Put ...
                    case XHttpMethod.PUT:
                        resp = client.Put(request);
                        break;

                    //
                    // Post ...
                    case XHttpMethod.POST:
                        resp = client.Post(request);
                        break;

                    //
                    // Delete ...
                    case XHttpMethod.DELETE:
                        resp = client.Delete(request);
                        break;
                }

                //
                if (!resp.IsSuccessful)
                {
                    //
                    // Log Exception ...
                    logger.LogError($"Error: {resp.ErrorMessage}");
                    logger.LogError($"Exception: {resp.ErrorException.ToJSON()}");
                    if (!resp.ErrorMessage.IsNullOrEmpty() &&
                        resp.ErrorMessage.Contains("timed out"))
                    {
                        XException.Timeout.Throw();
                    }

                    //
                    var ex = resp.Content.ToXError();
                    if (!ex.IsNull())
                    {
                        throw ex.ToException();
                    }

                    //
                    // UnAuthorized ...
                    if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        XException.NotAuthorized.Throw();
                    }

                    //
                    // NotFound ...
                    if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        XException.NotFound.Throw();
                    }

                    //
                    XException.ActionFailed.Throw();
                }

                //
                var result = resp.Content.FromJSON<T>();
                return result;
            }, cancellationToken);

            //
            return response;
        }
        #endregion
    }
}
