GR.Core Module¶
Description¶
Core is a module that contains interfaces, abstract classes, extensions, validations, helpers, it is the module that the other modules should extend
Install¶
- Package manager
Install-Package GR.Core -Version 1.9.3
- .net cli
dotnet add package GR.Core --version 1.9.3
- Package reference
<PackageReference Include="GR.Core" Version="1.9.3" />
- Packet cli
paket add GR.Core --version 1.9.3
Module usage¶
graph LR
A[GR.Core] -- extend --> B(Module abstraction 1)
A -- extend --> C(Module abstraction 2)
A -- extend --> R(Module abstraction 3)
B --> D{Application}
C --> D
R --> D
Abstractions¶
IBackgroundTaskQueue
- interface that is used for push tasks to be executed in backgroundIBaseModel
- interface that has all BaseModel fields, can be used on classes that use inheritance from another classes that BaseModelIBase<T>
- represent IBaseModel with genric type of entry idIDbContext
- this interface is the database context of module, each DbContext must implement this interfaceISender
- represent a generic sender of messages, it can send anything, it depend on registered providersIWritableOptions
- custom implementation of IOptionsSnapshot, has a method to update app settings configurations
BaseModel class¶
BaseModel is the base class for entities that use EF Core Structure of this class can be found below
public abstract class BaseModel : IBase<Guid>
{
/// <summary>
/// Constructor. Initialize object with default values. A unique Id, Creation time and set IsDeleted to false
/// </summary>
protected BaseModel()
{
Id = Guid.NewGuid();
Created = DateTime.UtcNow;
Changed = DateTime.UtcNow;
}
/// <summary>Stores Id of the Object</summary>
public Guid Id { get; set; }
/// <inheritdoc />
/// <summary>Stores Id of the User that created the object</summary>
public virtual string Author { get; set; }
/// <inheritdoc />
/// <summary>Stores the time when object was created</summary>
public DateTime Created { get; set; }
/// <inheritdoc />
/// <summary>
/// Stores the Id of the User that modified the object. Nullable
/// </summary>
public virtual string ModifiedBy { get; set; }
/// <inheritdoc />
/// <summary>Stores the time when object was modified. Nullable</summary>
public DateTime Changed { get; set; }
/// <inheritdoc />
/// <summary>
/// Stores state of the Object. True if object is deleted and false otherwise
/// </summary>
public virtual bool IsDeleted { get; set; }
/// <inheritdoc />
/// <summary>
/// Version of data
/// </summary>
public virtual int Version { get; set; }
/// <inheritdoc />
/// <summary>
/// Tenant id
/// </summary>
public virtual Guid? TenantId { get; set; }
/// <summary>
/// Disable audit tracking
/// This only work on current instance,
/// The true value ignore save a new version on audit
/// </summary>
[JsonIgnore]
[NotMapped]
public virtual bool DisableAuditTracking { get; set; }
/// <summary>
/// Get props name
/// </summary>
/// <returns></returns>
public static IEnumerable<string> GetPropsName()
{
return typeof(BaseModel).GetProperties().Select(x => x.Name).ToList();
}
}
Attributes¶
Events¶
Exceptions¶
Extensions¶
- AssemblyExtensions
GetTypeFromAssembliesByClassName
- get type by name from all assembliesGetAutoMapperProfilesFromAllAssemblies
- get all AutoMapper mappers from all assemblies
- BoolExtensions
Negate
- negate boolean value
- CollectionExtensions
AddRange
- add range items in HashSet, ICollectionReplace
- replace item in generic listDistinctBy
- get items distinct by a object proprietyJoin
- join a list of stringsIsLast
- return true if item is the last in collectionIsFirst
- check if is first itemGetDifferences
- get differencesfrom 2 listsContainsAny
- check if list is contained in anotherAnyStartWith
- check if list has any items that start with a stringToKeyValuePair
- transform to KeyValuePair dictionaryToObservableCollection
- transform collection to an observableRandomize
- randomize items in a collectionTranspose
- transpose collectionToCollection
- IEnumerable to CollectionCombinations
- Returns all combinations of a chosen amount of selected elements in the sequence.
- CryptoExtensions
EncryptWithRSA
- Encrypt a string using the supplied key. Encoding is done using RSA encryption.DecryptWithRSA
- Decrypt a string using the supplied key. Decoding is done using RSA encryption.
- DateTimeExtensions
EndOfDay
- Get end of dayStartOfDay
- Start of dayDayIndex
- Day of weekIntersects
- Intersects datesIsWeekend
- Check if is weekendAge
- Get the age of personIsLeapYear
- Returns whether or not a DateTime is during a leap year.DisplayTextDate
- Display text dateCreatedThisWeek
- query to get items created this weekCreatedThisMonth
- query to get items created this monthCreatedToday
- query to get items created todayCreatedOneHour
- query to get items created one hourCreatedThisYear
- query to get items created this yearToTimeStamp
- Date to time stamp
Helpers¶
ZipHelper
ZipHelper is a helper that use ZipArchive and create an archive from a Dictionary<string, MemoryStream> , first arg is name of file and the second is stream of file, the result is a stream. Example:var items = new Dictionary<string, MemoryStream>(); MemoryStream archive = ZipHelper.CreateZipArchive(items);
Example of return File in controller:
return File(archive, ContentType.ApplicationZip, "archive_name");
EncryptHelper
This helper is created for encrypt and decrypt anything , encryption is due grace a pass phrase. Example:
//Encryption
var serializedCard = cards.SerializeAsJson();
var key = GenerateKey(user);
var encrypted = EncryptHelper.Encrypt(serializedCard, key);
//Decryption
var serializedString = EncryptHelper.Decrypt(cardHash, key);
var cards = serializedString.Deserialize<IEnumerable<CreditCardPayViewModel>>();
MimeTypes
Contains all popular mime types, example of a record:
{".ez", "application/andrew-inset"}
MimeMapping
This module maps document extensions to Content Mime Type. Example:
var getType = MimeMapping.GetMimeMapping(fileName);
ModelBinders
ModelBinders is a .net core feature that allow us to map property on HttpRequest serialization, for more info check microsoft docs
GearBinder<TValue>
- Custom generic binder Example:
public class ProductsFilterRequest
{
public virtual int Page { get; set; } = 1;
public virtual int PerPage { get; set; } = 10;
[ModelBinder(BinderType = typeof(GearBinder<IEnumerable<CommerceFilter>>))]
public virtual IEnumerable<CommerceFilter> Filters { get; set; }
}
GearDictionaryBinder<TValue>
- custom generic binder for dictionary
Singleton<T, TResolver>
- is an implementation of singleton pattern that allow to use it in a short mode, if value is null, it create automatically a default constructor instance. Example:
public static IWindsorContainer Container => Singleton<IWindsorContainer, WindsorContainer>.Instance;
Arg
validator is a helper that throw an exception if argument not correspond to criteria, list of methods:
- NotNull
- NotNullOrEmpty
- InRange
- LessThan
- LessThanOrEqualTo
- GreaterThan
- GreaterThanOrEqualTo Example:
public static void Register(string name, Type type)
{
Arg.NotNullOrEmpty(name, nameof(Register));
Arg.NotNull(type, nameof(Register));
Storage.TryAdd(name, type);
}
EnumHelper
It has a method to get the description value from attribute of enum: Example:
var result = await _service.DeleteReportAsync(id);
result.Result = ResultMessagesEnum.DeleteSuccess.GetEnumDescription();
ExceptionHandler
it contains extensions for enumto transform to ResultModel Example:
ResultMessagesEnum.FolderNotSaved.ToErrorModel<Guid>();
GearPolicy
- is a helper that execute and retry task in case of an error, it use Policy from Poly library Example:
//if the first execution return an error, it retry 3 times with time delay
var depositRequest = await GearPolicy.ExecuteAndRetry(async ()
=> await _coinbaseProClient.DepositsService.DepositFundsAsync(paymentMethod, amount, Currency.USD));
IoC
- is an inversion of control helper that extend Castle Windsor Container Available methods:
void RegisterService<TAbstraction>(string providerName, Type provider) where TAbstraction : class
void RegisterSingletonService<TAbstraction>(string providerName, Type provider) where TAbstraction : class
void RegisterTransientService<TAbstraction>(string providerName, Type provider) where TAbstraction : class
void RegisterTransientService<TAbstraction, TImplementation>() where TImplementation : class, TAbstraction where TAbstraction : class
void RegisterTransientService<TAbstraction, TImplementation>(TImplementation instance) where TImplementation : class, TAbstraction where TAbstraction : class
void RegisterTransientService<TAbstraction, TImplementation>(string providerName) where TImplementation : class, TAbstraction where TAbstraction : class
void RegisterSingletonService<TAbstraction, TImplementation>() where TImplementation : class, TAbstraction where TAbstraction : class
void RegisterSingletonService<TService>() where TService : class
void RegisterServiceCollection(Dictionary<Type, Type> toMapCollection)
void RegisterScopedService<TAbstraction, TImplementation>(TImplementation instance) where TImplementation : class, TAbstraction where TAbstraction : class
void RegisterScopedService<TAbstraction, TImplementation>() where TImplementation : class, TAbstraction where TAbstraction : class
void RegisterService<TAbstraction, TImplementation>(Func<ComponentRegistration<TAbstraction>, ComponentRegistration<TAbstraction>> configuration)
bool IsServiceRegistered<TService>()
bool IsServiceRegistered(string provider)
TService Resolve<TService>()
TService ResolveNonRequired<TService>()
TService ResolveNonRequired<TService>(string key)
T Resolve<T>(string key)
object Resolve(Type type)
Example:
// register IAuditManager audit manager implementation
IoC.RegisterTransientService<IAuditManager, TManager>();
// Resolve IConfiguration instance
var configurator = IoC.Resolve<IConfiguration>();
JsonParser
- is a helper for read json files Available methods:
T ReadArrayDataFromJsonFile<T>(string filePath) where T : class
IEnumerable<dynamic> ReadDataListFromJsonWithTypeParameter(string filePath, Type entity)
T ReadObjectDataFromJsonFile<T>(string filePath) where T : class
Example:
var path = Path.Combine(AppContext.BaseDirectory, "Configuration/WidgetGroups.json");
var items = JsonParser.ReadArrayDataFromJsonFile<ICollection<WidgetGroup>>(path);
ObjectIdentificationHelper
- is a helper for check object type Available methods:
bool IsList(this object o)
bool IsDictionary(this object o)
bool IsInt(this string sVal)
bool IsNumeric(this string sVal)
Example:
if (!jObject.ContainsKey(_section))
{
jObject.Add(sectionObject.IsList()
? new JProperty(_section, new JArray(JArray.Parse(JsonConvert.SerializeObject(sectionObject))))
: new JProperty(_section, new JObject(JObject.Parse(JsonConvert.SerializeObject(sectionObject)))));
}
else
{
if (sectionObject.IsList())
jObject[_section] = JArray.Parse(JsonConvert.SerializeObject(sectionObject));
else
jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
}
ResourceProvider
- get app settings file path, in dependency of app environment: [Development, Production, Staging] Example:
//The result can be appsettings.json
ResourceProvider.AppSettingsFilepath(hostingEnvironment))
ResultModel<T>
- is a common return type for api and methods, it allow easy to check status of response and read the errors, it also contains helpers that allow easy understand the failure. Examples:
public static async Task<ResultModel> UploadAsync(this IFormFile file, string filePath)
{
var result = new ResultModel();
try
{
using (var stream = File.Create(filePath))
{
await file.CopyToAsync(stream);
}
result.IsSuccess = true;
}
catch (Exception e)
{
result.AddError(e.Message);
}
return result;
}
Services¶
WritableOptions<T>
- default implementation of IWritableOptions
Global settings¶
GearApplication instance¶
Mappers¶
AutoMapper¶
AutoMapper is supported directy from Core, created profiles are automatically scanned and registered, only that is need is to create your profile class. Example of profile:
public class OrganizationProfile : Profile
{
public OrganizationProfile()
{
CreateMap<Foo, FooDto>();
// Use CreateMap... Etc.. here (Profile methods are the same as configuration methods)
}
}
Mapster¶
Mapster is a library that support mapping type to another type, it has extensions for object type, sample example:
var user= new User();
var ldapUser = user.Adapt<LdapUser>();
More docs coming soon