### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Attributes\RequireXPoweredAttribute.cs using System.Linq; using xCommons.Constants; using xCommons.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Authorization; namespace xCommons.Attributes { public partial class RequireXPoweredAttribute : AuthorizeAttribute, IAuthorizationFilter { private readonly bool ignoreAnonymous; public RequireXPoweredAttribute (bool IgnoreAnonymous = true) { ignoreAnonymous = IgnoreAnonymous; } public void OnAuthorization (AuthorizationFilterContext context) { // var config = context.GetXAppConfiguration (); // var isExistsXPowered = context.HttpContext.Request.Headers .Any (h => h.Key .ToNormalString () == XAuthorization.XPoweredBy.ToNormalString () && h.Value == config.XPoweredValue); // var isAnonymous = context.IsAnonymousAllowed (); var handler = ignoreAnonymous ? isAnonymous ? false : true : true; // if (handler && !isExistsXPowered) { context.Result = new UnauthorizedResult (); } } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Attributes\XRateLimitAttribute.cs using System; using xCommons.Models; using xCommons.Constants; using xCommons.Extensions; using xCommons.Interfaces; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; namespace xCommons.Attributes { [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true )] public partial class XRateLimitAttribute : Attribute, IActionFilter, IOrderedFilter { public int Limit { get; set; } = 0; public int Order { get; set; } = -1000; public int PeriodSeconds { get; set; } = 0; public string KeyPrefix { get; set; } = null; public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip; public void OnActionExecuting(ActionExecutingContext context) { // var provider = context.HttpContext.RequestServices .GetService(); var configuration = context.HttpContext.RequestServices .GetService(); // if (provider.IsNull() || configuration.IsNull() || !provider.IsEnabled) { return; } // var limit = Limit > 0 ? Limit : configuration.DefaultLimit; // var periodSeconds = PeriodSeconds > 0 ? PeriodSeconds : configuration.DefaultPeriodSeconds; // var key = context.HttpContext.GetXRateLimitKey(KeyMode); if (!KeyPrefix.IsNullOrEmpty()) { key = string.Format("{0}:{1}", KeyPrefix, key); } // var result = provider.TryConsume( key: key, limit: limit, periodSeconds: periodSeconds ); // context.HttpContext.Items[XRateLimitConstants.AppliedItemKey] = true; WriteHeaders(context.HttpContext, result); // if (!result.IsAllowed) { // context.Result = new ObjectResult(new { resetOn = result.ResetOn, retryAfter = result.RetryAfterSeconds, message = "Too many requests. Please try again later.", }) { StatusCode = configuration.StatusCode }; } } public void OnActionExecuted(ActionExecutedContext context) { } private static void WriteHeaders( HttpContext context, XRateLimitResult result ) { // context.Response.Headers[XRateLimitConstants.LimitHeader] = result.Limit.ToString(); // context.Response.Headers[XRateLimitConstants.RemainingHeader] = result.Remaining.ToString(); // context.Response.Headers[XRateLimitConstants.ResetHeader] = result.ResetOn.ToUnixTimeSeconds().ToString(); // if (!result.IsAllowed) { // context.Response.Headers[XRateLimitConstants.RetryAfterHeader] = result.RetryAfterSeconds.ToString(); } } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Authorization\RequiredRolesHandler.cs using System.Linq; using IdentityModel; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; namespace xCommons.Authorization { public partial class RequiredRolesHandler : AuthorizationHandler { protected override Task HandleRequirementAsync ( AuthorizationHandlerContext context, RequiredRolesRequirement requirement ) { // var conatinsRole = context.User.HasClaim (c => c.Type == JwtClaimTypes.Role); if (!conatinsRole) { return Task.CompletedTask; } // var roleClaim = context.User.Claims.FirstOrDefault (c => c.Type == JwtClaimTypes.Role); if (roleClaim == null || !requirement.Roles.Contains (roleClaim.Value) ) { return Task.CompletedTask; } // context.Succeed (requirement); return Task.CompletedTask; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Authorization\RequiredRolesRequirement.cs using Microsoft.AspNetCore.Authorization; namespace xCommons.Authorization { public partial class RequiredRolesRequirement : IAuthorizationRequirement { public string[] Roles { get; } public RequiredRolesRequirement (params string[] Roles) { this.Roles = Roles; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Configurations\XAppConfiguration.cs using System.Collections.Generic; namespace xCommons.Configurations { /// /// represent an xBackend Application /// public partial class XAppConfiguration { public string Name { get; set; } public string Version { get; set; } public string Environment { get; set; } public string XPoweredValue { get; set; } public IEnumerable AllowedOrigins { get; set; } public string WelcomeMessage { get; set; } public string DefaultLanguage { get; set; } public XMessageResourceTitles MessageResourceTitles { get; set; } } public partial class XMessageResourceTitles { public string Terms { get; set; } public string Invite { get; set; } public string RegistrationApprove { get; set; } public string Registered { get; set; } public string VerificationCode { get; set; } public string ChangePassword { get; set; } public string PasswordChanged { get; set; } public string NewDeviceLoggedIn { get; set; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Configurations\XFileTypeDetectorConfiguration.cs namespace xCommons.Configurations { /// /// Configuration options for XFileTypeDetector ... /// public sealed class XFileTypeDetectorConfiguration { /// /// When true, magic bytes are always read first ... /// public bool PreferMagicBytes { get; set; } = true; /// /// Number of bytes read from the stream header ... /// public int HeaderSize { get; set; } = 32; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Configurations\XRateLimitConfiguration.cs using xCommons.Constants; using System.Collections.Generic; namespace xCommons.Configurations { public class XRateLimitConfiguration { public bool Enabled { get; set; } = false; public int StatusCode { get; set; } = 429; public int DefaultLimit { get; set; } = 60; public int DefaultPeriodSeconds { get; set; } = 60; public bool ApplyToAllRoutes { get; set; } = false; public ICollection Rules { get; set; } = []; public XRateLimitKeyMode DefaultKeyMode { get; set; } = XRateLimitKeyMode.Ip; } public partial class XRateLimitRule { public int Limit { get; set; } = 60; public bool Enabled { get; set; } = true; public int PeriodSeconds { get; set; } = 60; public string PathPrefix { get; set; } = "/"; public string Name { get; set; } = string.Empty; public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Configurations\XSwaggerConfiguration.cs using System.Collections.Generic; namespace xCommons.Configurations { public partial class XSwaggerConfiguration { public string Title { get; set; } = ""; public string Version { get; set; } = "V1.0"; public string Description { get; set; } = ""; public string TermsOfServiceUrl { get; set; } = ""; public XSwaggerContact Contact { get; set; } = null; public XSwaggerLicence License { get; set; } = null; public Dictionary DefaultValues {get; set;} = null; } public partial class XSwaggerContact { public string Name { get; set; } public string Email { get; set; } public string Url { get; set; } } public partial class XSwaggerLicence { public string Name { get; set; } public string Url { get; set; } } public partial class XSwaggerDefaultValues { public Dictionary Values { get; set; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\CommonConstants.cs namespace xCommons.Constants { public partial class CommonConstants { public static char DEFAULT_LIST_SEPERATOR = ','; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\ConfigurationNodeNames.cs namespace xCommons.Constants { public partial struct ConfigurationNodeNames { public const string CERTIFICATES_NODE = "Certificates"; public const string SWAGGER_NODE = "SwaggerConfiguration"; public const string RATE_LIMIT_NODE = "RateLimitConfiguration"; public const string FILE_TYPE_DETECTOR_NODE = "FileTypeDetectorConfiguration"; public const string MESSAGE_RESOURCE_TITLES_NODE = "MessageResourceTitles"; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XAuthentication.cs namespace xCommons.Constants { public partial struct XAuthentication { public const string JWT = "jwt"; public const string TOKEN = "token"; public const string BEARER = "Bearer"; public const string SMART_SCHEME = "XSmartScheme"; public const string INTROSPECTION = "introspection"; public const string IDENTITY_SERVER_LOCAL_API = "IdentityServerAccessToken"; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XAuthorization.cs namespace xCommons.Constants { public partial struct XAuthorization { public const string XApiKey = "X-Api-Key"; public const string Header = "Authorization"; public const string ExpiresAt = "expires_at"; public const string XPoweredBy = "X-PoweredBy"; public const string TokenIdentifier = "Bearer "; public const string AccessToken = "access_token"; public const string RefreshToken = "refresh_token"; public const int ThresholdBeforeTokenExpiration = 600; public const string RevisionChecksum = "revision_checksum"; public const string AccessTokenExpired = "AccessToken-Expired"; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XCustomClaims.cs namespace xCommons.Constants { public partial struct XCustomClaims { public const string Bio ="bio"; public const string Role = "role"; public const string UserId = "sub"; public const string Issuer = "iss"; public const string Scope = "scope"; public const string Email = "email"; public const string Audience = "aud"; public const string Gender = "gender"; public const string ExpiredOn = "exp"; public const string Picture = "picture"; public const string AuthType = "auth_type"; public const string IsBanned = "is_banned"; public const string ClientId = "client_id"; public const string BrithDate = "birthdate"; public const string IsEnabled = "is_enabled"; public const string UserName = "unique_name"; public const string FirstName = "given_name"; public const string LastName = "family_name"; public const string CoverImage = "cover_image"; public const string PhoneNumber = "phone_number"; public const string AuthenticatedOn = "auth_time"; public const string OpenToSearch = "open_to_search"; public const string EmailVerified = "email_verified"; public const string ApplicationId = "application_id"; public const string PhoneNumberVerified = "phone_number_verified"; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XDeviceType.cs namespace xCommons.Constants { /// /// a collection of available Client Devices /// public enum XDeviceType { Unknown, Mobile, Tablet, Desktop } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XFileExtensions.cs using xExceptions.Attributes; namespace xCommons.Constants { /// /// File Extensions Enumerable ... /// /// Document: 100–133 /// Archive: 200–202 /// Internal Supports: 300–302 /// Video: 400–405 /// Audio: 500–505 /// Image: 600–609 /// public enum XFileExtensions { // #region Document ... [StringValue(".txt")] TEXT = 100, [StringValue(".pdf")] PDF = 101, [StringValue(".ppt")] PPT = 102, [StringValue(".pptx")] PPTX = 103, [StringValue(".odp")] ODP = 104, [StringValue(".pps")] PPS = 105, [StringValue(".ods")] ODS = 106, [StringValue(".xlr")] XLR = 107, [StringValue(".xls")] XLS = 108, [StringValue(".xlsx")] XLSX = 109, [StringValue(".xml")] XML = 110, [StringValue(".doc")] DOC = 111, [StringValue(".docx")] DOCX = 112, [StringValue(".odt")] ODT = 113, [StringValue(".rtf")] RTF = 114, [StringValue(".tex")] TEX = 115, [StringValue(".wpd")] WPD = 116, [StringValue(".md")] MD = 117, [StringValue(".cs")] CSHARP = 118, [StringValue(".py")] PYTHON = 119, [StringValue(".js")] JAVASCRIPT = 120, [StringValue(".ts")] TYPESCRIPT = 121, [StringValue(".java")] JAVA = 122, [StringValue(".go")] GO = 123, [StringValue(".rs")] RUST = 124, [StringValue(".rb")] RUBY = 125, [StringValue(".php")] PHP = 126, [StringValue(".csv")] CSV = 127, [StringValue(".json")] JSON = 128, [StringValue(".yml")] YML = 129, [StringValue(".yaml")] YAML = 130, [StringValue(".css")] CSS = 131, [StringValue(".htm")] HTM = 132, [StringValue(".html")] HTML = 133, #endregion // #region Archive ... [StringValue(".zip")] ZIP = 200, [StringValue(".rar")] RAR = 201, [StringValue(".7z")] SEVENZIP = 202, #endregion // #region Internal Supports ... [StringValue(".ttf")] TTF = 300, [StringValue(".sdw")] SAHER_DASHBOARD_WIDGET = 301, [StringValue(".sdwmanifest")] SAHER_DASHBOARD_WIDGET_MANIFEST = 302, #endregion // #region Video ... [StringValue(".mp4")] MP4 = 400, [StringValue(".avi")] AVI = 401, [StringValue(".mpg")] MPG = 402, [StringValue(".mpeg")] MPEG = 403, [StringValue(".wmv")] WMV = 404, [StringValue(".webm")] WEBM = 405, #endregion // #region Audio ... [StringValue(".mp3")] MP3 = 500, [StringValue(".ogg")] OGG = 501, [StringValue(".wav")] WAV = 502, [StringValue(".wma")] WMA = 503, [StringValue(".aac")] AAC = 504, [StringValue(".m4a")] M4A = 505, #endregion // #region Image ... [StringValue(".png")] PNG = 600, [StringValue(".jpeg")] JPEG = 601, [StringValue(".jpg")] JPG = 602, [StringValue(".ico")] ICON = 603, [StringValue(".gif")] GIF = 604, [StringValue(".bmp")] BITMAP = 605, [StringValue(".webp")] WEBP = 606, [StringValue(".tif")] TIF = 607, [StringValue(".tiff")] TIFF = 608, [StringValue(".svg")] SVG = 609, #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XFileMimeTypes.cs using xExceptions.Attributes; namespace xCommons.Constants { /// /// MIME Types mapped to XFileExtensions ... /// /// Document: 100–133 /// Archive: 200–202 /// Internal Supports: 300–302 /// Video: 400–405 /// Audio: 500–505 /// Image: 600–609 /// public enum XFileMimeTypes { // #region Document ... [StringValue("text/plain")] TEXT = 100, [StringValue("application/pdf")] PDF = 101, [StringValue("application/vnd.ms-powerpoint")] PPT = 102, [StringValue("application/vnd.openxmlformats-officedocument.presentationml.presentation")] PPTX = 103, [StringValue("application/vnd.oasis.opendocument.presentation")] ODP = 104, [StringValue("application/vnd.ms-powerpoint")] PPS = 105, [StringValue("application/vnd.oasis.opendocument.spreadsheet")] ODS = 106, [StringValue("application/vnd.ms-excel")] XLR = 107, [StringValue("application/vnd.ms-excel")] XLS = 108, [StringValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")] XLSX = 109, [StringValue("text/xml")] XML = 110, [StringValue("application/msword")] DOC = 111, [StringValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document")] DOCX = 112, [StringValue("application/vnd.oasis.opendocument.text")] ODT = 113, [StringValue("application/rtf")] RTF = 114, [StringValue("application/x-tex")] TEX = 115, [StringValue("application/vnd.wordperfect")] WPD = 116, [StringValue("text/markdown")] MD = 117, [StringValue("text/x-csharp")] CSHARP = 118, [StringValue("text/x-python")] PYTHON = 119, [StringValue("application/javascript")] JAVASCRIPT = 120, [StringValue("application/typescript")] TYPESCRIPT = 121, [StringValue("text/x-java")] JAVA = 122, [StringValue("text/x-go")] GO = 123, [StringValue("text/x-rust")] RUST = 124, [StringValue("text/x-ruby")] RUBY = 125, [StringValue("text/x-php")] PHP = 126, [StringValue("text/csv")] CSV = 127, [StringValue("application/json")] JSON = 128, [StringValue("application/x-yaml")] YML = 129, [StringValue("application/x-yaml")] YAML = 130, [StringValue("text/css")] CSS = 131, [StringValue("text/html")] HTM = 132, [StringValue("text/html")] HTML = 133, #endregion // #region Archive ... [StringValue("application/zip")] ZIP = 200, [StringValue("application/x-rar-compressed")] RAR = 201, [StringValue("application/x-7z-compressed")] SEVENZIP = 202, #endregion // #region Internal Supports ... [StringValue("font/ttf")] TTF = 300, [StringValue("application/x-sdw")] SAHER_DASHBOARD_WIDGET = 301, [StringValue("application/x-sdwmanifest")] SAHER_DASHBOARD_WIDGET_MANIFEST = 302, #endregion // #region Video ... [StringValue("video/mp4")] MP4 = 400, [StringValue("video/x-msvideo")] AVI = 401, [StringValue("video/mpeg")] MPG = 402, [StringValue("video/mpeg")] MPEG = 403, [StringValue("video/x-ms-wmv")] WMV = 404, [StringValue("video/webm")] WEBM = 405, #endregion // #region Audio ... [StringValue("audio/mpeg")] MP3 = 500, [StringValue("audio/ogg")] OGG = 501, [StringValue("audio/wav")] WAV = 502, [StringValue("audio/x-ms-wma")] WMA = 503, [StringValue("audio/aac")] AAC = 504, [StringValue("audio/mp4")] M4A = 505, #endregion // #region Image ... [StringValue("image/png")] PNG = 600, [StringValue("image/jpeg")] JPEG = 601, [StringValue("image/jpeg")] JPG = 602, [StringValue("image/x-icon")] ICON = 603, [StringValue("image/gif")] GIF = 604, [StringValue("image/bmp")] BITMAP = 605, [StringValue("image/webp")] WEBP = 606, [StringValue("image/tiff")] TIF = 607, [StringValue("image/tiff")] TIFF = 608, [StringValue("image/svg+xml")] SVG = 609, #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XFileType.cs using xExceptions.Attributes; namespace xCommons.Constants { public enum XFileType { Image, ProfileImasge, CoverImage, Audio, Video, Document } public enum XFileCategory { [StringValue("Document")] Document = 100, [StringValue("Archive")] Archive = 200, [StringValue("Internal")] Internal = 300, [StringValue("Video")] Video = 400, [StringValue("Audio")] Audio = 500, [StringValue("Image")] Image = 600 } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XFileTypeDetectionSource.cs using xExceptions.Attributes; namespace xCommons.Constants { /// /// File Type Detection Source ... /// public enum XFileTypeDetectionSource { [StringValue("None")] None = 0, [StringValue("MagicBytes")] MagicBytes = 1, [StringValue("Extension")] Extension = 2, [StringValue("ProvidedMime")] ProvidedMime = 3, [StringValue("Fallback")] Fallback = 4 } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XPolicy.cs namespace xCommons.Constants { public partial struct XPolicy { public const string AllowedOrigins = "AllowedOrigins"; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XRateLimitConstants.cs namespace xCommons.Constants { /// /// RateLimit Implementation Constants ... /// public partial struct XRateLimitConstants { public const string CacheKeyPrefix = "xratelimit"; public const string ClientIdHeader = "X-ClientId"; public const string RetryAfterHeader = "Retry-After"; public const string LimitHeader = "X-RateLimit-Limit"; public const string ResetHeader = "X-RateLimit-Reset"; public const string AppliedItemKey = "X-RateLimit-Applied"; public const string RemainingHeader = "X-RateLimit-Remaining"; } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Constants\XRateLimitKeyMode.cs using xExceptions.Attributes; namespace xCommons.Constants { /// /// RateLimiting Modes ... /// public enum XRateLimitKeyMode { [StringValue("Ip")] Ip = 0, [StringValue("ClientId")] ClientId = 1, [StringValue("User")] User = 2, [StringValue("Route")] Route = 3, [StringValue("Custom")] Custom = 4 } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Controllers\XBaseApiController.cs using xCommons.Providers; using xCommons.Attributes; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace xCommons.Controllers { /// /// Base Api Controller /// [ApiController] [RequireXPowered(true)] [Route("api/[controller]")] [Produces("application/json")] public abstract partial class XBaseApiController : XBaseController { protected XBaseApiController( ILogger logger, XAppConfiguration appConfiguration, XValidationProvider validationProvider ) : base( logger, appConfiguration, validationProvider ) { } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Controllers\XBaseApiV1Controller.cs using xCommons.Providers; using xCommons.Attributes; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace xCommons.Controllers { /// /// Base Api V1 Controller /// [ApiController] [ApiVersion("1.0")] [RequireXPowered(true)] [Route("api/v{version:apiVersion}/[controller]")] public abstract partial class XBaseApiV1Controller : XBaseApiController { protected XBaseApiV1Controller( ILogger logger, XAppConfiguration appConfiguration, XValidationProvider validationProvider ) : base( logger, appConfiguration, validationProvider ) { } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Controllers\XBaseController.cs using System; using xCommons.Providers; using xCommons.Attributes; using xCommons.Extensions; using xExceptions.Constants; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Authorization; namespace xCommons.Controllers { /// /// Base Controller /// [Route ("[controller]")] [Produces ("application/json")] public abstract partial class XBaseController : ControllerBase { public ILogger Logger { get; } public XAppConfiguration AppConfiguration { get; } public XValidationProvider ValidationProvider { get; } protected XBaseController ( ILogger logger, XAppConfiguration appConfiguration, XValidationProvider validationProvider ) { Logger = logger; AppConfiguration = appConfiguration; ValidationProvider = validationProvider; } /// /// Check the Controller Up and Running /// /// string message [HttpGet] [Route ("Test/Hi")] [AllowAnonymous] public virtual IActionResult Hi () { // var controllerName = GetControllerName (); var message = $"{controllerName} Controller is Up and running ..."; // return Ok (message); } /// /// Check Controller ByPass XPowered Filter /// /// string message [HttpGet] [AllowAnonymous] [RequireXPowered (false)] [Route ("Test/PassRequireXPowered")] public virtual IActionResult PassRequireXPowered () { // var controllerName = GetControllerName (); var message = $"{controllerName} Controller bypass RequiredXPowered and Up and running ..."; // return Ok (message); } // #region Non Actions ... /// /// Convert an Exception to Propper Error Result /// /// /// [NonAction] public ActionResult GetExceptionActionResult (Exception ex) { // var exception = GetExceptionResult (ex); var error = ex.Message.ToXError (); // Logger.LogError ($"exception: {exception}, error: {error}"); // try { var xError = exception.Message.ToXError (); var xException = (XException) xError.Id; // switch (xException) { // case XException.NotFound: return NotFound (error); // case XException.NotAuthorized: return Unauthorized (); } } catch { } // return BadRequest (error); } /// /// Return Structured Exception /// /// /// [NonAction] public Exception GetExceptionResult (Exception ex) { // // Log Exception Message ... Logger.LogError (ex.Message); // // if Happens Exception is Know Error // catch it and return it in BadRequest Container ... var isEr = ex.Message.IsXError (); // if (isEr) { return ex; } // // if catched Exception Contains Unknown Error // return an Unknown Error ... return XException.Unknown.ToException (); } /// /// Retrieve ControllerName /// /// [NonAction] public string GetControllerName () { return this.ControllerContext.RouteData.Values["controller"].ToString (); } #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\DI\XDIHelperExtension.cs using xCommons.Providers; using xCommons.Extensions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; public static partial class XDIHelperExtension { /// /// Register XCommons Module Services /// /// public static void AddXCommons(this IServiceCollection services) { services.AddSingleton(); } /// /// Register XCommons Module Service ... /// /// /// public static void AddXCommons( this IServiceCollection services, IConfiguration configuration ) { // services.AddXCommons(); services.AddXFileTypeDetector(configuration); } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\BackgroundServiceExtensions.cs using xCommons.Providers; using Microsoft.Extensions.DependencyInjection; namespace xCommons.Extensions { public static class BackgroundServiceExtensions { /// /// Register Background Services ... /// /// /// public static void AddXBackgroundService( this IServiceCollection source ) where TService : XBackgroundService { // source.AddSingleton(); source.AddHostedService(); } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\CertificateExtensions.cs using xCommons.Models; using xCommons.Constants; using Microsoft.Extensions.Configuration; namespace xCommons.Extensions { public static partial class CertificateExtensions { /// /// Retrieve Specific Certificate From app Settings /// /// /// /// public static XCertificate GetCertificate (this IConfiguration configuration, string name) { // var certificatesSection = configuration.GetSection (ConfigurationNodeNames.CERTIFICATES_NODE); var certificateSection = certificatesSection.GetSection (name); var certificate = certificateSection.Get (); // return certificate; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\CommonExtensions.cs using System; using System.IO; using System.Web; using System.Xml; using AutoMapper; using System.Linq; using System.Text; using Newtonsoft.Json; using xCommons.Helpers; using System.Threading; using System.Reflection; using xCommons.Constants; using Newtonsoft.Json.Linq; using System.Globalization; using xExceptions.Constants; using System.Threading.Tasks; using xExceptions.Attributes; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Cryptography; using Newtonsoft.Json.Serialization; using System.Collections.ObjectModel; using System.Text.RegularExpressions; using xCommons.Configurations; namespace xCommons.Extensions { public static partial class CommonExtensions { /// /// Conert XMLNode to String ... /// /// /// /// public static string ToString(this XmlNode node, int indentation = 2) { // using (var sw = new StringWriter()) { // using (var xw = new XmlTextWriter(sw)) { xw.Formatting = System.Xml.Formatting.Indented; xw.Indentation = indentation; node.WriteContentTo(xw); } // return sw.ToString(); } } /// /// Converts a Json String to Dictionary of String Mappings /// /// Json String /// public static Dictionary JSONToDictionary(this string source) { // try { return JsonConvert.DeserializeObject>(source); } catch { return null; } } /// /// Convert properties of specific Class instance to Dictionary ... /// /// class instance /// public static Dictionary ToDictionary(this T source) where T : class { // var result = new Dictionary(); // if (source.IsNull()) { return result; } // PropertyInfo[] propertyInfos = source.GetType().GetProperties(); if (!propertyInfos.HasChild()) { return result; } // foreach (PropertyInfo propertyInfo in propertyInfos) { result.Add( propertyInfo.Name, propertyInfo .GetValue(source, null) .ToString() ); } // return result; } /// /// run specific task and retrieve result ... /// /// public static void RunTask(this Task source) { source. GetAwaiter() .GetResult(); } /// /// run specific task and retrieve result ... /// /// public static T RunTask(this Task source) { return source. GetAwaiter() .GetResult(); } /// /// Convert XML String to Json Object ... /// /// /// public static string ToJSON(this string source) { // var result = string.Empty; try { // result = XMLToJSONHelper.ToJSON(source); // // Handle Removing Additional Values ... result = result.Replace("s:", "").Replace("a:", ""); } catch { } // return result; } /// /// Convert object to Json ... /// /// /// public static string ToJSON(this T value) where T : class { // if (value.IsNull()) { return string.Empty; } // var setting = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, PreserveReferencesHandling = PreserveReferencesHandling.None }; // return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, setting); } /// /// Convert to Json With Support of Camel Casing /// /// /// /// public static string ToJSON(this T value, bool camelCase = false) { // if (value.IsNull()) { return string.Empty; } // var setting = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, PreserveReferencesHandling = PreserveReferencesHandling.None, }; // if (camelCase) { setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); } // return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, setting); } /// /// Map to Dynamic Object ... /// /// /// public static dynamic ToDynamicObject(this string source) { return JsonConvert.DeserializeObject(source); } /// /// Map to Dynamic Object ... /// /// /// public static dynamic ToDynamicObject(this object source) { // var dMapConfig = new MapperConfiguration(b => { }); var dMapper = dMapConfig.CreateMapper(); // return dMapper.Map(source); } /// /// Parse From Dynamic Object ... /// /// /// /// public static T FromDynamicObject(this object source) where T : class { // var dMapConfig = new MapperConfiguration(b => { }); var dMapper = dMapConfig.CreateMapper(); dynamic dSource = source; // return dMapper.Map(dSource); } /// /// Convert Type of Object to Safe Type /// /// /// /// public static T ConvertTo(this object source) { // T result = default(T); // try { // T item = (T)Convert.ChangeType(source, typeof(T)); // result = item; } catch { } // return result; } /// /// Convert an Instance to another Instance /// using AutoMapper dynamic Convertion /// /// /// /// public static T MapConvert(this T source) where T : class { // if (source.IsNull()) { return null; } // var dSource = (object)source.ToDynamicObject(); return dSource.FromDynamicObject(); } /// /// Convert Using Auto Mapper ... /// /// /// /// /// /// public static T MapConvert( this E source, Action cfgAction = null ) where T : class where E : class { // if (source.IsNull()) { return null; } // var dMapConfig = new MapperConfiguration(b => { // b.CreateMap() .ReverseMap(); // // Use Specified Provided Actions if Exists ... if (!cfgAction.IsNull()) { cfgAction.Invoke(b); } }); var dMapper = dMapConfig.CreateMapper(); // var dSource = (object)dMapper.Map(source); var result = dMapper.Map(dSource); // return result; } /// /// Convert Using Auto Mapper ... /// /// /// /// /// /// public static IEnumerable MapConvert( this IEnumerable source, Action cfgAction = null ) { // if (source.IsNull()) { return null; } // var dMapConfig = new MapperConfiguration(b => { // b.CreateMap() .ReverseMap(); // // Use Specified Provided Actions if Exists ... if (!cfgAction.IsNull()) { cfgAction.Invoke(b); } }); var dMapper = dMapConfig.CreateMapper(); // var dSource = (object)dMapper.Map(source); var result = dMapper.Map>(dSource); // return result; } /// /// Convert Using Auto Mapper ... /// /// /// /// /// /// public static ICollection MapConvert( this ICollection source, Action cfgAction = null ) { // if (source.IsNull()) { return null; } // var dMapConfig = new MapperConfiguration(b => { // b.CreateMap() .ReverseMap(); // // Use Specified Provided Actions if Exists ... if (!cfgAction.IsNull()) { cfgAction.Invoke(b); } }); var dMapper = dMapConfig.CreateMapper(); // var dSource = (object)dMapper.Map(source); var result = dMapper.Map>(dSource); // return result; } /// /// Convert Using Auto Mapper ... /// /// /// /// /// /// public static IList MapConvert( this IList source, Action cfgAction = null ) { // if (source.IsNull()) { return null; } // var dMapConfig = new MapperConfiguration(b => { // b.CreateMap() .ReverseMap(); // // Use Specified Provided Actions if Exists ... if (!cfgAction.IsNull()) { cfgAction.Invoke(b); } }); var dMapper = dMapConfig.CreateMapper(); // var dSource = (object)dMapper.Map(source); var result = dMapper.Map>(dSource); // return result; } /// /// Convert Using Auto Mapper ... /// /// /// /// /// /// /// public static IDictionary MapConvert( this IDictionary source, Action cfgAction = null ) { // if (source.IsNull()) { return null; } // var dMapConfig = new MapperConfiguration(b => { // b.CreateMap() .ReverseMap(); // // Use Specified Provided Actions if Exists ... if (!cfgAction.IsNull()) { cfgAction.Invoke(b); } }); var dMapper = dMapConfig.CreateMapper(); // var dSource = (object)dMapper.Map(source); var result = dMapper.Map>(dSource); // return result; } /// /// Convert a Type to Static Type /// /// /// /// public static T ToStatic(this object source) { // var entity = Activator.CreateInstance(); // var properties = source as IDictionary; // if (properties == null) { return entity; } // foreach (var entry in properties) { // var propertyInfo = entity.GetType().GetProperty(entry.Key); if (propertyInfo != null) { propertyInfo.SetValue(entity, entry.Value, null); } } // return entity; } /// /// Convert From Json String ... /// /// /// /// public static T FromJSON(this string value) { return JsonConvert.DeserializeObject(value); } /// /// Convert From Json String ... /// /// /// /// public static object FromJSON( this string value, Type type ) { return JsonConvert .DeserializeObject(value, type); } /// /// Search a Json String for Specific Node ... /// /// /// /// public static List FindTokens(this JToken containerToken, string name) { List matches = new List(); FindTokens(containerToken, name, matches); return matches; } /// /// Convert to MD5 Bytes ... /// /// /// public static byte[] ToMd5Bytes(this string source) { return new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(source)); } /// /// Convert to MD5 String ... /// /// /// public static string ToMd5String(this string source) { // // string representation (similar to UNIX format) return BitConverter.ToString(source.ToMd5Bytes()) // without dashes .Replace("-", string.Empty) // make lowercase .ToLower(); } /// /// Check a String is MD5 String or not ... /// /// /// public static bool IsMD5String(this string source) { // if (String.IsNullOrEmpty(source)) { return false; } // return Regex.IsMatch(source, "^[0-9a-fA-F]{32}$", RegexOptions.Compiled); } /// /// Convert an string to Byte array Representation ... /// /// /// public static byte[] ToBytes(this string source) { return Encoding.UTF8.GetBytes(source); } /// /// Converts Byte Array to String Value ... /// /// /// public static string FromBytes(this byte[] source) { // var result = Encoding.UTF8.GetString(source, 0, source.Length); return result; } /// /// Check object is Null ... /// /// /// public static bool IsNull(this object source) { return source == null; } /// /// Check collection Has Childs ... /// /// /// /// public static bool HasChild(this IList source) { return !source.IsNull() && source.Count() > 0; } /// /// Check collection Has Childs ... /// /// /// /// public static bool HasChild(this ICollection source) { return !source.IsNull() && source.Count() > 0; } /// /// Check collection Has Childs ... /// /// /// /// public static bool HasChild(this IEnumerable source) { return !source.IsNull() && source.Count() > 0; } /// /// Select Async ... /// /// /// /// /// /// public static async Task> SelectAsync( this IEnumerable source, Func> method ) { return await Task.WhenAll(source.Select(async s => await method(s))); } /// /// Converts an Enumerable to Async Enumerable ... /// /// /// /// /// public static async IAsyncEnumerable ToAsyncEnumerable( this IEnumerable source, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default ) { // foreach (var item in source) { // if (cancellationToken.IsCancellationRequested) { yield break; } // yield return item; } } /// /// Converts an Stream to Model AsyncEnumerator ... /// /// /// /// /// public static async IAsyncEnumerable ToModelAsyncEnumerable( this Stream source, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default ) { // // Validate Stream ... if (source.IsNull()) { yield break; } // while (source.CanRead) { // var model = await source .ReadModelFromStream(cancellationToken); // yield return model; } } /// /// Converts an Stream to String AsyncEnumerator ... /// using Read Line of Stream Reader ...S /// /// /// /// public static async IAsyncEnumerable ToStringAsyncEnumerable( this Stream source, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default ) { // // Validate Stream ... if (source.IsNull()) { yield break; } // while (source.CanRead) { // var json = await source .ReadJsonFromStream(cancellationToken); // yield return json; } } /// /// Write a Model to Stream ... /// /// an Stream to Write ... /// a Model instance to Write ... /// /// /// public static async Task WriteModelToStream( this Stream source, T model, CancellationToken cancellationToken = default ) { // // Validate Args ... if (source.IsNull() || model.IsNull()) { return; } // // Extract Json of Model ... var json = model.ToJSON(true); // await source.WriteJsonToStream( json: json, cancellationToken: cancellationToken ); } /// /// Write a Json String to Stream ... /// /// an Stream to Write ... /// json string to write ... /// /// public static async Task WriteJsonToStream( this Stream source, string json, CancellationToken cancellationToken = default ) { // // Validate Args ... if (source.IsNull() || json.IsNullOrEmpty()) { return; } // using (var streamWriter = new StreamWriter(stream: source)) { // using (var jsonWriter = new JsonTextWriter(streamWriter)) { // await jsonWriter.WriteRawAsync(json, cancellationToken); await jsonWriter.FlushAsync(cancellationToken); } } } /// /// Read a Json Model From Stream ... /// /// /// /// /// public static async Task ReadModelFromStream( this Stream source, CancellationToken cancellationToken = default ) { // T result = default(T); // var json = await source.ReadJsonFromStream(cancellationToken); if (!json.IsNullOrEmpty()) { // try { result = json.FromJSON(); } catch { } } // return result; } /// /// Reading Json String From Stream ... /// /// an Stream to Write ... /// /// public static async Task ReadJsonFromStream( this Stream source, CancellationToken cancellationToken = default ) { // var result = string.Empty; // // Validate Args ... if (source.IsNull()) { return result; } // using (var streamReader = new StreamReader(source)) { // result = await Task.Run(() => { return streamReader.ReadLine(); }, cancellationToken); } // return result; } /// /// Update a Collection item ... /// /// /// /// /// /// public static IList Update( this IList source, T sourceItem, T updateWith ) { // var result = new List(); // // Validate Args ... if (!source.HasChild() || updateWith.IsNull() || sourceItem.IsNull() ) { return result; } // // Extract Item from source ... result = source .Except(new List() { sourceItem }) .ToList(); result.Add(updateWith); // return source; } /// /// Update a Collection item ... /// /// /// /// /// /// public static ICollection Update( this ICollection source, T sourceItem, T updateWith ) { // var result = new List(); // // Validate Args ... if (!source.HasChild() || updateWith.IsNull() || sourceItem.IsNull() ) { return result; } // // Extract Item from source ... result = source .Except(new List() { sourceItem }) .ToList(); result.Add(updateWith); // return source; } /// /// Update a Collection item ... /// /// /// /// /// /// public static IEnumerable Update( this IEnumerable source, T sourceItem, T updateWith ) { // var result = new List(); // // Validate Args ... if (!source.HasChild() || updateWith.IsNull() || sourceItem.IsNull() ) { return result; } // // Extract Item from source ... result = source .Except(new List() { sourceItem }) .ToList(); result.Add(updateWith); // return source; } /// /// Select and Retrieve Nth Childs of given List ... /// /// /// /// /// /// public static IEnumerable GetNthItems(this IList source, int n, bool throwException = false) { // var result = new List(); if (n < 1 || n > source.Count || source.IsNull() || !source.HasChild()) { if (throwException) { throw XException.InvalidArgs.ToException(); } else { return result; } } // var index = 0; foreach (var item in source) { // result.Add(item); index++; // if (index >= n) { break; } } // return result; } /// /// Select and Retrieve Nth Childs of given List ... /// /// /// /// /// /// public static IEnumerable GetNthItems(this ICollection source, int n, bool throwException = false) { return source.ToList().GetNthItems( n: n, throwException: throwException ); } /// /// Select and Retrieve Nth Childs of given List ... /// /// /// /// /// /// public static IEnumerable GetNthItems(this IEnumerable source, int n, bool throwException = false) { return source.ToList().GetNthItems( n: n, throwException: throwException ); } /// /// Check an string is Null or Empty ... /// /// /// public static bool IsNullOrEmpty(this string sourse) { return string.IsNullOrEmpty(sourse); } /// /// Get string Value Attribute of an Enum ... /// /// /// public static string GetStringValue(this Enum source) { var type = source.GetType(); var fieldInfo = type.GetField(source.ToString()); var attributes = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[]; return attributes != null && attributes.Length > 0 ? attributes[0].StringValue : null; } /// /// Extracts digit's of an string ... /// /// /// public static string GetDigits(this string source) { try { // Regex regexObj = new Regex(@"[^\d]"); return regexObj.Replace(source, ""); } catch { return null; } } /// /// Check an string is contains only digits ... /// /// /// public static bool IsDigits(this string source) { return (source.GetDigits() != null && source.GetDigits().ToString() == source); } /// /// Convert to normal string, Trim and ToLower ... /// /// /// public static string ToNormalString(this string source) { // if (source.IsNullOrEmpty()) { return string.Empty; } // return source.Trim().ToLowerInvariant(); } /// /// Capitalize an string ... /// /// /// public static string Capitalize(this string source) { // if (source.IsNullOrEmpty()) { return string.Empty; } // var result = ""; if (source.Length > 1) { // var firstCharr = source.Substring(0, 1); var otherParts = source.Substring(1, source.Length - 1); // result = firstCharr.ToUpperInvariant() + otherParts; } else { result = source.ToUpperInvariant(); } // return result; } /// /// Summarize a Text ... /// /// /// /// /// public static string SummarizeContent( this string source, int maxAllowedLength = 0, string endsWith = "" ) { // var result = string.Empty; if (source.IsNullOrEmpty() || maxAllowedLength <= 0) { // result = source; return result; } // // Pattern of Links ... var pattern = @"(?:[!]\[(.*?)\]\(.*?\))"; // // Apply Summarization ... // // Replace Markdown Links using RegExp ... result = Regex.Replace(source, pattern, ""); // // Do Summarization if Length bigger than MaxLength ... if (result.Length > maxAllowedLength) { result = result.Substring(0, maxAllowedLength); } // // Apply EndsWith if Provided ... if (!endsWith.IsNullOrEmpty() && !result.EndsWith(endsWith)) { result += endsWith; } // return result; } /// /// Check an string is a Valid Representation of PhoneNumber ... /// /// /// public static bool IsValidMobileNumber(this string source) { // // Validating Mobile Numbers ... var phoneNumberUtil = PhoneNumbers.PhoneNumberUtil.GetInstance(); try { // var mPhoneNumber = phoneNumberUtil.Parse(source, null); if (phoneNumberUtil.IsValidNumber(mPhoneNumber)) { // return true; } // return false; } catch { // return false; } } /// /// Check an string is Valid Representation of Email Address ... /// /// /// public static bool IsValidEmail(this string source) { try { var addr = new System.Net.Mail.MailAddress(source); return addr.Address == source; } catch { return false; } } /// /// Check an string is Valid Representation of URL Address ... /// /// /// public static bool IsValidUrl(this string url) { return Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute); } /// /// check a URL has / at the end, if not add one ... /// /// /// public static string NormalizeUrl(this string url) { return url.EndsWith("/") ? url : url + "/"; } /// /// Check an string is GUID or not ... /// /// /// public static bool IsGuid(this string source) { // // Validate Args ... if (source.IsNullOrEmpty()) { return false; } // Guid guid; var result = Guid.TryParse(source, out guid); // return result; } /// /// Check Specific Guid string is Default Guid or not ... /// /// /// public static bool IsDefaultGuid(this string guid) { // if (!guid.IsGuid()) { return false; } // var empty = Guid.Empty.ToString(); return guid == empty; } /// /// Check Specific Guid is Default Guid or not ... /// /// /// public static bool IsDefaultGuid(this Guid guid) { // var empty = Guid.Empty; return guid == empty; } /// /// Parse an String to related Enumerable Items ... /// /// /// /// /// public static IEnumerable ParseListString( this string source, char? separator = null ) { // if (!separator.HasValue) { separator = CommonConstants.DEFAULT_LIST_SEPERATOR; } // var list = source.Split(separator.Value); var result = new Collection(); // foreach (var s in list) { // try { // T item = (T)Convert.ChangeType(s, typeof(T)); // result.Add(item); } catch { } } // return result; } /// /// Converts a List String Representation to GUid List ... /// /// /// /// public static IEnumerable ParseListGuid( this string list, char? separator = null ) { // var result = new List(); // if (!separator.HasValue) { separator = CommonConstants.DEFAULT_LIST_SEPERATOR; } // if (list.IsNullOrEmpty()) { return result; } // var items = list.Split(separator.Value); items.ToList().ForEach(i => { // if (!i.IsNullOrEmpty() && i.IsGuid() && !i.IsDefaultGuid()) { // var gID = new Guid(i); result.Add(gID); } }); // return result; } /// /// Convert a List to List String ... /// /// /// /// /// public static string ToListString( this IEnumerable source, char? separator = null ) { // if (!separator.HasValue) { separator = CommonConstants.DEFAULT_LIST_SEPERATOR; } // if (!source.HasChild()) { return string.Empty; } // string result = String.Join( separator .ToString(), source ); // return result; } /// /// get default value of a Type /// /// /// /// public static T Default(this T source) where T : class { return default(T); } /// /// Check if an object is Null or Default Value /// /// /// /// public static bool IsNullOrDefault(this T source) where T : class { return Equals(source, default(T)); } /// /// convert a timestamp to ISO String representation ... /// /// /// public static string ISODateString(this long timestamp) { // var time = timestamp.FromTimestamp(); var result = time.ToString("o"); // return result; } /// /// Converts a DateTime to Unix Like Long ... /// /// /// public static long ToTimestamp( this DateTime source ) { return new DateTimeOffset(source) .ToUnixTimeMilliseconds(); } /// /// convert timestamp to DateTime ... /// /// /// public static DateTime FromTimestamp(this long timestamp) { // var result = DateTimeOffset.FromUnixTimeMilliseconds(timestamp); return result.DateTime; } public static DateTime FromTimestamp(this string source) { // var timestamp = Int64.Parse(source); var time = timestamp.FromTimestamp(); return time; } /// /// Check a Date Time is Expired or not /// /// /// public static bool IsExPired(this DateTime source) { // if (source.IsNull()) { return true; } // var currentDate = DateTime.UtcNow; var isExpired = currentDate >= source; // return isExpired; } public static bool IsExpired(this long source) { var time = source.FromTimestamp(); return time.IsExPired(); } public static bool IsExpired(this string source) { // var time = DateTime.Parse(source); return time.IsExPired(); } /// /// Check Specified Time is Expired or not ... /// /// /// /// public static bool IsExpiredTTL( this DateTime source, int ttlSeconds ) { // var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var result = now < new DateTimeOffset(source) .ToUnixTimeSeconds() + ttlSeconds; // return result; } /// /// Determines a File Type is Image Kind or not /// /// /// public static bool IsImageKind(this XFileType source) { // var imageKind = new Collection() { XFileType.Image, XFileType.CoverImage, XFileType.ProfileImasge }; // return imageKind.Contains(source); } /// /// Encode String as Url /// /// /// public static string ToUrlEncoded(this string source) { return HttpUtility.UrlEncode(source); } /// /// Decode Url String /// /// /// public static string ToUrlDecoded(this string source) { return HttpUtility.UrlDecode(source); } /// /// Convert an Object to string for use in HttpParams /// /// /// /// public static string ToHttpParamString(this object value, CultureInfo cultureInfo) { // if (value is Enum) { // string name = Enum.GetName(value.GetType(), value); if (name != null) { // var field = IntrospectionExtensions .GetTypeInfo(value.GetType()) .GetDeclaredField(name); // if (field != null) { // var attribute = CustomAttributeExtensions .GetCustomAttribute(field, typeof(EnumMemberAttribute)) as EnumMemberAttribute; // if (attribute != null) { return attribute.Value != null ? attribute.Value : name; } } } } else if (value is bool) { return System.Convert.ToString(value, cultureInfo).ToLowerInvariant(); } else if (value is byte[]) { return System.Convert.ToBase64String((byte[])value); } else if (value != null && value.GetType().IsArray) { // var array = Enumerable.OfType((Array)value); return string.Join(",", Enumerable .Select( array, o => o.ToHttpParamString(cultureInfo))); } // return System.Convert.ToString(value, cultureInfo); } /// /// ReShape an Object as HttpParam String /// /// /// public static string AsHttpParamString(this object value) { return System.Uri .EscapeDataString(value .ToHttpParamString(CultureInfo.InvariantCulture)); } /// /// Calculating Date Difference Provider String /// and Generate Date based on UTC Time in Milliseconds like unix Date ... /// /// /// public static long GenerateDateTimeOffset(this string offsetProvider) { // if (offsetProvider.IsNullOrEmpty()) { return 0; } // var mExpireValue = 0; var mExpireValueStr = offsetProvider.GetDigits(); var mExpireUnit = offsetProvider.Replace(mExpireValueStr, ""); if (mExpireValueStr.IsNullOrEmpty() || mExpireUnit.IsNullOrEmpty()) { return 0; } // var isParsed = int.TryParse(mExpireValueStr, out mExpireValue); if (!isParsed) { return 0; } // DateTime? date = null; switch (mExpireUnit) { case "d": date = DateTime.UtcNow.AddDays(mExpireValue); break; case "h": date = DateTime.UtcNow.AddHours(mExpireValue); break; case "m": date = DateTime.UtcNow.AddMinutes(mExpireValue); break; case "s": date = DateTime.UtcNow.AddSeconds(mExpireValue); break; case "ms": default: date = DateTime.UtcNow.AddMilliseconds(mExpireValue); break; } // var result = !date.HasValue ? 0 : new DateTimeOffset(date.Value) .ToUnixTimeMilliseconds(); // return result; } /// /// Extract RateLimit Rule based on given Path ... /// /// /// /// public static XRateLimitRule GetMatchingRule( this XRateLimitConfiguration source, string path ) { // if (!source.Enabled) { return null; } // var normalizedPath = path.IsNullOrEmpty() ? "/" : path.ToNormalString(); // var rule = source.Rules.IsNull() ? null : source.Rules .Where(r => !r.IsNull() && r.Enabled && !r.PathPrefix.IsNullOrEmpty() && normalizedPath.StartsWith(r.PathPrefix.ToNormalString())) .OrderByDescending(r => r.PathPrefix.Length) .FirstOrDefault(); // if (!rule.IsNull()) { return rule; } // if (source.ApplyToAllRoutes) { // return new XRateLimitRule { Enabled = true, Name = "Default", PathPrefix = "/", Limit = source.DefaultLimit, KeyMode = source.DefaultKeyMode, PeriodSeconds = source.DefaultPeriodSeconds, }; } // return null; } // #region Int Id Extensions ... public static bool IsValidIntId(this int source) { return source > 0; } public static void ValidateIntId(this int source) { // if (!source.IsValidIntId()) { XException.InvalidArgs.Throw(); } } #endregion // #region Dictionary Extensions ... /// /// Converts to Meta Data Representation ... /// /// /// public static Dictionary AsMetadat(this string source) { // // Validate ... if (source.IsNullOrEmpty()) { return []; } // // JSON is expected to be like: [0.12, 0.34, ...] ... var result = source.FromJSON>(); if (!result.HasChild()) { result = []; } // return result; } /// /// Safe Metadata Reader ... /// /// /// /// public static string GetMetadata( this IDictionary source, string key ) { // var result = string.Empty; // if (!source.IsNullOrDefault() && source.TryGetValue(key, out result)) { return result; } // return result; } #endregion // #region StringExtensions for Identity Server ... public static string EnsureTrailingSlash(this string input) { if (!input.EndsWith("/")) { return input + "/"; } return input; } public static bool IsMissing(this string value) { return string.IsNullOrWhiteSpace(value); } public static bool IsPresent(this string value) { return !string.IsNullOrWhiteSpace(value); } public static string Sha256(this string input) { if (input.IsMissing()) return string.Empty; using (var sha = SHA256.Create()) { var bytes = Encoding.UTF8.GetBytes(input); var hash = sha.ComputeHash(bytes); return Convert.ToBase64String(hash); } } /// /// Apply Templates on provided String ... /// /// /// /// public static string ApplyTemplates( this string source, IDictionary templates = null ) { // // Validate ... if (source.IsNullOrEmpty() || !templates.HasChild()) { return source; } // var existsTemplates = templates.Where( x => source.Contains(x.Key) ); var result = source; foreach (var template in existsTemplates) { result = result.Replace(template.Key, template.Value); } // return result; } #endregion // #region Private ... private static void FindTokens(JToken containerToken, string name, List matches) { if (containerToken.Type == JTokenType.Object) { foreach (JProperty child in containerToken.Children()) { if (child.Name == name) { matches.Add(child.Value); } FindTokens(child.Value, name, matches); } } else if (containerToken.Type == JTokenType.Array) { foreach (JToken child in containerToken.Children()) { FindTokens(child, name, matches); } } } #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\DIExtensions.cs using System; using System.IO; using System.Linq; using xCommons.Filters; using xCommons.Constants; using xCommons.Providers; using xCommons.Interfaces; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc; using Microsoft.OpenApi.Models; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Swashbuckle.AspNetCore.SwaggerUI; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using xExceptions.Constants; namespace xCommons.Extensions { public static partial class DIExtensions { /// /// Inject Specific Registered Service from IServiceCollection /// /// /// /// public static T GetRegisteredService(this IServiceCollection source) { // var serviceProvider = source.BuildServiceProvider(); return serviceProvider.GetService(); } /// /// Register App Configuration as a Service /// /// /// /// public static void AddXAppConfiguration( this IServiceCollection services, IConfiguration configuration, string environment = null ) { // var appConfiguration = configuration.GetXAppConfiguration(); appConfiguration.Environment = environment; // services.AddSingleton(appConfiguration); } /// /// Retrieve Rate Limit Configurations and Register it ... /// /// /// public static void AddXRateLimitConfiguration( this IServiceCollection source, IConfiguration configuration ) { // var config = configuration.GetXRateLimitConfiguration(); source.AddXRateLimitConfiguration(config); } /// /// Register Rate Limit Configuration ... /// /// /// public static void AddXRateLimitConfiguration( this IServiceCollection source, XRateLimitConfiguration configuration ) { // if (source.IsNull()) { XException.InvalidConfiguration.Throw(); } // source.AddSingleton(configuration); } /// /// Add Environment name to XAppConfiguration ... /// /// /// public static void AddEnvironmentToXAppConfiguration( this IApplicationBuilder app, string environmentName ) { // // Setting Environment in App Confiuration ... using (var scope = app.ApplicationServices.CreateScope()) { // // Inject AppConfiguration ... var appConfiguration = scope.ServiceProvider .GetRequiredService(); if (!appConfiguration.IsNull()) { appConfiguration.Environment = environmentName; } } } /// /// Retrieve and Register File Type Detector Configuration ... /// /// /// public static void AddXFileTypeDetectorConfiguration( this IServiceCollection source, IConfiguration configuration ) { // var config = configuration.GetXFileTypeDetectorConfiguration(); source.AddXFileTypeDetectorConfiguration(config); } /// /// Register File Type Detector Configuration ... /// /// /// public static void AddXFileTypeDetectorConfiguration( this IServiceCollection source, XFileTypeDetectorConfiguration configuration ) { // if (configuration.IsNull()) { configuration = new(); } // source.AddSingleton(configuration); } /// /// Search Assemblies, Extract XML Comments and /// Integrate them inside swagger gen documents ... /// /// public static void IncludeAssembliesXMLComments(this SwaggerGenOptions source) { // // Extract all Exists .xml files ... var basePath = AppContext.BaseDirectory; var xmlFiles = Directory.GetFiles(basePath, "*.xml", SearchOption.TopDirectoryOnly); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // // Loop through Detected XML Files ... foreach (var xmlFile in xmlFiles) { // try { // // Retrieve file name for Assembly Checking ... var assemblyName = Path.GetFileNameWithoutExtension(xmlFile); // // Try to retrieve Assembly ... var assembly = assemblies .FirstOrDefault(a => a.GetName().Name == assemblyName); if (!assembly.IsNullOrDefault() || File.Exists(Path.Combine(basePath, $"{assemblyName}.dll")) ) { // // Includes Selected XML Comments ... source.IncludeXmlComments(xmlFile); } } catch (Exception ex) { Console.WriteLine($"Warning: Could not include XML comments from {xmlFile}. Error: {ex.Message}"); } } } /// /// Add Required OperationFilters and Authorization Fields to Swagger Options /// /// /// /// /// /// /// public static void AddXSwaggerGenOptions( this SwaggerGenOptions source, string xmlFilePath = null, bool addRequiredXPoweredFilter = true, bool addXTokenAuthorization = true, bool addXApiKeyAuthorization = true, bool addDefaultValueFilter = true ) { // if (source.IsNull()) { source = new SwaggerGenOptions(); } // // Add Xml File Path ... if (!xmlFilePath.IsNullOrEmpty()) { source.IncludeXmlComments(xmlFilePath); } // // Include all XML Documents ... source.IncludeAssembliesXMLComments(); // // Handle RequireXPowered Filter ... if (addRequiredXPoweredFilter) { source.OperationFilter(); } // // Add Default Values Filter ... if (addDefaultValueFilter) { source.OperationFilter(); } // // Handle XToken Authorizations ... if (addXTokenAuthorization) { // #region Bearer AccessToken ... // source.AddSecurityDefinition(nameof(XAuthorization.AccessToken), new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Bearer token", Type = SecuritySchemeType.ApiKey, Name = XAuthorization.Header }); // source.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = nameof (XAuthorization.AccessToken), Type = ReferenceType.SecurityScheme } }, Array.Empty () } }); #endregion // #region RefreshToken ... // source.AddSecurityDefinition(nameof(XAuthorization.RefreshToken), new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Refresh Token", Type = SecuritySchemeType.ApiKey, Name = XAuthorization.RefreshToken }); // source.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = nameof(XAuthorization.RefreshToken), Type = ReferenceType.SecurityScheme } }, Array.Empty () } }); #endregion // #region ExpiresAt ... // source.AddSecurityDefinition(nameof(XAuthorization.ExpiresAt), new OpenApiSecurityScheme { Description = "Expires at", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Name = XAuthorization.ExpiresAt }); // source.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = nameof (XAuthorization.ExpiresAt), Type = ReferenceType.SecurityScheme } }, Array.Empty () } }); #endregion } // // Handle XApiKey Authorization ... if (addXApiKeyAuthorization) { // source.AddSecurityDefinition(nameof(XAuthorization.XApiKey), new OpenApiSecurityScheme { In = ParameterLocation.Header, Name = XAuthorization.XApiKey, Type = SecuritySchemeType.ApiKey, Description = "Api Key for Authentication ...", }); // source.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = nameof (XAuthorization.XApiKey), Type = ReferenceType.SecurityScheme } }, Array.Empty () } }); } } /// /// Register Swagger /// /// /// /// /// /// /// /// /// public static void AddXSwagger( this IServiceCollection source, IConfiguration configuration, SwaggerGenOptions settings = null, string xmlFilePath = null, bool addRequiredXPoweredFilter = true, bool addXTokenAuthorization = true, bool addXApiKeyAuthorization = true, bool addDefaultValueFilter = true ) { // var xSwaggerConfig = configuration.GetXSwaggerConfiguration(); if (xSwaggerConfig.IsNull()) { xSwaggerConfig = new XSwaggerConfiguration(); } // source.AddSingleton(xSwaggerConfig); // #region Prepare SwaggerGenOptions ... if (settings.IsNull()) { settings = new SwaggerGenOptions(); } settings.AddXSwaggerGenOptions( xmlFilePath: xmlFilePath, addDefaultValueFilter: addDefaultValueFilter, addXTokenAuthorization: addXTokenAuthorization, addXApiKeyAuthorization: addXApiKeyAuthorization, addRequiredXPoweredFilter: addRequiredXPoweredFilter ); #endregion // #region Prepare Swagger Doc ... // // Api Document Section ... var apiDoc = new OpenApiInfo { Title = xSwaggerConfig.Title, Version = xSwaggerConfig.Version, Description = xSwaggerConfig.Description, }; // // Api Document TermsOfUse URL ... if (!xSwaggerConfig.TermsOfServiceUrl.IsNullOrEmpty()) { apiDoc.TermsOfService = new Uri(xSwaggerConfig.TermsOfServiceUrl); } // // Contact Section ... if (!xSwaggerConfig.Contact.IsNull()) { // var apiContact = new OpenApiContact { Name = xSwaggerConfig.Contact.Name, Email = xSwaggerConfig.Contact.Email }; // // Contact URL ... if (!xSwaggerConfig.Contact.Url.IsNullOrEmpty()) { apiContact.Url = new Uri(xSwaggerConfig.Contact.Url); } // apiDoc.Contact = apiContact; } // // License Section ... if (!xSwaggerConfig.License.IsNull()) { // var apiLicense = new OpenApiLicense { Name = xSwaggerConfig.License.Name, }; // // License URL ... if (!xSwaggerConfig.License.Url.IsNullOrEmpty()) { apiLicense.Url = new Uri(xSwaggerConfig.License.Url); } // apiDoc.License = apiLicense; } #endregion // // Register Swagger ... source.AddSwaggerGen( opt => { // opt.UpdateData(settings); // opt.SwaggerDoc("v1", apiDoc); } ); // // Register Swagger Operation Filters ... } /// /// Use Sagger /// /// /// public static void UseXSwagger( this IApplicationBuilder source, SwaggerUIOptions options = null ) { // source.UseSwagger(); // if (options.IsNull()) { source.UseSwaggerUI(); } else { source.UseSwaggerUI(options: options); } } /// /// Add Cross Origin Resource Sharings /// /// /// public static void AddXCors( this IServiceCollection source, IEnumerable allowedOrigins ) { // if (!allowedOrigins.HasChild()) { // Console.WriteLine($"XCommons: there is no provided allowedOrigins, start app without any specific cors, this may be unsecure ..."); // source.AddCors(options => { options.AddPolicy(XPolicy.AllowedOrigins, builder => { builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .WithExposedHeaders("*"); }); }); // return; } // source.AddCors(options => { options.AddPolicy(XPolicy.AllowedOrigins, builder => { builder .WithOrigins(allowedOrigins.ToArray()) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .WithExposedHeaders("*"); }); }); } /// /// Register RateLimit Service ... /// /// public static void AddXRateLimit( this IServiceCollection source ) { // source.AddMemoryCache(); source.AddSingleton(); } /// /// Register RateLimit Service ... /// Configs Retrieved from AppSettings ... /// /// /// public static void AddXRateLimit( this IServiceCollection source, IConfiguration configuration ) { // var config = configuration.GetXRateLimitConfiguration(); source.AddXRateLimit(config); } /// /// Register RateLimit Service ... /// /// /// public static void AddXRateLimit( this IServiceCollection source, XRateLimitConfiguration configuration ) { // if (configuration.IsNull()) { XException.InvalidConfiguration.Throw(); } // source.AddXRateLimitConfiguration(configuration); source.AddXRateLimit(); } public static void AddXFileTypeDetector( this IServiceCollection source, IConfiguration configuration ) { // source.AddXFileTypeDetectorConfiguration(configuration); source.AddSingleton(); } /// /// Use X Registered Cross Origin Resource Sharings /// /// public static void UseXCors(this IApplicationBuilder sources) { // sources.UseCors(XPolicy.AllowedOrigins); } /// /// Register Api V1 Versioning ... /// /// public static void AddXApiV1Versioning(this IServiceCollection services) { // // Register Api Versioning ... services.AddApiVersioning(opt => { // // Set Default Api Version ... opt.DefaultApiVersion = new ApiVersion(1, 0); // // Set Routing to Default API Version, if Version unspecified ... opt.AssumeDefaultVersionWhenUnspecified = true; // // Report All Available Api Versions on Response ... opt.ReportApiVersions = true; }); } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\EnumExtensions.cs using System; using System.Collections.Generic; namespace xCommons.Extensions { public static partial class EnumExtensions { public static string GetKey (this Enum source) { return Enum.GetName (source.GetType (), source); } public static T GetValue (this string source) { return (T) Enum.Parse (typeof (T), source); } public static void Iterate (this IEnumerator source, Action action) { // while (source.MoveNext ()) { // var current = source.Current; action (current); } } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\ExceptionExtensions.cs using System; using xExceptions.Models; using xExceptions.Constants; namespace xCommons.Extensions { /// /// this is an extension pack for Exceptions /// public static partial class ExceptionExtensions { /// /// determines an string contains an XError content or not /// /// /// public static bool IsXError (this string source) { // if (source.IsNullOrEmpty ()) { return false; } // var xError = source.ToXError (); if (xError != null) { return true; } // // If Convert Proccess fails ... var normalString = source.ToNormalString (); // // Return result based on string values ... return normalString.Contains ("id") && normalString.Contains ("message"); } /// /// deserialize an string to to XError class instance /// /// /// public static XError ToXError (this string source) { // if (source.IsNullOrEmpty ()) { return null; } // try { // var err = source.FromJSON (); // // if err is null we have to manually get value if (err == null) { // var normalString = source.ToNormalString (); var parts = normalString.Split (','); if (parts.Length > 2) { return null; } // var idContainer = parts[0]; var messageContainer = parts[1]; } // return err; } catch { return null; } } public static XError ToXError (this XException source) { // var errorId = (int) source; var errorMessage = source.GetStringValue (); // return new XError { Id = errorId, Message = errorMessage }; } /// /// Convert an XError instance to an Exception /// /// /// public static Exception ToException (this XError source) { // var jsonStr = source.ToJSON (); return new Exception (jsonStr); } public static Exception ToException (this XException source) { return source .ToXError () .ToException (); } /// /// Convert an Exception to corresponding XError Object /// /// /// public static XError FromException (this Exception source) { // if (source == null || source.Message.IsNullOrEmpty ()) { return null; } // return source.Message.ToXError (); } /// /// Add Content to Contentable XException member and return XError Object /// /// /// /// public static XError AddContentToError (this XException exception, string value) { // var xError = exception.ToXError (); xError.Message = string.Format (xError.Message, value); // return xError; } /// /// Add Content to Contentable XException member and return Exception Object /// /// /// /// public static Exception AddContentToException (this XException exception, string value) { // var xError = exception.ToXError (); xError.Message = string.Format (xError.Message, value); // return xError.ToException (); } /// /// Throw Specific Exception ... /// /// /// public static void Throw ( this XException source, string content = null ) { // Exception exception = null; if (content.IsNullOrEmpty ()) { exception = source.ToException (); } else { exception = source.AddContentToException (content); } // throw exception; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\FilterExtensions.cs using System.Linq; using xCommons.Configurations; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Authorization; namespace xCommons.Extensions { public static partial class FilterExtensions { public static XAppConfiguration GetXAppConfiguration (this ActionExecutingContext source) { // var services = source.HttpContext.RequestServices; return (XAppConfiguration) services.GetService (typeof (XAppConfiguration)); } public static XAppConfiguration GetXAppConfiguration (this AuthorizationFilterContext source) { // var services = source.HttpContext.RequestServices; return (XAppConfiguration) services.GetService (typeof (XAppConfiguration)); } public static bool IsAnonymousAllowed (this AuthorizationFilterContext source) { // var result = source.Filters .Any (f => f.GetType () == typeof (AllowAnonymousFilter)) || source.ActionDescriptor.FilterDescriptors .Any (f => f.GetType () == typeof (AllowAnonymousFilter)) || source.ActionDescriptor.EndpointMetadata .Any (f => f.GetType () == typeof (AllowAnonymousAttribute)); // return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\IConfigurationExtensions.cs using System.Linq; using xCommons.Constants; using xCommons.Configurations; using System.Collections.Generic; using Microsoft.Extensions.Configuration; namespace xCommons.Extensions { public static partial class IConfigurationExtensions { /// /// Retrieve AppConfiguration from Configurations /// /// /// public static XAppConfiguration GetXAppConfiguration(this IConfiguration source) { // var xMessageResourceTitlesConfigSection = source .GetSection(ConfigurationNodeNames.MESSAGE_RESOURCE_TITLES_NODE); // var result = new XAppConfiguration { Name = source[nameof(XAppConfiguration.Name)], Version = source[nameof(XAppConfiguration.Version)], XPoweredValue = source[nameof(XAppConfiguration.XPoweredValue)], WelcomeMessage = source[nameof(XAppConfiguration.WelcomeMessage)], AllowedOrigins = source .GetSection(nameof(XAppConfiguration.AllowedOrigins)) .Get>(), DefaultLanguage = source[nameof(XAppConfiguration.DefaultLanguage)], MessageResourceTitles = xMessageResourceTitlesConfigSection .Get() }; // return result; } /// /// Retrieve Swagger Configurations /// /// /// public static XSwaggerConfiguration GetXSwaggerConfiguration(this IConfiguration source) { // var xSwaggerConfigSection = source .GetSection(ConfigurationNodeNames.SWAGGER_NODE); return xSwaggerConfigSection.Get(); } /// /// Retrieve RateLimit Configurations ... /// /// /// public static XRateLimitConfiguration GetXRateLimitConfiguration(this IConfiguration source) { // var section = source .GetSection(ConfigurationNodeNames.RATE_LIMIT_NODE); // var result = section.Get(); return result; } /// /// Retrieve File Type Detector Configuration ... /// /// /// public static XFileTypeDetectorConfiguration GetXFileTypeDetectorConfiguration(this IConfiguration source) { // var section = source .GetSection(ConfigurationNodeNames.FILE_TYPE_DETECTOR_NODE); // var result = section.Get(); if (result.IsNull()) { result = new(); } // return result; } /// /// Converts a ConfigurationSection to object Representation ... /// /// /// public static object ToObject(this IConfigurationSection section) { // // an Inner Function for Create Recursive Parsing ... object ConvertSection(IConfigurationSection sec) { // var children = sec .GetChildren() .ToList(); if (!children.Any()) { return sec.Value ?? string.Empty; } // // Detect Array Like Sections ... bool isArray = children.All(ch => int.TryParse(ch.Key, out _)); if (isArray) { // return children .OrderBy(c => int.Parse(c.Key)) .Select(ConvertSection) .ToList(); } // // Otherwise ... return children .ToDictionary( c => c.Key, c => ConvertSection(c) ); } // // Try to Parse using Inner Function ... var result = ConvertSection(section); // return result; } /// /// Converts a ConfigurationSection to Json Representation ... /// /// /// public static string ToJSON(this IConfigurationSection section) { // // Try to Parse using Inner Function ... var obj = section.ToObject(); // // Convert it to Json ... var result = obj.ToJSON(); // return result; } /// /// Get a Configuration Section as Object ... /// /// /// /// public static object GetSectionAsObject( this IConfiguration source, string section ) { // object result = null; // if (!section.IsNullOrEmpty()) { // var sec = source.GetSection(section); if (!sec.IsNull()) { result = sec.ToObject(); } } // return result; } /// /// Retrieve a Configuration Section as Json String ... /// /// /// /// public static string GetSectionAsJson( this IConfiguration source, string section ) { // var result = string.Empty; // // Retrieve Secion as Object ... var obj = source.GetSectionAsObject(section); if (!obj.IsNull()) { // // Converts Section Object to Json ... result = obj.ToJSON(); } // return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\IFormFileExtensions.cs using System; using System.IO; using System.Text; using UglyToad.PdfPig; using System.Threading; using xCommons.Extensions; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace xAiModels.Extensions { public static class IFormFileExtensions { /// /// Read a IFormFile Content as byte array ... /// /// /// /// public static async Task ReadAsBytes( this IFormFile source, CancellationToken cancellationToken = default ) { // // Create and use a Memory Stream ... using var stream = new MemoryStream(); // // Copy File Content to Stream ... await source.CopyToAsync( target: stream, cancellationToken: cancellationToken ); // // Read Stream Content as byte array ... var result = stream.ToArray(); // return result; } /// /// Read a File Content by it's Path as byte array ... /// /// /// /// /// /// public static async Task ReadAsBytes( this string filePath, int bufferSize = 81920, CancellationToken cancellationToken = default ) { // if (string.IsNullOrWhiteSpace(filePath)) { throw new Exception("Invalid Args ..."); } // // Create and use a Memory Stream ... using var memStream = new MemoryStream(); // using var stream = new FileStream( path: filePath, mode: FileMode.Open, access: FileAccess.Read, share: FileShare.ReadWrite ); // // Copy File Content to Stream ... await stream.CopyToAsync( destination: memStream, bufferSize: bufferSize, cancellationToken: cancellationToken ); // // Read Stream Content as byte array ... var result = memStream.ToArray(); // return result; } /// /// Read Text Content of Document ... /// /// /// /// public static async Task ReadContent( this IFormFile source, CancellationToken cancellationToken = default ) { // // Check if File PDF or not ... var isPDF = source.ContentType .ToNormalString() .Contains("pdf" .ToNormalString()); // var result = string.Empty; // var isValidFileType = isPDF; if (!isValidFileType) { return result; } // if (isPDF) { // // Reading File Content as Byte array ... var fileBytes = await source.ReadAsBytes(cancellationToken); // // Create a PDF Document ... using var stream = new MemoryStream(fileBytes); using var document = PdfDocument.Open(stream); // // Extract PDF Text ... var textBuilder = new StringBuilder(); foreach (var page in document.GetPages()) { textBuilder.Append(page.Text); } // result = textBuilder.ToString(); } // return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\ModelExtensions.cs using System; using System.Linq; using System.Reflection; using System.Linq.Expressions; using System.Collections.Generic; using System.Collections.ObjectModel; namespace xCommons.Extensions { public static partial class ModelExtensions { /// /// Retrieve a Binding Flag for Retrieve all Instance Members including /// Priate and Public ... /// /// public static BindingFlags GetDefaultBindingFlag() { return BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; } /// /// Update an Instance of a Typed Object with Data Provided by another Instance of Typed Object /// /// /// /// /// /// /// /// /// /// /// public static T UpdateData( this T source, D updateWith, ICollection propertyWhiteList = null, ICollection propertyBlackList = null, ICollection>> propertyValueProviders = null, bool updateWithNullOrEmptyValues = false, bool throwExceptionOnFails = false ) where T : class where D : class { // var hasWhiteList = propertyWhiteList.HasChild(); var hasBlackList = propertyBlackList.HasChild(); var hasValueProvider = propertyValueProviders.HasChild>>(); // var fullPropertyList = updateWith.GetType().GetProperties().Select(prop => prop.Name); var mustSetProps = (hasWhiteList ? propertyWhiteList : fullPropertyList); // if (hasBlackList) { mustSetProps = mustSetProps.Where(propName => !propertyBlackList.Contains(propName)); } // mustSetProps.ToList().ForEach(propName => { // try { // var sourceProp = source.GetType().GetProperty(propName); var sourceValue = sourceProp.GetValue(source); var sourceValueType = sourceValue.IsNull() ? null : sourceValue.GetType(); // var updateWithProp = updateWith.GetType().GetProperty(propName); var updateWithValue = updateWithProp.GetValue(updateWith); var updateWithValueType = updateWithValue.IsNull() ? null : updateWithValue.GetType(); // var valueProviderValue = hasValueProvider ? propertyValueProviders .FirstOrDefault(p => p.Key == propName).Value : null; var updateVal = !valueProviderValue.IsNull() ? valueProviderValue.Invoke(updateWith) : (updateWithValue.IsNull() && !updateWithNullOrEmptyValues) ? sourceValue : updateWithValue; var updateValType = updateVal.IsNull() ? null : updateVal.GetType(); // Type t = Nullable.GetUnderlyingType(sourceProp.PropertyType) ?? sourceProp.PropertyType; object safeValue = (updateVal == null) ? null : !updateValType.IsCollectionType() ? Convert.ChangeType(updateVal, t) : updateVal; // sourceProp.SetValue(source, safeValue); } catch (Exception ex) { // if (throwExceptionOnFails) { throw ex; } } }); // return source; } /// /// Check a Class is Contains a Property or not ... /// /// /// /// /// /// public static bool HasProperty( this T source, string property, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) where T : class { // var result = source .GetType() .GetProperties(bindingAttr) .Any(prop => prop.Name == property); ; // return result; } /// /// Check a Class is Contains a field or not ... /// /// /// /// /// /// public static bool HasField( this T source, string field, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) where T : class { // var result = source .GetType() .GetFields(bindingAttr) .Any(fld => fld.Name == field); // return result; } /// /// Check a Class is Contains a Method or not ... /// /// /// /// /// /// public static bool HasMethod( this T source, string method, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) where T : class { // var result = source .GetType() .GetMethods(bindingAttr) .Any(mthd => mthd.Name == method); // return result; } /// /// Retrieve a Class Properties Names ... /// /// /// /// /// public static string[] GetPropertiesNames( this T source, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) { // var result = source .GetType() .GetProperties(bindingAttr) .Select(p => p.Name) .ToArray(); // return result; } /// /// Retrieve a Class Fields Names ... /// /// /// /// /// public static string[] GetFieldsNames( this T source, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) { // var result = source .GetType() .GetFields(bindingAttr) .Select(p => p.Name) .ToArray(); // return result; } /// /// Retrieve a Class Methods Names ... /// /// /// /// /// public static string[] GetMethodsNames( this T source, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) { // var result = source .GetType() .GetMethods(bindingAttr) .Select(p => p.Name) .ToArray(); // return result; } /// /// Retrieve a Class Members Names ... /// /// /// /// /// public static string[] GetMembersNames( this T source, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) { // var result = source .GetType() .GetMembers(bindingAttr) .Select(p => p.Name) .ToArray(); // return result; } /// /// Get a Class Property Value using Generic Concept ... /// /// /// /// /// /// /// public static TProp GetProperty( this T source, string property, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) where T : class { // TProp result = default; // // Check if T Has Property ... if (source.HasProperty(property)) { // // Access Property ... var prop = source .GetType() .GetProperty( property, bindingAttr ); // // Retrieve Property Value as Object ... var propVal = prop.GetValue(source); // result = (TProp)propVal; } // return result; } /// /// Get a Class Field Value using Generic Concept ... /// /// /// /// /// /// /// public static TField GetField( this T source, string field, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) where T : class { // TField result = default; // if (source.HasField(field)) { // var fld = source .GetType() .GetField( field, bindingAttr ); // var fieldVal = fld.GetValue(source); result = (TField)fieldVal; } // return result; } /// /// Set a Class Property Value using Generic Concept ... /// /// /// /// /// /// /// /// public static bool SetProperty( this T source, string property, TProp value, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) where T : class { // // Check T Has Property ... var result = source.HasProperty(property); if (!result) { return result; } // // Access Property ... var prop = source .GetType() .GetProperty( property, bindingAttr ); // // Set Property ... try { // result = true; prop.SetValue(source, value); } catch { result = false; } // return result; } /// /// Set a Class Field Value using Generic Concept ... /// /// /// /// /// /// /// /// public static bool SetField( this T source, string field, TField value, BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ) where T : class { // // Check T Has Field ... var result = source.HasField(field); if (!result) { return result; } // // Access Field ... var fld = source .GetType() .GetField( field, bindingAttr ); // // Set Value ... try { // result = true; fld.SetValue(source, value); } catch { result = false; } // return result; } /// /// Check two Instance of Typed Object Values are Same or not /// /// /// /// /// /// /// /// /// /// /// public static bool IsSameContent( this T source, D dest, ICollection propertyWhiteList = null, ICollection propertyBlackList = null, ICollection>> propertyValueCheckers = null, bool throwExceptionOnFails = false ) where T : class where D : class { // var hasWhiteList = propertyWhiteList.HasChild(); var hasBlackList = propertyBlackList.HasChild(); var hasCheckerProvider = propertyValueCheckers.HasChild>>(); // var fullPropertyList = dest.GetType().GetProperties().Select(prop => prop.Name); var mustCheckProps = (hasWhiteList ? propertyWhiteList : fullPropertyList); if (hasBlackList) { mustCheckProps = mustCheckProps.Where(propName => !propertyBlackList.Contains(propName)); } // var result = true; mustCheckProps.ToList().ForEach(propName => { // try { // var sourceProp = source.GetType().GetProperty(propName); var destProp = dest.GetType().GetProperty(propName); // // Check Types ... var isSameType = true; // // Check var isSameValue = false; var mustDoCustomCheck = hasCheckerProvider && propertyValueCheckers.Any(p => p.Key == propName); if (mustDoCustomCheck) { // // Check Values ... var valueChecker = propertyValueCheckers.FirstOrDefault(p => p.Key == propName).Value; isSameValue = valueChecker.Invoke(source, dest); } else { // // // isSameType = (sourceProp.PropertyType == destProp.PropertyType && // sourceProp.ReflectedType == destProp.ReflectedType); // // Check Values ... isSameValue = Equals(sourceProp.GetValue(source), destProp.GetValue(dest)); } // if (!isSameType || !isSameValue) { result = false; } } catch (Exception ex) { // if (throwExceptionOnFails) { throw ex; } } }); // return result; } /// /// Check specific type is Collection Type or not /// /// /// public static bool IsCollectionType(this Type source) { // if (source.IsNull() || !source.IsGenericType) { return false; } // var genericTypeDefinition = source.GetGenericTypeDefinition(); var result = genericTypeDefinition == typeof(List<>) || genericTypeDefinition == typeof(HashSet<>) || genericTypeDefinition == typeof(Collection<>) || genericTypeDefinition == typeof(ICollection<>) || genericTypeDefinition == typeof(IEnumerable<>); // return result; } /// /// Retrieve a Property Value in Generic /// /// /// /// public static string GetPropValues(this T item) where T : class { // var props = item.GetType().GetProperties(); var vals = props.Select(p => p.GetValue(item)); // return vals.ToJSON(); } /// /// Check a Property Value Contains specific value /// /// /// /// /// public static bool PropValuesContains(this T item, string value) where T : class { // return item.GetPropValues() .ToNormalString() .Contains(value .ToNormalString()); } /// /// Generate Default Column Map /// /// /// /// public static IDictionary>> GetDefaultColumnsMap(this T item) where T : class { // if (item.IsNull()) { return null; } // var result = new Dictionary>>(); var props = item.GetType().GetProperties(); // foreach (var prop in props) { result.Add(prop.Name, t => t.GetType().GetProperty(prop.Name).GetValue(t, null)); } // return result; } /// /// Generate Default Column Map /// /// /// /// public static IDictionary GetPropValuesDictionary(this T item) where T : class { // if (item.IsNull()) { return null; } // var result = new Dictionary(); var props = item.GetType().GetProperties(); // foreach (var prop in props) { result.Add(prop.Name, prop.GetValue(item).ToJSON()); } // return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\ServiceProviderExtensions.cs using System; using xCommons.Helpers; using System.Collections; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace xCommons.Extensions { public static class ServiceProviderExtensions { /// /// Get all registered /// /// /// public static Dictionary GetAllServiceDescriptors (this IServiceProvider provider) { // if (provider is ServiceProvider serviceProvider) { // var result = new Dictionary (); // var engine = serviceProvider.GetFieldValue ("_engine"); var callSiteFactory = engine.GetPropertyValue ("CallSiteFactory"); var descriptorLookup = callSiteFactory.GetFieldValue ("_descriptorLookup"); if (descriptorLookup is IDictionary dictionary) { foreach (DictionaryEntry entry in dictionary) { result.Add ((Type) entry.Key, (ServiceDescriptor) entry.Value.GetPropertyValue ("Last")); } } // return result; } // throw new NotSupportedException ($"Type '{provider.GetType()}' is not supported!"); } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\XHttpContextExtensions.cs using System.IO; using xCommons.Constants; using Microsoft.AspNetCore.Http; namespace xCommons.Extensions { public static partial class XHttpContextExtensions { /// /// Convert IFormFile to Bytes Array /// /// /// public static byte[] ToByteArray(this IFormFile source) { // byte[] data; using (var br = new BinaryReader(source.OpenReadStream())) { data = br.ReadBytes((int)source.OpenReadStream().Length); } // return data; } /// /// Extract Rate Limit Key ... /// /// /// /// public static string GetXRateLimitKey( this HttpContext source, XRateLimitKeyMode keyMode ) { // if (source.IsNull()) { return "unknown"; } // switch (keyMode) { // case XRateLimitKeyMode.ClientId: { // var clientId = source.Request.Headers[XRateLimitConstants.ClientIdHeader].ToString(); return clientId.IsNullOrEmpty() ? "anonymous" : clientId.ToNormalString(); } // case XRateLimitKeyMode.User: { // var userId = source.User?.FindFirst(XCustomClaims.UserId)?.Value; if (userId.IsNullOrEmpty()) { userId = source.User?.Identity?.Name; } // return userId.IsNullOrEmpty() ? "anonymous" : userId.ToNormalString(); } // case XRateLimitKeyMode.Route: { // return string.Format( "{0}:{1}", source.Request.Method, source.Request.Path ).ToNormalString(); } // case XRateLimitKeyMode.Custom: { return "custom"; } // case XRateLimitKeyMode.Ip: default: { // return source.Connection.RemoteIpAddress .IsNull() ? "unknown" : source.Connection.RemoteIpAddress .ToString() .ToNormalString(); } } } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\XHttpExtensions.cs using System; using System.Net; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting.Server.Features; namespace xCommons.Extensions { /// /// All Extensions around Http ... /// public static class XHttpExtensions { /// /// Write Response as JSON ... /// /// /// /// /// public static async Task WriteResponseAsJsonAsync( this HttpContext source, HttpStatusCode status, object data ) { // await source.Response.WriteJsonAsync( data: data, status: status ); } /// /// Write JSON ... /// /// /// /// /// public static async Task WriteJsonAsync( this HttpResponse source, HttpStatusCode status, object data ) { // source.StatusCode = (int)status; source.ContentType = "application/json; charset=utf-8"; var json = data.ToJSON(); // await source.WriteAsync(json); } /// /// Copy Request Headers ... /// /// /// /// public static void CopyRequestHeaders( this HttpContext source, HttpContent dest, string[] exceptions = null ) { // if (dest.IsNull() || source.IsNull()) { return; } // source.Request.CopyHeaders( dest: dest, exceptions: exceptions ); } /// /// Copy Request Headers ... /// /// /// /// public static void CopyRequestHeaders( this HttpContext source, HttpRequestMessage dest, string[] exceptions = null ) { // if (dest.IsNull() || source.IsNull()) { return; } // source.Request.CopyHeaders( dest: dest, exceptions: exceptions ); } /// /// Copy Headers ... /// /// /// /// public static void CopyHeaders( this HttpRequest source, HttpContent dest, string[] exceptions = null ) { // if (dest.IsNull() || source.IsNull()) { return; } // foreach (var header in source.Headers) { // if ( exceptions.HasChild() && exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)) ) { continue; } // dest.Headers.TryAddWithoutValidation( name: header.Key, values: [.. header.Value] ); } } /// /// Copy Headers ... /// /// /// /// public static void CopyHeaders( this HttpRequest source, HttpRequestMessage dest, string[] exceptions = null ) { // if (dest.IsNull() || source.IsNull()) { return; } // foreach (var header in source.Headers) { // if ( exceptions.HasChild() && exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)) ) { continue; } // dest.Headers.TryAddWithoutValidation( name: header.Key, values: [.. header.Value] ); } } /// /// Copy Headers ... /// /// /// /// public static void CopyHeaders( this HttpResponseMessage source, HttpContext context, string[] exceptions = null ) { // // Validate ... if (source.IsNull() || context.IsNull()) { return; } // source.CopyHeaders( exceptions: exceptions, response: context.Response ); } /// /// Copy Headers ... /// /// /// /// public static void CopyHeaders( this HttpResponseMessage source, HttpResponse response, string[] exceptions = null ) { // // Validate ... if (source.IsNull() || response.IsNull()) { return; } // foreach (var header in source.Headers) { // if ( exceptions.HasChild() && exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)) ) { continue; } // response.Headers[header.Key] = header.Value.ToArray(); } // foreach (var header in source.Content.Headers) { // if ( exceptions.HasChild() && exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)) ) { continue; } // response.Headers[header.Key] = header.Value.ToArray(); } } /// /// Extract Application Urls ... /// /// /// public static ICollection GetApplicationUrls( this IServiceProvider services ) { // var server = services.GetService(); var addresses = server?.Features.Get(); var result = addresses?.Addresses ?? Array.Empty(); // return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Extensions\XMiddlewareExtensions.cs using xCommons.Middlewares; using Microsoft.AspNetCore.Builder; namespace xCommons.Extensions { public static partial class XMiddlewareExtensions { /// /// Use XRateLimit Middleware ... /// /// /// public static IApplicationBuilder UseXRateLimit( this IApplicationBuilder source ) { return source.UseMiddleware(); } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Filters\RequireXPoweredOperationFilter.cs using xCommons.Constants; using xCommons.Extensions; using Microsoft.OpenApi.Any; using xCommons.Configurations; using Microsoft.OpenApi.Models; using System.Collections.Generic; using Swashbuckle.AspNetCore.SwaggerGen; namespace xCommons.Filters { /// /// RequireXPowered for NGSwag /// public partial class RequireXPoweredOperationFilter : IOperationFilter { private readonly XAppConfiguration config; public RequireXPoweredOperationFilter (XAppConfiguration config) { this.config = config; } public void Apply (OpenApiOperation operation, OperationFilterContext context) { // if (operation.Parameters.IsNull ()) { operation.Parameters = new List (); } // operation.Parameters.Add (new OpenApiParameter { In = ParameterLocation.Header, Name = XAuthorization.XPoweredBy, Description = "a Basic Authorization Filter", Required = false, Schema = new OpenApiSchema { Type = "String", Default = new OpenApiString (config.XPoweredValue) } }); } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Filters\SwaggerDefaultValuesOperationFilter.cs using System.Linq; using xCommons.Extensions; using Microsoft.OpenApi.Any; using xCommons.Configurations; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; namespace xCommons.Filters { public class SwaggerDefaultValuesOperationFilter : IOperationFilter { private readonly XSwaggerConfiguration config; public SwaggerDefaultValuesOperationFilter( XSwaggerConfiguration config ) { this.config = config; } public void Apply( OpenApiOperation operation, OperationFilterContext context ) { // // Validate Configuration ... if ( !config.IsNull() && !config.DefaultValues.IsNull() && config.DefaultValues.HasChild() ) { // foreach (var prv in config.DefaultValues) { // // Detect Parameter ... var swaggerParam = operation.Parameters.FirstOrDefault(p => p.Name == prv.Key); if (!swaggerParam.IsNull()) { swaggerParam.Schema.Default = new OpenApiString(prv.Value); } } } } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Helpers\ObjectHelper.cs using System; using System.Linq; using System.Collections.Generic; namespace xCommons.Helpers { public partial class ObjectHelper { /// /// Convert Enum Keys to Array /// /// /// public static Array GetKeys () { // ValidateEnumbType (); var type = typeof (T); // var result = Enum.GetNames (type); // return result; } /// /// Convert EnumValues to Array /// /// /// public static Array GetValues () { // ValidateEnumbType (); var type = typeof (T); // var result = Enum.GetValues (type); // return result; } /// /// Convert an Enum to IEnumerable of it's Childs /// /// /// public static IEnumerable ToEnumerableValues () { // ValidateEnumbType (); var type = typeof (T); // var result = GetValues () .Cast (); // return result; } /// /// Retrieve Keys of an Enumerable /// /// /// public static IEnumerable ToEnumerableKeys () { // ValidateEnumbType (); var type = typeof (T); // var result = GetKeys () .Cast (); // return result; } public static IDictionary ToDictionary () { // ValidateEnumbType (); // var result = new Dictionary (); foreach (var name in Enum.GetNames (typeof (T))) { result.Add (name, (int) Enum.Parse (typeof (T), name)); } // return result; } private static void ValidateEnumbType () { // var type = typeof (T); if (!type.IsEnum) { throw new InvalidCastException (); } } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Helpers\XFileHelper.cs using System; using System.Linq; using xCommons.Models; using System.Reflection; using xCommons.Constants; using xCommons.Extensions; using xExceptions.Attributes; using System.Collections.Generic; namespace xCommons.Helpers { /// /// File Helper ... /// public static class XFileHelper { /// /// Cache Data ... /// private static readonly Lazy> _cache = new(Build, isThreadSafe: true); /// /// Retrieve List ... /// /// public static IReadOnlyList GetAll() => _cache.Value; /// /// Normalize File Extension ... /// /// /// public static string NormalizeExtension(string extension) { // var result = extension; // if (result.IsNullOrEmpty()) { return result; } // result = result.Trim(); if (result.IsNullOrEmpty()) { return result; } // if (result == ".") { // result = string.Empty; return result; } // result = result.StartsWith(".") ? result.ToLowerInvariant() : "." + result.ToLowerInvariant(); // return result; } /// /// Check a File Extension is Supported or not ... /// /// /// public static bool IsSupported(string extension) { // var info = GetByExtension(extension); var result = !info.IsNull(); // return result; } /// /// Detect File Info based On Extension ... /// /// /// public static XFileTypeInfo GetByExtension(string extension) { // XFileTypeInfo result = null; // // Validate ... if (extension.IsNullOrEmpty()) { return result; } // var normalized = NormalizeExtension(extension); // // Detect Item ... result = GetAll() .FirstOrDefault(x => x.Extension.Equals( normalized, StringComparison.OrdinalIgnoreCase)); // return result; } /// /// Detect File Info based on Mime Type ... /// /// /// public static XFileTypeInfo GetByMimeType(string mimeType) { // XFileTypeInfo result = null; // // Validate ... if (mimeType.IsNullOrEmpty()) { return result; } // result = GetAll() .FirstOrDefault(x => x.MimeType.Equals( mimeType.Trim(), StringComparison.OrdinalIgnoreCase)); // return result; } /// /// Detect File Info based on Enum Member Name ... /// /// /// public static XFileTypeInfo GetByName(string name) { // XFileTypeInfo result = null; // // Validate ... if (name.IsNullOrEmpty()) { return result; } // result = GetAll() .FirstOrDefault(x => x.Name.Equals( name.Trim(), StringComparison.OrdinalIgnoreCase)); // return result; } /// /// Detect File Info based on Enum Member Value ... /// /// /// public static XFileTypeInfo GetByValue(int value) { // var result = GetAll() .FirstOrDefault(x => x.Value == value); // return result; } /// /// Try Get File Info By Extension ... /// /// /// /// public static bool TryGetByExtension( string extension, out XFileTypeInfo result ) { result = GetByExtension(extension); return result != null; } /// /// Try Get File Info By Mime Type ... /// /// /// /// public static bool TryGetByMimeType( string mimeType, out XFileTypeInfo result ) { result = GetByMimeType(mimeType); return result != null; } /// /// Get Mime Type based on Extension ... /// /// /// public static string GetMimeType(string extension) { // var result = string.Empty; var info = GetByExtension(extension); if (!info.IsNull()) { result = info.MimeType; } // return result; } /// /// Get Extension based on Mime Type ... /// /// /// public static string GetExtension(string mimeType) { // var result = string.Empty; var info = GetByMimeType(mimeType); if (!info.IsNull()) { result = info.Extension; } // return result; } /// /// Get File Category based on Value ... /// /// /// public static XFileCategory? GetCategory(int value) { // if (value >= 100 && value < 200) return XFileCategory.Document; if (value >= 200 && value < 300) return XFileCategory.Archive; if (value >= 300 && value < 400) return XFileCategory.Internal; if (value >= 400 && value < 500) return XFileCategory.Video; if (value >= 500 && value < 600) return XFileCategory.Audio; if (value >= 600 && value < 700) return XFileCategory.Image; // return null; } /// /// Get File Category based on Extension ... /// /// /// public static XFileCategory? GetCategory(string extension) { // var info = GetByExtension(extension); var result = !info.IsNull() ? GetCategory(info.Value) : null; // return result; } /// /// Get all Specified Category File Type Info ... /// /// /// public static IReadOnlyList GetByCategory(XFileCategory category) { // var min = (int)category; var max = min + 100; // var result = GetAll() .Where(x => x.Value >= min && x.Value < max) .ToList() .AsReadOnly(); // return result; } /// /// Get All Supported Extensions ... /// /// public static IReadOnlyList GetExtensions() { // var result = GetAll() .Select(x => x.Extension) .ToList() .AsReadOnly(); // return result; } /// /// Get All Supported Mime Types ... /// /// public static IReadOnlyList GetMimeTypes() { // var result = GetAll() .Select(x => x.MimeType) .Where(m => !string.IsNullOrWhiteSpace(m)) .Distinct(StringComparer.OrdinalIgnoreCase) .ToList() .AsReadOnly(); // return result; } // #region Private ... /// /// Build List ... /// /// private static IReadOnlyList Build() { // var extensions = ReadEnum(); var mimeTypes = ReadEnum(); // var list = new List(extensions.Count); foreach (var ext in extensions.Values.OrderBy(e => e.Value)) { // mimeTypes.TryGetValue(ext.Value, out var mime); list.Add(new XFileTypeInfo { Name = ext.Name, Value = ext.Value, Extension = ext.StringValue, MimeType = mime.StringValue ?? string.Empty }); } // var result = list.AsReadOnly(); return result; } /// /// Read Enum ... /// /// /// private static Dictionary ReadEnum() where TEnum : struct, Enum { // var map = new Dictionary(); foreach (var field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)) { // var attr = field.GetCustomAttribute(); if (attr == null) continue; var value = Convert.ToInt32(field.GetValue(null)); // map[value] = new EnumEntry { Value = value, Name = field.Name, StringValue = attr.StringValue }; } // return map; } /// /// Enum Entries for Read ... /// private struct EnumEntry { public int Value { get; set; } public string Name { get; set; } public string StringValue { get; set; } } #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Helpers\XGenericHelper.cs using System; using System.Linq; using System.Reflection; using xCommons.Extensions; using System.Collections.Generic; namespace xCommons.Helpers { public static class XGenericHelper { /// /// Invoke a Generic Method of Specified Type ... /// /// /// /// /// public static void InvokeGenericMethod( this Type source, string methodName, Type runtimeType, params object[] args ) { // source.InvokeGenericMethod( args: args, methodName: methodName, runtimeType: runtimeType ); } /// /// Invoke a Generic Method of Specified Type ... /// /// /// /// /// /// /// public static TResponse InvokeGenericMethod( this Type source, string methodName, Type runtimeType, params object[] args ) { // var overLoads = source.GetGenericMethodInfo( methodName: methodName ); if (!overLoads.HasChild()) { return default; } // var method = overLoads.ElementAt(0); MethodInfo genericMethod = method.MakeGenericMethod(runtimeType); // var resultObj = genericMethod.Invoke(null, args); var result = (TResponse)resultObj; // return result; } /// /// Invoke a Generic Method of Specified Type ... /// /// /// /// /// public static void InvokeGenericMethod( this Type source, string methodName, Type[] runtimeTypes, params object[] args ) { // source.InvokeGenericMethod( args: args, methodName: methodName, runtimeTypes: runtimeTypes ); } /// /// Invoke a Generic Method of Specified Type ... /// /// /// /// /// /// /// public static TResponse InvokeGenericMethod( this Type source, string methodName, Type[] runtimeTypes, params object[] args ) { // var overLoads = source.GetGenericMethodInfo( methodName: methodName ); if (!overLoads.HasChild()) { return default; } // // Detect a Method by Generic Types ... // var method = overLoads.ElementAt(0); var method = overLoads.First(m => m.GetGenericArguments().Length == runtimeTypes.Length); MethodInfo genericMethod = method.MakeGenericMethod(runtimeTypes); // var resultObj = genericMethod.Invoke(null, args); var result = resultObj.ConvertTo(); // return result; } /// /// Extract a Generic Method's Overloads ... /// /// /// /// public static List GetGenericMethodInfo( this Type source, string methodName ) { // var methods = source .GetMethods(); // var result = methods .Where(mi => mi.Name == methodName && mi.IsGenericMethodDefinition) .ToList(); // return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Helpers\XMLToJSONHelper.cs using System; using System.Xml; using System.Text; using System.Collections.Generic; namespace xCommons.Helpers { public partial class XMLToJSONHelper { // #region Actions ... public static string ToJSON (string xml) { // XmlDocument doc = new XmlDocument (); doc.LoadXml (xml); // return XmlToJSON (doc); } public static string XmlToJSON (XmlDocument xmlDoc) { // StringBuilder sbJSON = new StringBuilder (); // sbJSON.Append ("{ "); XmlToJSONnode (sbJSON, xmlDoc.DocumentElement, true); sbJSON.Append ("}"); // return sbJSON.ToString (); } #endregion // #region Private ... // private static void XmlToJSONnode (StringBuilder sbJSON, XmlElement node, bool showNodeName) { // if (showNodeName) { sbJSON.Append ("\"" + SafeJSON (node.Name) + "\": "); } // sbJSON.Append ("{"); // // Build a sorted list of key-value pairs // where key is case-sensitive nodeName // value is an ArrayList of string or XmlElement // so that we know whether the nodeName is an array or not. SortedList childNodeNames = new SortedList (); // // Add in all node attributes if (node.Attributes != null) foreach (XmlAttribute attr in node.Attributes) StoreChildNode (childNodeNames, attr.Name, attr.InnerText); // // Add in all nodes foreach (XmlNode cnode in node.ChildNodes) { // if (cnode is XmlText) { StoreChildNode (childNodeNames, "value", cnode.InnerText); } else if (cnode is XmlElement) { StoreChildNode (childNodeNames, cnode.Name, cnode); } } // // Now output all stored info foreach (string childname in childNodeNames.Keys) { // List alChild = (List) childNodeNames[childname]; if (alChild.Count == 1) { OutputNode (childname, alChild[0], sbJSON, true); } else { // sbJSON.Append (" \"" + SafeJSON (childname) + "\": [ "); // foreach (object Child in alChild) { OutputNode (childname, Child, sbJSON, false); } // sbJSON.Remove (sbJSON.Length - 2, 2); sbJSON.Append (" ], "); } } // sbJSON.Remove (sbJSON.Length - 2, 2); sbJSON.Append (" }"); } // // StoreChildNode: Store data associated with each nodeName // so that we know whether the nodeName is an array or not. private static void StoreChildNode (SortedList childNodeNames, string nodeName, object nodeValue) { // // Pre-process contraction of XmlElement-s if (nodeValue is XmlElement) { // // Convert into "aa":null // xx into "aa":"xx" XmlNode cnode = (XmlNode) nodeValue; if (cnode.Attributes.Count == 0) { // XmlNodeList children = cnode.ChildNodes; if (children.Count == 0) { nodeValue = null; } else if (children.Count == 1 && (children[0] is XmlText)) { nodeValue = ((XmlText) (children[0])).InnerText; } } } // // Add nodeValue to ArrayList associated with each nodeName // If nodeName doesn't exist then add it List ValuesAL; // if (childNodeNames.ContainsKey (nodeName)) { ValuesAL = (List) childNodeNames[nodeName]; } else { // ValuesAL = new List (); childNodeNames[nodeName] = ValuesAL; } // ValuesAL.Add (nodeValue); } // private static void OutputNode (string childname, object alChild, StringBuilder sbJSON, bool showNodeName) { if (alChild == null) { if (showNodeName) sbJSON.Append ("\"" + SafeJSON (childname) + "\": "); sbJSON.Append ("null"); } else if (alChild is string) { if (showNodeName) sbJSON.Append ("\"" + SafeJSON (childname) + "\": "); string sChild = (string) alChild; sChild = sChild.Trim (); sbJSON.Append ("\"" + SafeJSON (sChild) + "\""); } else XmlToJSONnode (sbJSON, (XmlElement) alChild, showNodeName); sbJSON.Append (", "); } // // Make a string safe for JSON private static string SafeJSON (string sIn) { // StringBuilder sbOut = new StringBuilder (sIn.Length); foreach (char ch in sIn) { // if (Char.IsControl (ch) || ch == '\'') { // int ich = (int) ch; sbOut.Append (@"\u" + ich.ToString ("x4")); continue; } else if (ch == '\"' || ch == '\\' || ch == '/') { sbOut.Append ('\\'); } // sbOut.Append (ch); } // return sbOut.ToString (); } #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Helpers\XNetworkHelper.cs using System.Net; using System.Linq; using xCommons.Models; using System.Net.Sockets; using System.Collections.Generic; using System.Net.NetworkInformation; namespace xCommons.Helpers { public static class XNetworkHelper { /// /// Retrieve Application Host's Machin IP Addresses ... /// /// string public static string GetIp () { // var name = Dns.GetHostName (); // get container id var result = Dns.GetHostEntry (name) .AddressList .FirstOrDefault ( x => x.AddressFamily == AddressFamily.InterNetwork ) .MapToIPv4 () .ToString (); // return result; } /// /// Retrieve All Available IP's in Application Host's Machin ... /// /// a Collection of XNetworkInfo class instances public static IEnumerable GetNetworkInfos () { // var result = System.Net.NetworkInformation.NetworkInterface .GetAllNetworkInterfaces () .Where ( ni => !ni.IsReceiveOnly && ni.OperationalStatus == OperationalStatus.Up && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback ) .SelectMany (ni => ni .GetIPProperties () .GatewayAddresses .Select (ga => new { Name = ni.Name, Description = ni.Description, Gateway = ga.Address .MapToIPv4 () .ToString (), NI = ni } ) ) .SelectMany (data => data.NI .GetIPProperties () .UnicastAddresses .Select (ip => new XNetworkInfo { Name = data.Name, Gateway = data.Gateway, Description = data.Description, NetworkInterface = data.NI, IP = ip.Address .MapToIPv4 () .ToString () } ) ); // return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Helpers\XOsHelper.cs using System; using System.Diagnostics; using xCommons.Extensions; using xExceptions.Constants; using System.Threading.Tasks; using xExceptions.Attributes; using System.Runtime.InteropServices; namespace xCommons.Helpers { /// /// Several OS Type ... /// public enum XOSType { [StringValue("Unknown")] XUnknown, [StringValue("Mac")] XMacOs, [StringValue("Linux")] XLinux, [StringValue("Windows")] XWindows, [StringValue("FreeBSD")] XFreeBSD, } /// /// OS Command Execution Result ... /// public class XOSCMDResult { /// /// Execution Result ... /// /// public string Result { get; set; } /// /// Execution Error ... /// /// public string Error { get; set; } } /// /// a Helper Class which Provides OS Command Executions ... /// public static partial class XOsHelper { /// /// Retrieve OS Type ... /// /// public static XOSType GetOSType() { // XOSType result = XOSType.XUnknown; // if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { result = XOSType.XMacOs; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { result = XOSType.XLinux; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { result = XOSType.XWindows; } // else if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) // { // result = XOSType.XFreeBSD; // } // return result; } /// /// Retrieve OS Description ... /// /// public static string GetOSDescription() { // var result = RuntimeInformation.OSDescription; return result; } /// /// Execute an Specified Command ... /// /// Specified Command /// Command Arguments /// public static async Task Execute( string cmd, string args ) { // var result = new XOSCMDResult { Error = "Unknown", }; // try { // // Validate CMD ... var isValid = !cmd.IsNullOrEmpty(); if (!isValid) { XException.InvalidArgs.Throw(); } // // Validate OS Type ... XOSType osType = GetOSType(); isValid = osType != XOSType.XUnknown; if (!isValid) { XException.InvalidArgs.Throw(); } // return await Task.Run(() => { // ProcessStartInfo psi = new ProcessStartInfo(); // psi.FileName = cmd; psi.Arguments = args; psi.UseShellExecute = false; psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; // Process process = Process.Start(psi); // // Read the output string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); // process.WaitForExit(); // result = new XOSCMDResult { Error = error, Result = output, }; // return result; }); } catch (Exception ex) { result.Error = ex.Message; } // return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Helpers\XReflectionHelper.cs using System; using System.Reflection; namespace xCommons.Helpers { public static class XReflectionHelper { public static object GetFieldValue (this object obj, string fieldName) { if (obj == null) throw new ArgumentNullException (nameof (obj)); Type objType = obj.GetType (); var fieldInfo = GetFieldInfo (objType, fieldName); if (fieldInfo == null) throw new ArgumentOutOfRangeException (fieldName, $"Couldn't find field {fieldName} in type {objType.FullName}"); return fieldInfo.GetValue (obj); } public static void SetFieldValue (this object obj, string fieldName, object val) { if (obj == null) throw new ArgumentNullException (nameof (obj)); Type objType = obj.GetType (); var fieldInfo = GetFieldInfo (objType, fieldName); if (fieldInfo == null) throw new ArgumentOutOfRangeException (fieldName, $"Couldn't find field {fieldName} in type {objType.FullName}"); fieldInfo.SetValue (obj, val); } private static FieldInfo GetFieldInfo (Type type, string fieldName) { FieldInfo fieldInfo = null; do { fieldInfo = type.GetField (fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); type = type.BaseType; } while (fieldInfo == null && type != null); return fieldInfo; } public static object GetPropertyValue (this object obj, string propertyName) { if (obj == null) throw new ArgumentNullException (nameof (obj)); Type objType = obj.GetType (); var propertyInfo = GetPropertyInfo (objType, propertyName); if (propertyInfo == null) throw new ArgumentOutOfRangeException (propertyName, $"Couldn't find property {propertyName} in type {objType.FullName}"); return propertyInfo.GetValue (obj, null); } public static void SetPropertyValue (this object obj, string propertyName, object val) { if (obj == null) throw new ArgumentNullException (nameof (obj)); Type objType = obj.GetType (); var propertyInfo = GetPropertyInfo (objType, propertyName); if (propertyInfo == null) throw new ArgumentOutOfRangeException (propertyName, $"Couldn't find property {propertyName} in type {objType.FullName}"); propertyInfo.SetValue (obj, val, null); } private static PropertyInfo GetPropertyInfo (Type type, string propertyName) { PropertyInfo propertyInfo = null; do { propertyInfo = type.GetProperty (propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); type = type.BaseType; } while (propertyInfo == null && type != null); return propertyInfo; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Interfaces\IXCipher.cs namespace xCommons.Interfaces { public interface IXCipher { string Encrypt(string plainText); string Decrypt(string cipherText); string EncryptFromBytes(byte[] textBytes); string DecryptFromBytes(byte[] cipherBytes); } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Interfaces\IXFileTypeDetector.cs using System.IO; using xCommons.Models; using System.Threading; using xCommons.Constants; using System.Threading.Tasks; namespace xCommons.Interfaces { public interface IXFileTypeDetector { /// /// Detect MIME Type based on File Name ... /// /// /// string DetectFromExtension(string fileName); /// /// Detect XFileExtensions based on File Name ... /// /// /// XFileExtensions? DetectExtension(string fileName); /// /// Detect Type based on File's Magic Byte ... /// /// /// /// Task DetectFromMagicBytesAsync( Stream stream, CancellationToken cancellationToken = default ); /// /// Complexity Detect Type ... /// /// /// /// /// /// Task DetectAsync( string fileName, string providedMimeType, Stream stream, CancellationToken cancellationToken = default ); /// /// Check a File Extension is Known or not ... /// /// /// bool IsKnownExtension(string fileName); } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Interfaces\IXRateLimitProvider.cs using xCommons.Models; using xCommons.Configurations; namespace xCommons.Interfaces { public interface IXRateLimitProvider { bool IsEnabled { get; } XRateLimitResult TryConsume( string key, int limit, int periodSeconds ); XRateLimitResult TryConsume( string key, XRateLimitRule rule ); } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Middlewares\XRateLimitMiddleware.cs using System.Net; using xCommons.Models; using xCommons.Constants; using xCommons.Attributes; using xCommons.Extensions; using xCommons.Interfaces; using System.Threading.Tasks; using xCommons.Configurations; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; namespace xCommons.Middlewares { public class XRateLimitMiddleware { // private readonly RequestDelegate next; private readonly IXRateLimitProvider provider; private readonly XRateLimitConfiguration configuration; public XRateLimitMiddleware( RequestDelegate next, IXRateLimitProvider provider, XRateLimitConfiguration configuration ) { // this.next = next; this.provider = provider; this.configuration = configuration; } public async Task InvokeAsync(HttpContext context) { // if (!provider.IsEnabled) { await next(context); return; } // var endpoint = context.Features.Get()?.Endpoint; if (!endpoint.IsNull() && !endpoint.Metadata .GetMetadata() .IsNull() ) { // await next(context); return; } // var rule = configuration.GetMatchingRule(context.Request.Path); if (rule.IsNull()) { await next(context); return; } // var key = context.GetXRateLimitKey(rule.KeyMode); var result = provider.TryConsume(key, rule); // WriteHeaders(context, result); // if (!result.IsAllowed) { // await context.WriteResponseAsJsonAsync( status: (HttpStatusCode)configuration.StatusCode, data: new { message = "Too many requests. Please try again later.", retryAfter = result.RetryAfterSeconds, resetOn = result.ResetOn } ); return; } // await next(context); } private static void WriteHeaders( HttpContext context, XRateLimitResult result ) { // context.Response.Headers[XRateLimitConstants.LimitHeader] = result.Limit.ToString(); // context.Response.Headers[XRateLimitConstants.RemainingHeader] = result.Remaining.ToString(); // context.Response.Headers[XRateLimitConstants.ResetHeader] = result.ResetOn.ToUnixTimeSeconds().ToString(); // if (!result.IsAllowed) { context.Response.Headers[XRateLimitConstants.RetryAfterHeader] = result.RetryAfterSeconds.ToString(); } } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Models\XCertificate.cs namespace xCommons.Models { public partial class XCertificate { public string Path { get; set; } public string Secret { get; set; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Models\XFileTypeDetectionResult.cs using xCommons.Constants; namespace xCommons.Models { public class XFileTypeDetectionResult { /// /// File Mime Type ... /// public string MimeType { get; set; } /// /// File Extension ... /// public string Extension { get; set; } /// /// Type Detection Source ... /// public XFileTypeDetectionSource Source { get; set; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Models\XFileTypeInfo.cs namespace xCommons.Models { public class XFileTypeInfo { /// /// Enum Value ... /// public int Value { get; set; } /// /// Enum Item Name as String ... /// public string Name { get; set; } = string.Empty; /// /// Extension as String ... /// public string Extension { get; set; } = string.Empty; /// /// Mime Type as String ... /// public string MimeType { get; set; } = string.Empty; /// /// Override To String ... /// /// public override string ToString() { // var result = $"{Name} ({Extension}) -> {MimeType} [{Value}]"; return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Models\XLoggerModel.cs using System; using Microsoft.AspNetCore.Http; namespace xCommons.Models { public class XLoggerModel { public string Host { get; set; } public string Path { get; set; } public string Schema { get; set; } public string Method { get; set; } public string UserID { get; set; } public string Request { get; set; } public int StatusCode { get; set; } public bool IsSucceed { get; set; } public string Response { get; set; } public string QueryString { get; set; } public DateTime RequestedOn { get; set; } public DateTime RespondedOn { get; set; } public IHeaderDictionary Headers { get; set; } public Exception Exception { get; set; } = null; public XLoggerHttpConnection Connection { get; set; } } public class XLoggerHttpConnection { public string Id { get; set; } public string RemoteIpAddress { get; set; } public string RemotePort { get; set; } public string LocalIpAddress { get; set; } public string LocalPort { get; set; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Models\XNetworkInfo.cs using System; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using System.Net.NetworkInformation; namespace xCommons.Models { public class XNetworkInfo { /// /// Network Name ... /// /// public string Name { get; set; } /// /// Network Description ... /// /// public string Description { get; set; } /// /// IP Address which Exists on Current Network ... /// /// public string IP { get; set; } /// /// Current Networks Gateway Address ... /// /// public string Gateway { get; set; } /// /// Network Interface Object ... /// /// public NetworkInterface NetworkInterface { get; set; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Models\XRateLimitCounter.cs using System; namespace xCommons.Models { public class XRateLimitCounter { public int Count { get; set; } public int Limit { get; set; } public DateTimeOffset ResetOn { get; set; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Models\XRateLimitResult.cs using System; namespace xCommons.Models { public class XRateLimitResult { public int Limit { get; set; } public string Key { get; set; } public int Remaining { get; set; } public bool IsAllowed { get; set; } public int RetryAfterSeconds { get; set; } public DateTimeOffset ResetOn { get; set; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Models\XServiceDescriptor.cs using System; namespace xCommons.Models { public class XServiceDescriptor { public Type Service { get; set; } public Type Implementation { get; set; } } public class XServiceDescriptor : XServiceDescriptor { public XServiceDescriptor() : base() { Service = typeof(TService); Implementation = typeof(TImplmentation); } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Providers\XBackgroundService.cs using System; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace xCommons.Providers { /// /// Default Background Service ... /// public abstract class XBackgroundService : BackgroundService { // protected readonly IServiceProvider serviceProvider; protected readonly ILogger logger; protected XBackgroundService( IServiceProvider serviceProvider, ILogger logger ) { // this.logger = logger; this.serviceProvider = serviceProvider; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Providers\XCipher.cs using System; using System.IO; using System.Text; using xCommons.Extensions; using xCommons.Interfaces; using System.Security.Cryptography; namespace xCommons.Providers { public class XCipher : IXCipher { // #region Props ... private readonly string secretKey; private readonly byte[] iv; private readonly byte[] key; private readonly XValidationProvider validationProvider; #endregion // #region Constructor ... public XCipher( string cipherKey, XValidationProvider validationProvider ) { // this.secretKey = cipherKey.ToMd5String(); this.validationProvider = validationProvider; // var ivBytes = new byte[16]; var keyBytes = new byte[32]; var secretBytes = Encoding.UTF8.GetBytes(this.secretKey); // Array.Copy( secretBytes, ivBytes, secretBytes.Length < ivBytes.Length ? secretBytes.Length : ivBytes.Length ); this.iv = ivBytes; // Array.Copy( secretBytes, keyBytes, secretBytes.Length < keyBytes.Length ? secretBytes.Length : keyBytes.Length ); this.key = keyBytes; // Encoding.UTF8.GetBytes (this.secretKey); } #endregion // #region Actions ... public string Encrypt(string plainText) { // validationProvider.NotEmpty(plainText); // var textBytes = Encoding.UTF8.GetBytes(plainText); var result = EncryptFromBytes(textBytes); // return result; } public string Decrypt(string cipherText) { // validationProvider.NotEmpty(cipherText); // var cipherBytes = Convert.FromBase64String(cipherText); var result = DecryptFromBytes(cipherBytes); // return result; } public string EncryptFromBytes(byte[] textBytes) { // // Validate Args ... validationProvider.NotNull(textBytes); // Declare the string used to hold // the decrypted text. byte[] encryptedBytes = null; // Create an RijndaelManaged object // with the specified key and IV. using (var rijAlg = new RijndaelManaged()) { //Settings rijAlg.Mode = CipherMode.CBC; rijAlg.Padding = PaddingMode.PKCS7; // rijAlg.FeedbackSize = 128; rijAlg.Key = key; rijAlg.IV = iv; // using (var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV)) { encryptedBytes = encryptor.TransformFinalBlock(textBytes, 0, textBytes.Length); } } // return Convert.ToBase64String(encryptedBytes); } public string DecryptFromBytes(byte[] cipherBytes) { // // Validate Args ... validationProvider.NotNull(cipherBytes); // Declare the string used to hold // the decrypted text. string plaintext = null; // Create an RijndaelManaged object // with the specified key and IV. using (var rijAlg = new RijndaelManaged()) { //Settings rijAlg.Mode = CipherMode.CBC; rijAlg.Padding = PaddingMode.PKCS7; // rijAlg.FeedbackSize = 128; rijAlg.Key = key; rijAlg.IV = iv; // Create a decrytor to perform the stream transform. var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); // Create the streams used for decryption. using (var msDecrypt = new MemoryStream(cipherBytes)) { using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (var srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } } // return plaintext; } #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Providers\XFileTypeDetector.cs using System; using System.IO; using xCommons.Models; using xCommons.Helpers; using System.Threading; using xCommons.Constants; using xCommons.Interfaces; using xCommons.Extensions; using System.Threading.Tasks; using xCommons.Configurations; using System.Collections.Generic; namespace xCommons.Providers { public class XFileTypeDetector : IXFileTypeDetector { private readonly XFileTypeDetectorConfiguration configuration; private readonly Dictionary MagicSignatures = new(StringComparer.OrdinalIgnoreCase) { ["image/png"] = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, ["image/jpeg"] = new byte[] { 0xFF, 0xD8, 0xFF }, ["image/gif"] = new byte[] { 0x47, 0x49, 0x46, 0x38 }, ["image/bmp"] = new byte[] { 0x42, 0x4D }, ["image/x-icon"] = new byte[] { 0x00, 0x00, 0x01, 0x00 }, ["application/pdf"] = new byte[] { 0x25, 0x50, 0x44, 0x46 }, ["application/zip"] = new byte[] { 0x50, 0x4B, 0x03, 0x04 }, ["application/x-rar-compressed"] = new byte[] { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07 }, ["application/x-7z-compressed"] = new byte[] { 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C }, ["audio/mpeg"] = new byte[] { 0xFF, 0xFB }, ["audio/ogg"] = new byte[] { 0x4F, 0x67, 0x67, 0x53 }, ["font/ttf"] = new byte[] { 0x00, 0x01, 0x00, 0x00 } }; public XFileTypeDetector( XFileTypeDetectorConfiguration configuration ) { this.configuration = configuration; } /// /// Detect Type based on File Name ... /// /// /// public string DetectFromExtension(string fileName) { // var result = string.Empty; // // Validate ... if (fileName.IsNullOrEmpty()) { return result; } // var extension = Path.GetExtension(fileName); if (extension.IsNullOrEmpty()) { return result; } // result = XFileHelper.GetMimeType(extension); // return result; } /// /// Detect XFileExtensions based on File Name ... /// /// /// public XFileExtensions? DetectExtension(string fileName) { // XFileExtensions? result = null; if (fileName.IsNullOrEmpty()) { return result; } // var extension = Path.GetExtension(fileName); var info = XFileHelper.GetByExtension(extension); if (info.IsNull()) { return result; } // result = (XFileExtensions)info.Value; // return result; } /// /// Check a File Extension is Known or not ... /// /// /// public bool IsKnownExtension(string fileName) { // var result = !fileName.IsNullOrEmpty(); if (!result) { return result; } // var extension = Path.GetExtension(fileName); result = XFileHelper.IsSupported(extension); // return result; } /// /// Detect Type based on File's Magic Byte ... /// /// /// /// public async Task DetectFromMagicBytesAsync( Stream stream, CancellationToken cancellationToken = default ) { // var result = string.Empty; // // Validate ... if (stream == null || !stream.CanRead) { return result; } // var originalPosition = stream.CanSeek ? stream.Position : 0L; try { // var header = new byte[configuration.HeaderSize]; var read = await ReadHeaderAsync(stream, header, cancellationToken); if (read < 2) { return result; } // foreach (var signature in MagicSignatures) { // if (MatchesSignature(header, read, signature.Value)) { // result = signature.Key; return result; } } // return result; } finally { // if (stream.CanSeek) { stream.Position = originalPosition; } } } /// /// Complexity Detect Type ... /// /// /// /// /// /// public async Task DetectAsync( string fileName, string providedMimeType, Stream stream, CancellationToken cancellationToken = default ) { // var result = new XFileTypeDetectionResult { Source = XFileTypeDetectionSource.None }; // if (configuration.PreferMagicBytes) { // var magicMime = await DetectFromMagicBytesAsync(stream, cancellationToken); if (!magicMime.IsNullOrEmpty()) { // result.MimeType = magicMime; result.Extension = XFileHelper.GetExtension(magicMime); result.Source = XFileTypeDetectionSource.MagicBytes; // return result; } } // var extensionMime = DetectFromExtension(fileName); if (!extensionMime.IsNullOrEmpty()) { // result.MimeType = extensionMime; result.Extension = Path.GetExtension(fileName)?.ToLowerInvariant(); result.Source = XFileTypeDetectionSource.Extension; // return result; } // if (!string.IsNullOrWhiteSpace(providedMimeType)) { // var info = XFileHelper.GetByMimeType(providedMimeType); if (info != null) { // result.MimeType = info.MimeType; result.Extension = info.Extension; result.Source = XFileTypeDetectionSource.ProvidedMime; } } // return result; } // #region Private ... private static async Task ReadHeaderAsync( Stream stream, byte[] buffer, CancellationToken ct = default ) { // var totalRead = 0; while (totalRead < buffer.Length) { // var read = await stream.ReadAsync( buffer, totalRead, buffer.Length - totalRead, ct); if (read == 0) break; totalRead += read; } // return totalRead; } private static bool MatchesSignature(byte[] header, int length, byte[] signature) { // if (length < signature.Length) return false; for (var i = 0; i < signature.Length; i++) { if (header[i] != signature[i]) return false; } // return true; } #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Providers\XRateLimitProvider.cs using System; using xCommons.Models; using xCommons.Constants; using xCommons.Extensions; using xCommons.Interfaces; using xExceptions.Constants; using xCommons.Configurations; using System.Collections.Concurrent; using Microsoft.Extensions.Caching.Memory; namespace xCommons.Providers { public class XRateLimitProvider : IXRateLimitProvider { // private readonly IMemoryCache cache; private readonly XRateLimitConfiguration configuration; private readonly ConcurrentDictionary syncRoots = new(); public XRateLimitProvider( IMemoryCache cache, XRateLimitConfiguration configuration ) { // this.cache = cache; this.configuration = configuration; } public bool IsEnabled { get { return !configuration.IsNull() && configuration.Enabled; } } public XRateLimitResult TryConsume( string key, XRateLimitRule rule ) { // if (rule.IsNull()) { XException.InvalidArgs.Throw(); } // return TryConsume( key: key, limit: rule.Limit, periodSeconds: rule.PeriodSeconds ); } public XRateLimitResult TryConsume( string key, int limit, int periodSeconds ) { // if (limit <= 0 || periodSeconds <= 0) { XException.InvalidArgs.Throw(); } // var normalizedKey = BuildCacheKey(key); var now = DateTimeOffset.UtcNow; // if (!IsEnabled) { // return new XRateLimitResult { Limit = limit, IsAllowed = true, Remaining = limit, Key = normalizedKey, RetryAfterSeconds = 0, ResetOn = now.AddSeconds(periodSeconds) }; } // var syncRoot = syncRoots.GetOrAdd( key: normalizedKey, valueFactory: _ => new object() ); // lock (syncRoot) { // var counter = cache.Get(normalizedKey); if (counter.IsNull() || counter.ResetOn <= now) { // counter = new XRateLimitCounter { Count = 0, Limit = limit, ResetOn = now.AddSeconds(periodSeconds) }; } // counter.Count++; counter.Limit = limit; // var remaining = Math.Max(0, limit - counter.Count); var isAllowed = counter.Count <= limit; var retryAfter = isAllowed ? 0 : (int)Math.Ceiling((counter.ResetOn - now).TotalSeconds); // var options = new MemoryCacheEntryOptions { AbsoluteExpiration = counter.ResetOn }; // options.RegisterPostEvictionCallback((cacheKey, value, reason, state) => { syncRoots.TryRemove(cacheKey.ToString(), out _); }); // cache.Set(normalizedKey, counter, options); // return new XRateLimitResult { Limit = limit, Key = normalizedKey, IsAllowed = isAllowed, Remaining = remaining, ResetOn = counter.ResetOn, RetryAfterSeconds = retryAfter, }; } } private static string BuildCacheKey(string key) { // var normalized = key.IsNullOrEmpty() ? "anonymous" : key.ToNormalString(); // return string.Format( "{0}:{1}", XRateLimitConstants.CacheKeyPrefix, normalized ); } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Providers\XResumableBackgroundService.cs using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace xCommons.Providers { /// /// Resumable Background Task ... /// public abstract class XResumableBackgroundService : XBackgroundService { /// /// Check is Paused ... /// protected bool paused = false; protected XResumableBackgroundService( IServiceProvider serviceProvider, ILogger logger ) : base( logger: logger, serviceProvider: serviceProvider ) { } protected override async Task ExecuteAsync( CancellationToken stoppingToken = default ) { // if (paused) { return; } // await DoWorkAsync( payload: null, cancellationToken: stoppingToken ); } /// /// do all required works here ... /// /// /// /// public abstract Task DoWorkAsync( object payload = null, CancellationToken cancellationToken = default ); /// /// Pause Consuming ... /// /// public bool Pause() { // var result = !paused; if (!result) { return result; } // paused = true; result = paused; return result; } /// /// Resume Consuming ... /// /// public bool Resume() { // var result = paused; if (!result) { return result; } // paused = false; result = !paused; return result; } } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Providers\XTimeBasedBackgroundService.cs using System; using System.Threading; using xCommons.Extensions; using xExceptions.Constants; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace xCommons.Providers { /// /// Do Background Jobs based on Time Intervals ... /// public abstract class XTimeBasedBackgroundService : XBackgroundService { // private bool isWorking = false; private readonly TimeSpan restartInterval; private readonly SemaphoreSlim mlock = new(1, 1); public DateTime? LastRunTime { get; private set; } private CancellationTokenSource cancellationTokenSource; protected XTimeBasedBackgroundService( IServiceProvider serviceProvider, ILogger logger, int intervalInMinutes = 10 ) : base( logger: logger, serviceProvider: serviceProvider ) { // // Validate Interval ... if (intervalInMinutes <= 0) { XException.InvalidArgs.Throw(); } // restartInterval = TimeSpan.FromMinutes(intervalInMinutes); } /// /// Override base action to Implement timing ... /// /// /// protected override async Task ExecuteAsync(CancellationToken stoppingToken) { // while (!stoppingToken.IsCancellationRequested) { try { if (!isWorking) { // // Enable Working ... await mlock.WaitAsync(stoppingToken); try { isWorking = true; } finally { mlock.Release(); } // // Start a new work task ... cancellationTokenSource = CancellationTokenSource .CreateLinkedTokenSource(stoppingToken); // // Execute the work ... await ExecuteWorkAsync(cancellationTokenSource.Token); // // Disable Working ... await mlock.WaitAsync(stoppingToken); try { isWorking = false; } finally { mlock.Release(); } // // Wait for the restart interval ... await Task.Delay(restartInterval, stoppingToken); } else { // // Prevent tight error loops ... await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); } } catch (OperationCanceledException) { // // Disable Working ... await mlock.WaitAsync(stoppingToken); try { isWorking = false; } finally { mlock.Release(); } break; } catch (Exception) { // // Disable Working ... await mlock.WaitAsync(stoppingToken); try { isWorking = false; } finally { mlock.Release(); } // // Prevent tight error loops ... await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); } } } /// /// Override Stop Background Worker ... /// /// /// public override async Task StopAsync(CancellationToken cancellationToken) { // // Cancel the current work session cancellationTokenSource.Cancel(); await base.StopAsync(cancellationToken); } /// /// Dispose all Objects ... /// public override void Dispose() { mlock.Dispose(); cancellationTokenSource.Dispose(); GC.SuppressFinalize(this); base.Dispose(); } /// /// do all required works here ... /// /// /// public abstract Task DoWorkAsync( CancellationToken cancellationToken = default ); /// /// Refresh Worker ... /// /// /// public async Task Refresh( CancellationToken cancellationToken = default ) { // // Cancel current work if running cancellationTokenSource.Cancel(); // // Wait a moment for cancellation await Task.Delay(100, cancellationToken); // // Start new work immediately cancellationTokenSource = CancellationTokenSource .CreateLinkedTokenSource(cancellationToken); await ExecuteWorkAsync(cancellationTokenSource.Token); } // #region Private ... private async Task ExecuteWorkAsync(CancellationToken cancellationToken) { // LastRunTime = DateTime.UtcNow; try { await DoWorkAsync(cancellationToken); } catch (OperationCanceledException) { } catch (Exception) { } finally { } } #endregion } } ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xCommons\Providers\XValidationProvider.cs using System; using System.Linq; using xCommons.Extensions; using xExceptions.Constants; using System.Threading.Tasks; using System.Collections.Generic; namespace xCommons.Providers { public partial class XValidationProvider { private ICollection validationGroup; // #region Simple Validators ... /// /// given objects must not null /// /// public void NotNull ( params object[] values) { // foreach (var o in values) { // if (o == null) { XException.InvalidArgs.Throw (); } } } /// /// given strings must not empty or null /// /// public void NotEmpty ( params string[] values) { // foreach (var s in values) { // if (s.IsNullOrEmpty ()) { XException.InvalidArgs.Throw (); } } } /// /// Check a numeric value is bigger than 0 /// /// public void NotZero ( params int[] values) { // foreach (var s in values) { // if (s == 0) { XException.InvalidArgs.Throw (); } } } /// /// Check a numeric value is bigger than 0 /// /// public void NotZero ( params long[] values) { // foreach (var s in values) { // if (s == 0) { XException.InvalidArgs.Throw (); } } } /// /// Check a numeric value is bigger than 0 /// /// public void NotZero ( params decimal[] values) { // foreach (var s in values) { // if (s == 0) { XException.InvalidArgs.Throw (); } } } /// /// Check a Value is a Valid Guid ... /// /// public void IsGuid (params string[] values) { // foreach (var s in values) { // if (!s.IsGuid () || s.IsDefaultGuid ()) { XException.InvalidArgs.Throw (); } } } /// /// Check a Value is a Valid Guid ... /// /// public void IsGuid (params Guid[] values) { // foreach (var s in values) { // if (s.IsNull () || s.IsDefaultGuid ()) { XException.InvalidArgs.Throw (); } } } /// /// Check a Value is an MD5 ... /// /// public void IsMD5 (params string[] values) { // foreach (var s in values) { // if (!s.IsMD5String ()) { XException.InvalidArgs.Throw (); } } } /// /// non zero childs /// /// public void NotZeroChilds ( params IEnumerable[] values) { // foreach (var s in values) { // if (s == null || s.Count () == 0) { XException.InvalidArgs.Throw (); } } } /// /// non zero childs /// /// public void NotZeroChilds ( params ICollection[] values) { // foreach (var s in values) { // if (s == null || s.Count == 0) { XException.InvalidArgs.Throw (); } } } /// /// given string must be a valid URL ... /// /// /// public void Url ( string url, Exception exception = null ) { // NotEmpty (url); // if (exception == null) { exception = XException.InavlidUrl.ToException (); } // if (!url.IsValidUrl ()) { throw exception; } } /// /// given string must be a valid Email Address ... /// /// /// public void EmailAddress ( string emailAdress, Exception exception = null ) { // NotEmpty (emailAdress); // if (exception == null) { exception = XException.InvalidEmailAddress.ToException (); } // if (!emailAdress.IsValidEmail ()) { throw exception; } } /// /// given string must be a valid Mobile Number ... /// /// /// public void MobileNumber ( string mobileNumber, Exception exception = null ) { // NotEmpty (mobileNumber); // if (exception == null) { exception = XException.InvalidMobileNumber.ToException (); } // if (!mobileNumber.IsValidMobileNumber ()) { throw exception; } } #endregion // #region Group Validatos ... public XValidationProvider GroupValidationBuilder () { // validationGroup = new List (); // return this; } public XValidationProvider AddNotEmpty (params string[] values) { // this.validationGroup.Add (() => this.NotEmpty (values) ); // return this; } public XValidationProvider AddNotNull (params object[] values) { // this.validationGroup.Add (() => this.NotNull (values) ); // return this; } public XValidationProvider AddNotZero (params int[] values) { // this.validationGroup.Add (() => this.NotZero (values) ); // return this; } public XValidationProvider AddNotZero (params long[] values) { // this.validationGroup.Add (() => this.NotZero (values) ); // return this; } public XValidationProvider AddNotZero (params decimal[] values) { // this.validationGroup.Add (() => this.NotZero (values) ); // return this; } public XValidationProvider AddIsGuid (params string[] values) { // this.validationGroup.Add (() => this.IsGuid (values) ); // return this; } public XValidationProvider AddIsGuid (params Guid[] values) { // this.validationGroup.Add (() => this.IsGuid (values) ); // return this; } public XValidationProvider AddIsMD5 (params string[] values) { // this.validationGroup.Add (() => this.IsMD5 (values) ); // return this; } public XValidationProvider AddNotZeroChilds (params IEnumerable[] values) { // this.validationGroup.Add (() => this.NotZeroChilds (values) ); // return this; } public XValidationProvider AddNotZeroChilds (params ICollection[] values) { // this.validationGroup.Add (() => this.NotZeroChilds (values) ); // return this; } public XValidationProvider AddEmailAddress ( string emailAdress, Exception exception = null) { // this.validationGroup.Add (() => this.EmailAddress (emailAdress, exception) ); // return this; } public XValidationProvider AddMobileNumber ( string mobileNumber, Exception exception = null) { // this.validationGroup.Add (() => this.MobileNumber (mobileNumber, exception) ); // return this; } public XValidationProvider AddUrl ( string url, Exception exception = null) { // this.validationGroup.Add (() => this.Url (url, exception) ); // return this; } public void ValidateGroup () { // // Run each Tasks ... foreach (var action in validationGroup) { action.Invoke (); } // // Clear Task List ... validationGroup.Clear (); } public async Task ValidateGroupAsync () { // // Run each Tasks ... foreach (var action in validationGroup) { await Task.Run (action); } // // Clear Task List ... validationGroup.Clear (); } #endregion } }