Initial Commit ...
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Models;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
public static partial class CertificateExtensions {
|
||||
/// <summary>
|
||||
/// Retrieve Specific Certificate From app Settings
|
||||
/// </summary>
|
||||
/// <param name="configuration"></param>
|
||||
/// <param name="name"></param>
|
||||
/// <returns></returns>
|
||||
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<XCertificate> ();
|
||||
|
||||
//
|
||||
return certificate;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,319 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Swashbuckle.AspNetCore.SwaggerUI;
|
||||
using xCommons.Configurations;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Filters;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
public static partial class DIExtensions {
|
||||
|
||||
/// <summary>
|
||||
/// Inject Specific Registered Service from IServiceCollection
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static T GetRegisteredService<T> (this IServiceCollection source) {
|
||||
//
|
||||
var serviceProvider = source.BuildServiceProvider ();
|
||||
return serviceProvider.GetService<T> ();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register App Configuration as a Service
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public static void AddXAppConfiguration (this IServiceCollection services, IConfiguration configuration) {
|
||||
//
|
||||
var appConfiguration = configuration.GetXAppConfiguration ();
|
||||
services.AddSingleton<XAppConfiguration> (appConfiguration);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add Required OperationFilters and Authorization Fields to Swagger Options
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="xmlFilePath"></param>
|
||||
/// <param name="addRequiredXPoweredFilter"></param>
|
||||
/// <param name="addXTokenAuthorization"></param>
|
||||
public static void AddXSwaggerGenOptions (
|
||||
this SwaggerGenOptions source,
|
||||
string xmlFilePath = null,
|
||||
bool addRequiredXPoweredFilter = true,
|
||||
bool addXTokenAuthorization = true
|
||||
) {
|
||||
//
|
||||
if (source.IsNull ()) {
|
||||
source = new SwaggerGenOptions ();
|
||||
}
|
||||
|
||||
//
|
||||
// Add Xml File Path ...
|
||||
if (!xmlFilePath.IsNullOrEmpty ()) {
|
||||
source.IncludeXmlComments (xmlFilePath);
|
||||
}
|
||||
|
||||
//
|
||||
// Handle RequireXPowered Filter ...
|
||||
if (addRequiredXPoweredFilter) {
|
||||
source.OperationFilter<RequireXPoweredOperationFilter> ();
|
||||
}
|
||||
|
||||
//
|
||||
// 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<string> ()
|
||||
}
|
||||
});
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region RefreshToken ...
|
||||
//
|
||||
source.AddSecurityDefinition (nameof (XAuthorization.RefreshToken), new OpenApiSecurityScheme {
|
||||
In = ParameterLocation.Header,
|
||||
Description = "refresh token",
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
Name = nameof (XAuthorization.RefreshToken)
|
||||
});
|
||||
|
||||
//
|
||||
source.AddSecurityRequirement (new OpenApiSecurityRequirement {
|
||||
{
|
||||
new OpenApiSecurityScheme {
|
||||
Reference = new OpenApiReference {
|
||||
Id = nameof (XAuthorization.RefreshToken),
|
||||
Type = ReferenceType.SecurityScheme
|
||||
}
|
||||
}, Array.Empty<string> ()
|
||||
}
|
||||
});
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region ExpiresAt ...
|
||||
//
|
||||
source.AddSecurityDefinition (nameof (XAuthorization.ExpiresAt), new OpenApiSecurityScheme {
|
||||
In = ParameterLocation.Header,
|
||||
Description = "expires at",
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
Name = nameof (XAuthorization.ExpiresAt)
|
||||
});
|
||||
|
||||
//
|
||||
source.AddSecurityRequirement (new OpenApiSecurityRequirement {
|
||||
{
|
||||
new OpenApiSecurityScheme {
|
||||
Reference = new OpenApiReference {
|
||||
Id = nameof (XAuthorization.ExpiresAt),
|
||||
Type = ReferenceType.SecurityScheme
|
||||
}
|
||||
}, Array.Empty<string> ()
|
||||
}
|
||||
});
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register Swagger
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="configuration"></param>
|
||||
/// <param name="settings"></param>
|
||||
/// <param name="xmlFilePath"></param>
|
||||
/// <param name="addRequiredXPoweredFilter"></param>
|
||||
/// <param name="addXTokenAuthorization"></param>
|
||||
public static void AddXSwagger (
|
||||
this IServiceCollection source,
|
||||
IConfiguration configuration,
|
||||
SwaggerGenOptions settings = null,
|
||||
string xmlFilePath = null,
|
||||
bool addRequiredXPoweredFilter = true,
|
||||
bool addXTokenAuthorization = true
|
||||
) {
|
||||
//
|
||||
var xSwaggerConfig = configuration.GetXSwaggerConfiguration ();
|
||||
if (xSwaggerConfig.IsNull ()) {
|
||||
xSwaggerConfig = new XSwaggerConfiguration ();
|
||||
}
|
||||
|
||||
//
|
||||
#region Prepare SwaggerGenOptions ...
|
||||
if (settings.IsNull ()) {
|
||||
settings = new SwaggerGenOptions ();
|
||||
}
|
||||
settings.AddXSwaggerGenOptions (
|
||||
xmlFilePath: xmlFilePath,
|
||||
addRequiredXPoweredFilter: addRequiredXPoweredFilter,
|
||||
addXTokenAuthorization: addXTokenAuthorization
|
||||
);
|
||||
#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);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use Sagger
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="options"></param>
|
||||
public static void UseXSwagger (
|
||||
this IApplicationBuilder source,
|
||||
SwaggerUIOptions options = null
|
||||
) {
|
||||
//
|
||||
source.UseSwagger ();
|
||||
|
||||
//
|
||||
if (options.IsNull ()) {
|
||||
source.UseSwaggerUI ();
|
||||
} else {
|
||||
source.UseSwaggerUI (options: options);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add Cross Origin Resource Sharings
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="allowedOrigins"></param>
|
||||
public static void AddXCors (
|
||||
this IServiceCollection source,
|
||||
IEnumerable<string> 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 ("*");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use X Registered Cross Origin Resource Sharings
|
||||
/// </summary>
|
||||
/// <param name="sources"></param>
|
||||
public static void UseXCors (this IApplicationBuilder sources) {
|
||||
//
|
||||
sources.UseCors (XPolicy.AllowedOrigins);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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<T> (this string source) {
|
||||
return (T) Enum.Parse (typeof (T), source);
|
||||
}
|
||||
|
||||
public static void Iterate<T> (this IEnumerator<T> source, Action<T> action) {
|
||||
//
|
||||
while (source.MoveNext ()) {
|
||||
//
|
||||
var current = source.Current;
|
||||
action (current);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using System;
|
||||
using xExceptions.Constants;
|
||||
using xExceptions.Models;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
/// <summary>
|
||||
/// this is an extension pack for Exceptions
|
||||
/// </summary>
|
||||
public static partial class ExceptionExtensions {
|
||||
|
||||
/// <summary>
|
||||
/// determines an string contains an XError content or not
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// deserialize an string to to XError class instance
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static XError ToXError (this string source) {
|
||||
//
|
||||
if (source.IsNullOrEmpty ()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
try {
|
||||
//
|
||||
var err = source.FromJSON<XError> ();
|
||||
|
||||
//
|
||||
// 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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert an XError instance to an Exception
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
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 ();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert an Exception to corresponding XError Object
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static XError FromException (this Exception source) {
|
||||
//
|
||||
if (source == null || source.Message.IsNullOrEmpty ()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
return source.Message.ToXError ();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add Content to Contentable XException member and return XError Object
|
||||
/// </summary>
|
||||
/// <param name="exception"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static XError AddContentToError (this XException exception, string value) {
|
||||
//
|
||||
var xError = exception.ToXError ();
|
||||
xError.Message = string.Format (xError.Message, value);
|
||||
|
||||
//
|
||||
return xError;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add Content to Contentable XException member and return Exception Object
|
||||
/// </summary>
|
||||
/// <param name="exception"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static Exception AddContentToException (this XException exception, string value) {
|
||||
//
|
||||
var xError = exception.ToXError ();
|
||||
xError.Message = string.Format (xError.Message, value);
|
||||
|
||||
//
|
||||
return xError.ToException ();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throw Specific Exception ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="content"></param>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using xCommons.Configurations;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using xCommons.Configurations;
|
||||
using xCommons.Constants;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
public static partial class IConfigurationExtensions {
|
||||
/// <summary>
|
||||
/// Retrieve AppConfiguration from Configurations
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
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<IEnumerable<string>> (),
|
||||
DefaultLanguage = source[nameof (XAppConfiguration.DefaultLanguage)],
|
||||
MessageResourceTitles = xMessageResourceTitlesConfigSection
|
||||
.Get<XMessageResourceTitles> ()
|
||||
};
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve Swagger Configurations
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static XSwaggerConfiguration GetXSwaggerConfiguration (this IConfiguration source) {
|
||||
//
|
||||
var xSwaggerConfigSection = source
|
||||
.GetSection (ConfigurationNodeNames.SWAGGER_NODE);
|
||||
return xSwaggerConfigSection.Get<XSwaggerConfiguration> ();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
public static partial class ModelExtensions {
|
||||
/// <summary>
|
||||
/// Update an Instance of a Typed Object with Data Provided by another Instance of Typed Object
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="updateWith"></param>
|
||||
/// <param name="propertyWhiteList"></param>
|
||||
/// <param name="propertyBlackList"></param>
|
||||
/// <param name="propertyValueProviders"></param>
|
||||
/// <param name="updateWithNullOrEmptyValues"></param>
|
||||
/// <param name="throwExceptionOnFails"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="D"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static T UpdateData<T, D> (
|
||||
this T source,
|
||||
D updateWith,
|
||||
ICollection<string> propertyWhiteList = null,
|
||||
ICollection<string> propertyBlackList = null,
|
||||
ICollection<KeyValuePair<string, Func<D, object>>> propertyValueProviders = null,
|
||||
bool updateWithNullOrEmptyValues = false,
|
||||
bool throwExceptionOnFails = false
|
||||
)
|
||||
where T : class
|
||||
where D : class {
|
||||
//
|
||||
var hasWhiteList = propertyWhiteList.HasChild<string> ();
|
||||
var hasBlackList = propertyBlackList.HasChild<string> ();
|
||||
var hasValueProvider = propertyValueProviders.HasChild<KeyValuePair<string, Func<D, object>>> ();
|
||||
|
||||
//
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Check two Instance of Typed Object Values are Same or not
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="dest"></param>
|
||||
/// <param name="propertyWhiteList"></param>
|
||||
/// <param name="propertyBlackList"></param>
|
||||
/// <param name="throwExceptionOnFails"></param>
|
||||
/// <param name="propertyValueCheckers"></param>
|
||||
/// /// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="D"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static bool IsSameContent<T, D> (
|
||||
this T source,
|
||||
D dest,
|
||||
ICollection<string> propertyWhiteList = null,
|
||||
ICollection<string> propertyBlackList = null,
|
||||
ICollection<KeyValuePair<string, Func<T, D, bool>>> propertyValueCheckers = null,
|
||||
bool throwExceptionOnFails = false
|
||||
)
|
||||
where T : class
|
||||
where D : class {
|
||||
//
|
||||
var hasWhiteList = propertyWhiteList.HasChild<string> ();
|
||||
var hasBlackList = propertyBlackList.HasChild<string> ();
|
||||
var hasCheckerProvider = propertyValueCheckers.HasChild<KeyValuePair<string, Func<T, D, bool>>> ();
|
||||
|
||||
//
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check specific type is Collection Type or not
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve a Property Value in Generic
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static string GetPropValues<T> (this T item)
|
||||
where T : class {
|
||||
//
|
||||
var props = item.GetType ().GetProperties ();
|
||||
var vals = props.Select (p => p.GetValue (item));
|
||||
|
||||
//
|
||||
return vals.ToJSON ();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check a Property Value Contains specific value
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static bool PropValuesContains<T> (this T item, string value)
|
||||
where T : class {
|
||||
//
|
||||
return item.GetPropValues ()
|
||||
.ToNormalString ()
|
||||
.Contains (value
|
||||
.ToNormalString ());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate Default Column Map
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static IDictionary<string, Expression<Func<T, object>>> GetDefaultColumnsMap<T> (this T item)
|
||||
where T : class {
|
||||
//
|
||||
if (item.IsNull ()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
var result = new Dictionary<string, Expression<Func<T, object>>> ();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate Default Column Map
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static IDictionary<string, string> GetPropValuesDictionary<T> (this T item)
|
||||
where T : class {
|
||||
//
|
||||
if (item.IsNull ()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
var result = new Dictionary<string, string> ();
|
||||
var props = item.GetType ().GetProperties ();
|
||||
|
||||
//
|
||||
foreach (var prop in props) {
|
||||
result.Add (prop.Name, prop.GetValue (item).ToJSON ());
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using xCommons.Helpers;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
public static class ServiceProviderExtensions {
|
||||
/// <summary>
|
||||
/// Get all registered <see cref="ServiceDescriptor"/>
|
||||
/// </summary>
|
||||
/// <param name="provider"></param>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<Type, ServiceDescriptor> GetAllServiceDescriptors (this IServiceProvider provider) {
|
||||
//
|
||||
if (provider is ServiceProvider serviceProvider) {
|
||||
//
|
||||
var result = new Dictionary<Type, ServiceDescriptor> ();
|
||||
|
||||
//
|
||||
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!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.IO;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
public static partial class XHttpContextExtensions {
|
||||
/// <summary>
|
||||
/// Convert IFormFile to Bytes Array
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using xCommons.Middlewares;
|
||||
|
||||
namespace xCommons.Extensions
|
||||
{
|
||||
public static class XMiddlewareExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Use XRequestLogger Middleware for log Requests ...
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
public static void UseXRequestLogger(this IApplicationBuilder app) {
|
||||
app.UseMiddleware<XRequestLogger>();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user