diff --git a/src/EasMe.Authorization/EasMe.Authorization.csproj b/src/EasMe.Authorization/EasMe.Authorization.csproj index 21534533..13b07394 100644 --- a/src/EasMe.Authorization/EasMe.Authorization.csproj +++ b/src/EasMe.Authorization/EasMe.Authorization.csproj @@ -1,25 +1,25 @@ - - net6.0 - enable - enable - C:\Users\kkass\source\build\easme - 1.0.0 - 2.0.0 - EasMe.Authorization - bberka - AspNetCore authorization extender library. Easily manage and apply required roles for desired endpoints. - https://github.com/bberka/EasMe/tree/master - https://github.com/bberka/EasMe/blob/master/LICENSE.txt - https://github.com/bberka/EasMe/tree/master + + net6.0 + enable + enable + C:\Users\kkass\source\build\easme + 1.0.0 + 2.0.0 + EasMe.Authorization + bberka + AspNetCore authorization extender library. Easily manage and apply required roles for desired endpoints. + https://github.com/bberka/EasMe/tree/master + https://github.com/bberka/EasMe/blob/master/LICENSE.txt + https://github.com/bberka/EasMe/tree/master - + - - - - - + + + + + diff --git a/src/EasMe.Authorization/Enums.cs b/src/EasMe.Authorization/Enums.cs index 1a66b151..c1df61e7 100644 --- a/src/EasMe.Authorization/Enums.cs +++ b/src/EasMe.Authorization/Enums.cs @@ -1,6 +1,7 @@ namespace EasMe.Authorization; -public enum HttpMethod { +public enum HttpMethod +{ GET, POST, PUT, @@ -12,12 +13,14 @@ public enum HttpMethod { TRACE } -public enum AuthorizationType { +public enum AuthorizationType +{ HttpMethodAuthorization, EndpointAuthorization } -public static class EasMeClaimType { +public static class EasMeClaimType +{ /// /// Claim Type for initializing User authorization in order to use . ///
diff --git a/src/EasMe.Authorization/HasActionPermissionAttribute.cs b/src/EasMe.Authorization/HasActionPermissionAttribute.cs index 5f163d3c..63513d14 100644 --- a/src/EasMe.Authorization/HasActionPermissionAttribute.cs +++ b/src/EasMe.Authorization/HasActionPermissionAttribute.cs @@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -using Newtonsoft.Json; namespace EasMe.Authorization; @@ -22,7 +21,8 @@ namespace EasMe.Authorization; /// claims. /// ///
-public class HasActionPermissionAttribute : ActionFilterAttribute { +public class HasActionPermissionAttribute : ActionFilterAttribute +{ private readonly string _actionCode; public HasActionPermissionAttribute(object actionCode) { @@ -30,12 +30,13 @@ public HasActionPermissionAttribute(object actionCode) { if (string.IsNullOrEmpty(_actionCode)) throw new ArgumentNullException(nameof(_actionCode)); } + public HasActionPermissionAttribute(string actionCode) { _actionCode = actionCode; if (string.IsNullOrEmpty(_actionCode)) throw new ArgumentNullException(nameof(_actionCode)); } - + public override void OnActionExecuting(ActionExecutingContext actionExecutingContext) { if (actionExecutingContext.HttpContext.User.Identity is not { IsAuthenticated: true }) { Trace.WriteLine("Not authenticated"); @@ -51,7 +52,7 @@ public override void OnActionExecuting(ActionExecutingContext actionExecutingCon Trace.WriteLine(endPointPermissionString); var permList = InternalHelper.SplitPermissions(endPointPermissionString); - Trace.WriteLine("Permission List: " + string.Join(",",permList)); + Trace.WriteLine("Permission List: " + string.Join(",", permList)); if (permList.Length == 0) { actionExecutingContext.Result = new ForbidResult(); return; diff --git a/src/EasMe.Authorization/HttpMethodAuthorizationMiddleware.cs b/src/EasMe.Authorization/HttpMethodAuthorizationMiddleware.cs index b6c3bfab..c28afde7 100644 --- a/src/EasMe.Authorization/HttpMethodAuthorizationMiddleware.cs +++ b/src/EasMe.Authorization/HttpMethodAuthorizationMiddleware.cs @@ -6,7 +6,8 @@ namespace EasMe.Authorization; /// /// Is to authorize every user by permissions /// -public class HttpMethodAuthorizationMiddleware { +public class HttpMethodAuthorizationMiddleware +{ private readonly RequestDelegate _next; public HttpMethodAuthorizationMiddleware(RequestDelegate next) { diff --git a/src/EasMe.Authorization/InternalHelper.cs b/src/EasMe.Authorization/InternalHelper.cs index 12c84344..b67fd828 100644 --- a/src/EasMe.Authorization/InternalHelper.cs +++ b/src/EasMe.Authorization/InternalHelper.cs @@ -1,6 +1,7 @@ namespace EasMe.Authorization; -internal static class InternalHelper { +internal static class InternalHelper +{ internal static HttpMethod? GetHttpMethod(string permission) { var parse = Enum.TryParse(typeof(HttpMethod), permission, out var obj); if (!parse) return null; diff --git a/src/EasMe.Authorization/README.md b/src/EasMe.Authorization/README.md index 2fd22062..a2a0219d 100644 --- a/src/EasMe.Authorization/README.md +++ b/src/EasMe.Authorization/README.md @@ -1,19 +1,23 @@ # EasMe.Authorization + Permission Authorization helper for AsNetCore.Mvc. Uses base HttpContext.User authentication and verifies permissions initialized by server ### Table of Contents + - Filters > HasPermissionAttribute - Middlewares > HttpMethodAuthorizationMiddleware - AuthorizationHelper - Enums ### HasPermissionAttribute + 1. Add "EasMeClaimType.EndPointPermissions" to User claims 2. Set value as list of permissions separeted by "," 3. Add HasPermission("PermissionName") to Controller or Endpoint Action ### HttpMethodAuthorizationMiddleware + 1. Add "EasMeClaimType.HttpMethodPermissions" to User claims 2. Set value as list of permissions separeted by "," 3. Get permission values from "EasMe.Authorization.HttpMethod" enum \ No newline at end of file diff --git a/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.csproj.CoreCompileInputs.cache b/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.csproj.CoreCompileInputs.cache index eca815e3..381b1ad8 100644 --- a/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.csproj.CoreCompileInputs.cache +++ b/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -4fafd1b16d689fcdf2c18739c1f9c50f9f85f4fa +aeedc4284f04e07a61c4999a2ba39b935d430ab2 diff --git a/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.dll b/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.dll index 4100d47f..eb73ee6c 100644 Binary files a/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.dll and b/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.dll differ diff --git a/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.pdb b/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.pdb index 0fb5bf91..2c5f21f9 100644 Binary files a/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.pdb and b/src/EasMe.Authorization/obj/Release/net6.0/EasMe.Authorization.pdb differ diff --git a/src/EasMe.Authorization/obj/Release/net6.0/ref/EasMe.Authorization.dll b/src/EasMe.Authorization/obj/Release/net6.0/ref/EasMe.Authorization.dll index 3a37aba5..e272c495 100644 Binary files a/src/EasMe.Authorization/obj/Release/net6.0/ref/EasMe.Authorization.dll and b/src/EasMe.Authorization/obj/Release/net6.0/ref/EasMe.Authorization.dll differ diff --git a/src/EasMe.Authorization/obj/Release/net6.0/refint/EasMe.Authorization.dll b/src/EasMe.Authorization/obj/Release/net6.0/refint/EasMe.Authorization.dll index 3a37aba5..e272c495 100644 Binary files a/src/EasMe.Authorization/obj/Release/net6.0/refint/EasMe.Authorization.dll and b/src/EasMe.Authorization/obj/Release/net6.0/refint/EasMe.Authorization.dll differ diff --git a/src/EasMe.Box/Box.cs b/src/EasMe.Box/Box.cs index 76a26bd4..2665d12d 100644 --- a/src/EasMe.Box/Box.cs +++ b/src/EasMe.Box/Box.cs @@ -1,11 +1,13 @@ using System.Windows.Forms; -namespace EasMe.MessageBox { - public static class Box { +namespace EasMe.MessageBox +{ + public static class Box + { public static bool Confirm(string Message) //Shows a confirmation box and returns the result taken from user { if (DialogResult.Yes == System.Windows.Forms.MessageBox.Show(Message, "Confirmation", - MessageBoxButtons.YesNo, MessageBoxIcon.Question)) + MessageBoxButtons.YesNo, MessageBoxIcon.Question)) return true; return false; } @@ -23,7 +25,7 @@ public static void Warn(string Message) //Shows a warning message box with only public static void Info(string Message) //Shows an information message box with only OK buttong { System.Windows.Forms.MessageBox.Show(Message, "Information", MessageBoxButtons.OK, - MessageBoxIcon.Information); + MessageBoxIcon.Information); } public static void Error(string Message) //Shows an Error message box with only OK buttong diff --git a/src/EasMe.Box/EasMe.Box.csproj b/src/EasMe.Box/EasMe.Box.csproj index fdd5b07d..13485f40 100644 --- a/src/EasMe.Box/EasMe.Box.csproj +++ b/src/EasMe.Box/EasMe.Box.csproj @@ -1,46 +1,46 @@  - - - Debug - AnyCPU - {A34014DE-E353-44E7-874F-CFD7E3F16137} - Library - Properties - EasMe.MessageBox - EasMe.MessageBox - v4.8 - 512 - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\bin\ - TRACE - prompt - 4 - - - - - - - - - - - - - - + + + Debug + AnyCPU + {A34014DE-E353-44E7-874F-CFD7E3F16137} + Library + Properties + EasMe.MessageBox + EasMe.MessageBox + v4.8 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + ..\bin\ + TRACE + prompt + 4 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/EasMe.EntityFrameworkCore/BaseEntity.cs b/src/EasMe.EntityFrameworkCore/BaseEntity.cs index aff7e1dc..e31fbde3 100644 --- a/src/EasMe.EntityFrameworkCore/BaseEntity.cs +++ b/src/EasMe.EntityFrameworkCore/BaseEntity.cs @@ -2,7 +2,8 @@ namespace EasMe.EntityFrameworkCore; -public abstract class BaseEntity : IBaseEntity { +public abstract class BaseEntity : IBaseEntity +{ protected BaseEntity(Guid guid) { Id = guid; } @@ -12,7 +13,8 @@ protected BaseEntity() { public DateTime RegisterDate { get; set; } = DateTime.Now; - [Key] public Guid Id { get; set; } + [Key] + public Guid Id { get; set; } public bool Equals(BaseEntity? other) { if (other is null) return false; diff --git a/src/EasMe.EntityFrameworkCore/EasMe.EntityFrameworkCore.csproj b/src/EasMe.EntityFrameworkCore/EasMe.EntityFrameworkCore.csproj index afc9f8e8..7ccfac42 100644 --- a/src/EasMe.EntityFrameworkCore/EasMe.EntityFrameworkCore.csproj +++ b/src/EasMe.EntityFrameworkCore/EasMe.EntityFrameworkCore.csproj @@ -1,25 +1,25 @@ - - net6.0 - enable - enable - C:\Users\kkass\source\build\easme - 2.0.0 - 2.0.0 - true - EasMe.EntityFrameworkCore - EntityFrameworkCore extender library with built in repository pattern interfaces and more. - https://github.com/bberka/EasMe/tree/master - https://github.com/bberka/EasMe/blob/master/LICENSE.txt - https://github.com/bberka/EasMe/tree/master - bberka + + net6.0 + enable + enable + C:\Users\kkass\source\build\easme + 2.0.0 + 2.0.0 + true + EasMe.EntityFrameworkCore + EntityFrameworkCore extender library with built in repository pattern interfaces and more. + https://github.com/bberka/EasMe/tree/master + https://github.com/bberka/EasMe/blob/master/LICENSE.txt + https://github.com/bberka/EasMe/tree/master + bberka - + - - - + + + diff --git a/src/EasMe.EntityFrameworkCore/EntityRepositoryBase.cs b/src/EasMe.EntityFrameworkCore/EntityRepositoryBase.cs index 782dd7cd..afa99534 100644 --- a/src/EasMe.EntityFrameworkCore/EntityRepositoryBase.cs +++ b/src/EasMe.EntityFrameworkCore/EntityRepositoryBase.cs @@ -10,7 +10,8 @@ namespace EasMe.EntityFrameworkCore; /// public class EntityRepositoryBase : IEntityRepository where TEntity : class, IEntity, new() - where TContext : DbContext, new() { + where TContext : DbContext, new() +{ private readonly TContext _dbContext; private readonly DbSet _dbSet; @@ -21,14 +22,14 @@ public EntityRepositoryBase(TContext dbContext) { public IQueryable Get(Expression>? filter = null) { return filter == null - ? _dbSet - : _dbSet.Where(filter); + ? _dbSet + : _dbSet.Where(filter); } public List GetList(Expression>? filter = null) { return filter == null - ? _dbSet.ToList() - : _dbSet.Where(filter).ToList(); + ? _dbSet.ToList() + : _dbSet.Where(filter).ToList(); } public TEntity? GetFirstOrDefault(Expression> filter) { diff --git a/src/EasMe.EntityFrameworkCore/GenericRepository.cs b/src/EasMe.EntityFrameworkCore/GenericRepository.cs index 51f4f2e6..1d030fd3 100644 --- a/src/EasMe.EntityFrameworkCore/GenericRepository.cs +++ b/src/EasMe.EntityFrameworkCore/GenericRepository.cs @@ -5,7 +5,8 @@ namespace EasMe.EntityFrameworkCore; public class GenericRepository : IGenericRepository where TEntity : class, IEntity - where TContext : DbContext, new() { + where TContext : DbContext, new() +{ private readonly TContext _dbContext; public GenericRepository(TContext context) { @@ -75,9 +76,9 @@ public virtual IQueryable GetSelect( } public TResult? GetFirstOrDefaultSelect(Expression> select, - Expression>? filter = null, - Func, IOrderedQueryable>? orderBy = null, - params string[] includeExpressions) { + Expression>? filter = null, + Func, IOrderedQueryable>? orderBy = null, + params string[] includeExpressions) { var query = Table.AsQueryable(); foreach (var includeProperty in includeExpressions) query = query.Include(includeProperty); @@ -88,14 +89,14 @@ public virtual IQueryable GetSelect( } public virtual IQueryable Get(Expression>? filter = null, - params string[] includeExpressions) { + params string[] includeExpressions) { return GetOrdered(filter, null, includeExpressions); } public virtual IQueryable GetPaging(int page, int pageSize = 15, - Expression>? filter = null, - Func, IOrderedQueryable>? orderBy = null, - params string[] includeExpressions) { + Expression>? filter = null, + Func, IOrderedQueryable>? orderBy = null, + params string[] includeExpressions) { var query = Table.AsQueryable(); if (filter != null) query = query.Where(filter); @@ -106,8 +107,8 @@ public virtual IQueryable GetPaging(int page, int pageSize = 15, if (orderBy != null) query = orderBy(query); var skipItemIndex = (page - 1) * pageSize; return query - .Skip(skipItemIndex) - .Take(pageSize); + .Skip(skipItemIndex) + .Take(pageSize); } diff --git a/src/EasMe.EntityFrameworkCore/IBaseEntity.cs b/src/EasMe.EntityFrameworkCore/IBaseEntity.cs index 8b6e2845..4889e9d7 100644 --- a/src/EasMe.EntityFrameworkCore/IBaseEntity.cs +++ b/src/EasMe.EntityFrameworkCore/IBaseEntity.cs @@ -1,5 +1,6 @@ namespace EasMe.EntityFrameworkCore; -public interface IBaseEntity : IEquatable, IEntity { +public interface IBaseEntity : IEquatable, IEntity +{ Guid Id { get; set; } } \ No newline at end of file diff --git a/src/EasMe.EntityFrameworkCore/IEntity.cs b/src/EasMe.EntityFrameworkCore/IEntity.cs index 09a5c533..55a56638 100644 --- a/src/EasMe.EntityFrameworkCore/IEntity.cs +++ b/src/EasMe.EntityFrameworkCore/IEntity.cs @@ -1,4 +1,5 @@ namespace EasMe.EntityFrameworkCore; -public interface IEntity { +public interface IEntity +{ } \ No newline at end of file diff --git a/src/EasMe.EntityFrameworkCore/IEntityRepository.cs b/src/EasMe.EntityFrameworkCore/IEntityRepository.cs index 59007530..48329020 100644 --- a/src/EasMe.EntityFrameworkCore/IEntityRepository.cs +++ b/src/EasMe.EntityFrameworkCore/IEntityRepository.cs @@ -3,7 +3,8 @@ namespace EasMe.EntityFrameworkCore; public interface IEntityRepository - where T : class, IEntity, new() { + where T : class, IEntity, new() +{ IQueryable Get(Expression>? filter = null); List GetList(Expression>? filter = null); bool Any(Expression> filter); diff --git a/src/EasMe.EntityFrameworkCore/IGenericRepository.cs b/src/EasMe.EntityFrameworkCore/IGenericRepository.cs index 09c6dfd2..2a74fbaa 100644 --- a/src/EasMe.EntityFrameworkCore/IGenericRepository.cs +++ b/src/EasMe.EntityFrameworkCore/IGenericRepository.cs @@ -3,7 +3,8 @@ namespace EasMe.EntityFrameworkCore; public interface IGenericRepository - where TEntity : class, IEntity { + where TEntity : class, IEntity +{ TEntity? GetFirstOrDefault(Expression>? filter = null, params string[] includeProperties); List ToList() { diff --git a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.csproj.CoreCompileInputs.cache b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.csproj.CoreCompileInputs.cache index 47ac7acc..985d0df0 100644 --- a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.csproj.CoreCompileInputs.cache +++ b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -cf44246bab67ed77808a280229c8690acf656006 +5ff824631b2de19b93466a17ba3d2074bd44e034 diff --git a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.dll b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.dll index 13d0fcdd..df56c346 100644 Binary files a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.dll and b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.dll differ diff --git a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.pdb b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.pdb index 45e63981..c9f9d97b 100644 Binary files a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.pdb and b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/EasMe.EntityFrameworkCore.pdb differ diff --git a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/ref/EasMe.EntityFrameworkCore.dll b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/ref/EasMe.EntityFrameworkCore.dll index a6fc043f..dff900c3 100644 Binary files a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/ref/EasMe.EntityFrameworkCore.dll and b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/ref/EasMe.EntityFrameworkCore.dll differ diff --git a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/refint/EasMe.EntityFrameworkCore.dll b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/refint/EasMe.EntityFrameworkCore.dll index a6fc043f..dff900c3 100644 Binary files a/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/refint/EasMe.EntityFrameworkCore.dll and b/src/EasMe.EntityFrameworkCore/obj/Release/net6.0/refint/EasMe.EntityFrameworkCore.dll differ diff --git a/src/EasMe.Logging/EasLog.cs b/src/EasMe.Logging/EasLog.cs index dc3fc160..d39f712a 100644 --- a/src/EasMe.Logging/EasLog.cs +++ b/src/EasMe.Logging/EasLog.cs @@ -8,7 +8,8 @@ namespace EasMe.Logging; /// /// Simple static json and console logger with useful options. /// -public class EasLog : IEasLog { +public class EasLog : IEasLog +{ private static readonly object _fileLock = new(); private static readonly EasTask EasTask = new(); @@ -35,7 +36,7 @@ public void LogResult(Result.Result result) { if (!easLogLevel.IsLoggable()) return; if (result.Errors.Count > 0) { WriteLog(_LogSource, easLogLevel, null, $"ErrorCode:{result.ErrorCode}", - $"Errors:{string.Join(",", result.Errors)}"); + $"Errors:{string.Join(",", result.Errors)}"); return; } @@ -47,8 +48,8 @@ public void LogResult(ResultData result) { if (!easLogLevel.IsLoggable()) return; if (result.Errors.Count > 0) { WriteLog(_LogSource, easLogLevel, null, $"ErrorCode:{result.ErrorCode}", - $"Data:{result.Data.ToJsonString()}", - $"Errors:{string.Join(",", result.Errors)}"); + $"Data:{result.Data.ToJsonString()}", + $"Errors:{string.Join(",", result.Errors)}"); return; } @@ -60,7 +61,7 @@ public void LogResult(Result.Result result, object message) { if (!easLogLevel.IsLoggable()) return; if (result.Errors?.Count > 0) { WriteLog(_LogSource, easLogLevel, null, $"Message:{message}", $"ErrorCode:{result.ErrorCode}", - $"Errors:{string.Join(",", result.Errors)}"); + $"Errors:{string.Join(",", result.Errors)}"); return; } @@ -72,12 +73,12 @@ public void LogResult(ResultData result, object message) { if (!easLogLevel.IsLoggable()) return; if (result.Errors.Count > 0) { WriteLog(_LogSource, easLogLevel, null, $"Message:{message}", $"ErrorCode:{result.ErrorCode}", - $"Errors:{string.Join(",", result.Errors)}", $"Data:{result.Data.ToJsonString()}"); + $"Errors:{string.Join(",", result.Errors)}", $"Data:{result.Data.ToJsonString()}"); return; } WriteLog(_LogSource, easLogLevel, null, $"Message:{message}", $"ErrorCode:{result.ErrorCode}", - $"Data:{result.Data.ToJsonString()}"); + $"Data:{result.Data.ToJsonString()}"); } @@ -122,7 +123,7 @@ public void Info(object obj1, object obj2, object obj3, object obj4, object obj5 } public void Info(object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, - object obj8) { + object obj8) { if (!EasLogLevel.Information.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Information, null, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -168,7 +169,7 @@ public void Error(object obj1, object obj2, object obj3, object obj4, object obj } public void Error(object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, - object obj8) { + object obj8) { if (!EasLogLevel.Error.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Error, null, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -214,7 +215,7 @@ public void Warn(object obj1, object obj2, object obj3, object obj4, object obj5 } public void Warn(object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, - object obj8) { + object obj8) { if (!EasLogLevel.Warning.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Warning, null, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -261,13 +262,13 @@ public void Exception(Exception ex, object obj1, object obj2, object obj3, objec } public void Exception(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, - object obj7) { + object obj7) { if (!EasLogLevel.Fatal.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Fatal, ex, obj1, obj2, obj3, obj4, obj5, obj6, obj7); } public void Exception(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, - object obj7, object obj8) { + object obj7, object obj8) { if (!EasLogLevel.Fatal.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Fatal, ex, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -314,7 +315,7 @@ public void Fatal(object obj1, object obj2, object obj3, object obj4, object obj } public void Fatal(object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, - object obj8) { + object obj8) { if (!EasLogLevel.Fatal.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Fatal, null, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -356,13 +357,13 @@ public void Fatal(Exception ex, object obj1, object obj2, object obj3, object ob } public void Fatal(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, - object obj7) { + object obj7) { if (!EasLogLevel.Fatal.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Fatal, ex, obj1, obj2, obj3, obj4, obj5, obj6, obj7); } public void Fatal(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, - object obj7, object obj8) { + object obj7, object obj8) { if (!EasLogLevel.Fatal.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Fatal, ex, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -409,7 +410,7 @@ public void Debug(object obj1, object obj2, object obj3, object obj4, object obj } public void Debug(object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, - object obj8) { + object obj8) { if (!EasLogLevel.Debug.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Debug, null, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -450,13 +451,13 @@ public void Debug(Exception ex, object obj1, object obj2, object obj3, object ob } public void Debug(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, - object obj7) { + object obj7) { if (!EasLogLevel.Debug.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Debug, ex, obj1, obj2, obj3, obj4, obj5, obj6, obj7); } public void Debug(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, - object obj7, object obj8) { + object obj7, object obj8) { if (!EasLogLevel.Debug.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Debug, ex, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -503,7 +504,7 @@ public void Trace(object obj1, object obj2, object obj3, object obj4, object obj } public void Trace(object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, - object obj8) { + object obj8) { if (!EasLogLevel.Trace.IsLoggable()) return; WriteLog(_LogSource, EasLogLevel.Trace, null, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8); } @@ -516,10 +517,10 @@ public bool IsLogLevelEnabled(EasLogLevel easLogLevel) { private string GetExactLogPath(EasLogLevel severity) { var date = DateTime.Now.ToString(EasLogFactory.Config.DateFormatString); var path = EasLogFactory.Config.SeparateLogLevelToFolder - ? Path.Combine(_folderName, date, - severity + "_" + EasLogFactory.Config.LogFileName + date + EasLogFactory.Config.LogFileExtension) - : Path.Combine(_folderName, - EasLogFactory.Config.LogFileName + date + EasLogFactory.Config.LogFileExtension); + ? Path.Combine(_folderName, date, + severity + "_" + EasLogFactory.Config.LogFileName + date + EasLogFactory.Config.LogFileExtension) + : Path.Combine(_folderName, + EasLogFactory.Config.LogFileName + date + EasLogFactory.Config.LogFileExtension); return path; } @@ -531,26 +532,26 @@ protected void WriteLog(string source, EasLogLevel severity, Exception? exceptio WebInfo? webInfo = null; if (EasLogFactory.Config.WebInfoLogging) webInfo = new WebInfo(); var loggingAction = new Action(() => { - var paramToLog = param.ToLogString(); - var log = LogModel.Create(severity, source, paramToLog, exception, webInfo); - if (EasLogFactory.Config.ConsoleAppender) EasLogConsole.Log(log.Level, log.ToJsonString() ?? ""); - var logFilePath = GetExactLogPath(log.Level); - try { - var folderPath = Path.GetDirectoryName(logFilePath); - if (folderPath is not null) - if (!Directory.Exists(folderPath)) - Directory.CreateDirectory(folderPath); - - lock (_fileLock) { - File.AppendAllText(logFilePath, log.ToJsonString() + "\n"); - } - } - catch (Exception ex) { - lock (_exceptions) { - _exceptions.Add(ex); - } - } - }); + var paramToLog = param.ToLogString(); + var log = LogModel.Create(severity, source, paramToLog, exception, webInfo); + if (EasLogFactory.Config.ConsoleAppender) EasLogConsole.Log(log.Level, log.ToJsonString() ?? ""); + var logFilePath = GetExactLogPath(log.Level); + try { + var folderPath = Path.GetDirectoryName(logFilePath); + if (folderPath is not null) + if (!Directory.Exists(folderPath)) + Directory.CreateDirectory(folderPath); + + lock (_fileLock) { + File.AppendAllText(logFilePath, log.ToJsonString() + "\n"); + } + } + catch (Exception ex) { + lock (_exceptions) { + _exceptions.Add(ex); + } + } + }); EasTask.AddToQueue(loggingAction); } } \ No newline at end of file diff --git a/src/EasMe.Logging/EasLogConfiguration.cs b/src/EasMe.Logging/EasLogConfiguration.cs index ea3483fb..71aaa302 100644 --- a/src/EasMe.Logging/EasLogConfiguration.cs +++ b/src/EasMe.Logging/EasLogConfiguration.cs @@ -1,6 +1,7 @@ namespace EasMe.Logging; -public class EasLogConfiguration { +public class EasLogConfiguration +{ internal EasLogConfiguration() { } diff --git a/src/EasMe.Logging/EasLogConsole.cs b/src/EasMe.Logging/EasLogConsole.cs index 0d4f182b..2bd5d84f 100644 --- a/src/EasMe.Logging/EasLogConsole.cs +++ b/src/EasMe.Logging/EasLogConsole.cs @@ -7,7 +7,8 @@ namespace EasMe.Logging; /// File logging with heavy api request sometime creating errors. /// With this you only log to console but if error happens you log with EasLog or some other library to a file. /// -public static class EasLogConsole { +public static class EasLogConsole +{ private const ConsoleColor FatalColor = ConsoleColor.Magenta; private const ConsoleColor ErrorColor = ConsoleColor.Red; private const ConsoleColor BaseColor = ConsoleColor.White; diff --git a/src/EasMe.Logging/EasLogFactory.cs b/src/EasMe.Logging/EasLogFactory.cs index b08260e4..592ba366 100644 --- a/src/EasMe.Logging/EasLogFactory.cs +++ b/src/EasMe.Logging/EasLogFactory.cs @@ -2,7 +2,8 @@ namespace EasMe.Logging; -public static class EasLogFactory { +public static class EasLogFactory +{ public static readonly IEasLog StaticLogger = CreateLogger("StaticLogger"); private static bool _isConfigured; internal static EasLogConfiguration Config { get; set; } = new(); @@ -43,13 +44,13 @@ public static void Configure(Action action) { public static void ConfigureDebugDefault(bool isWeb) { if (_isConfigured) throw new InvalidOperationException("EasLog configuration already loaded."); Config = new EasLogConfiguration { - ConsoleAppender = true, - ExceptionHideSensitiveInfo = false, - LogFileName = "Trace_", - MinimumLogLevel = EasLogLevel.Debug, - WebInfoLogging = isWeb, - SeparateLogLevelToFolder = false - }; + ConsoleAppender = true, + ExceptionHideSensitiveInfo = false, + LogFileName = "Trace_", + MinimumLogLevel = EasLogLevel.Debug, + WebInfoLogging = isWeb, + SeparateLogLevelToFolder = false + }; _isConfigured = true; } } \ No newline at end of file diff --git a/src/EasMe.Logging/EasLogLevel.cs b/src/EasMe.Logging/EasLogLevel.cs index 524a2ece..b1c507c9 100644 --- a/src/EasMe.Logging/EasLogLevel.cs +++ b/src/EasMe.Logging/EasLogLevel.cs @@ -1,6 +1,7 @@ namespace EasMe.Logging; -public enum EasLogLevel { +public enum EasLogLevel +{ Trace = -1, Debug = 0, Information = 1, diff --git a/src/EasMe.Logging/EasLogReader.cs b/src/EasMe.Logging/EasLogReader.cs index ff94bf9c..4cc4e37a 100644 --- a/src/EasMe.Logging/EasLogReader.cs +++ b/src/EasMe.Logging/EasLogReader.cs @@ -1,10 +1,10 @@ -using EasMe.Exceptions; -using EasMe.Extensions; +using EasMe.Extensions; using EasMe.Logging.Models; namespace EasMe.Logging; -public static class EasLogReader { +public static class EasLogReader +{ public static string? LogFilePath { get; set; } public static string[] LogFileContent { get; set; } @@ -22,7 +22,7 @@ public static void Load(string logFilePath) { LogFileContent = lines; } catch (Exception e) { - throw new FailedToReadException("Failed reading log file with given path: " + LogFilePath, e); + throw new Exception("Failed reading log file with given path: " + LogFilePath, e); } } @@ -43,12 +43,12 @@ public static List GetLogFileContent() { } if (list.Count == 0) - throw new NotFoundException( - "Failed getting log file content as List, log file does not have logs recorded."); + throw new Exception( + "Failed getting log file content as List, log file does not have logs recorded."); return list; } catch (Exception ex) { - throw new FailedToDeserializeException("Failed to deserialize log file content.", ex); + throw new Exception("Failed to deserialize log file content.", ex); } } @@ -62,6 +62,4 @@ public static List GetLogFileContent(EasLogLevel logLevel) { var list = GetLogFileContent(); return list.Where(x => x.Level == logLevel).ToList(); } - - } \ No newline at end of file diff --git a/src/EasMe.Logging/EasMe.Logging.csproj b/src/EasMe.Logging/EasMe.Logging.csproj index 7a3847e5..85c19a2c 100644 --- a/src/EasMe.Logging/EasMe.Logging.csproj +++ b/src/EasMe.Logging/EasMe.Logging.csproj @@ -1,30 +1,30 @@ - - net6.0 - enable - enable - C:\Users\kkass\source\build\easme - 3.1.0 - 3.1.0 - true - EasMe.Logging - Simple lightweight Json logging library. - https://github.com/bberka/EasMe/tree/master - https://github.com/bberka/EasMe/blob/master/LICENSE.txt - https://github.com/bberka/EasMe/tree/master - bberka + + net6.0 + enable + enable + C:\Users\kkass\source\build\easme + 3.1.0 + 3.1.0 + true + EasMe.Logging + Simple lightweight Json logging library. + https://github.com/bberka/EasMe/tree/master + https://github.com/bberka/EasMe/blob/master/LICENSE.txt + https://github.com/bberka/EasMe/tree/master + bberka - + - - - + + + - - - - + + + + diff --git a/src/EasMe.Logging/IEasLog.cs b/src/EasMe.Logging/IEasLog.cs index 02623677..dd274bb1 100644 --- a/src/EasMe.Logging/IEasLog.cs +++ b/src/EasMe.Logging/IEasLog.cs @@ -2,7 +2,8 @@ namespace EasMe.Logging; -public interface IEasLog { +public interface IEasLog +{ void LogResult(Result.Result result); void LogResult(ResultData result); void LogResult(Result.Result result, object message); @@ -47,10 +48,10 @@ public interface IEasLog { void Exception(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6); void Exception(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, - object obj7); + object obj7); void Exception(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, - object obj7, object obj8); + object obj7, object obj8); void Fatal(params object[] param); void Fatal(object obj1); @@ -71,7 +72,7 @@ void Exception(Exception ex, object obj1, object obj2, object obj3, object obj4, void Fatal(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7); void Fatal(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, - object obj8); + object obj8); void Debug(params object[] param); void Debug(object obj1); @@ -92,7 +93,7 @@ void Fatal(Exception ex, object obj1, object obj2, object obj3, object obj4, obj void Debug(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7); void Debug(Exception ex, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, - object obj8); + object obj8); void Trace(params object[] param); void Trace(object obj1); diff --git a/src/EasMe.Logging/Internal/EasLogHelper.cs b/src/EasMe.Logging/Internal/EasLogHelper.cs index 50e015cf..96608ca3 100644 --- a/src/EasMe.Logging/Internal/EasLogHelper.cs +++ b/src/EasMe.Logging/Internal/EasLogHelper.cs @@ -1,29 +1,25 @@ -using System.Diagnostics; -using EasMe.Exceptions; -using EasMe.Extensions; -using EasMe.Logging.Models; +using EasMe.Extensions; using Microsoft.AspNetCore.Http; namespace EasMe.Logging.Internal; -internal static class EasLogHelper { - - +internal static class EasLogHelper +{ internal static int ConvertConfigFileSize(string value) { try { var split = value.Split("-"); - if (split.Length == 0) throw new NotValidException("Given LogFileSize is not valid."); + if (split.Length == 0) throw new InvalidDataException("Given LogFileSize is not valid."); var size = Convert.ToInt32(split[0].Trim()); var unit = split[1].Trim().ToLower(); return unit switch { - "kb" => size * 1024, - "mb" => size * 1024 * 1024, - "gb" => size * 1024 * 1024 * 1024, - _ => size - }; + "kb" => size * 1024, + "mb" => size * 1024 * 1024, + "gb" => size * 1024 * 1024 * 1024, + _ => size + }; } catch (Exception ex) { - throw new FailedToParseException("Failed to parse configuration file size.", ex); + throw new Exception("Failed to parse configuration file size.", ex); } } diff --git a/src/EasMe.Logging/Internal/Extensions.cs b/src/EasMe.Logging/Internal/Extensions.cs index d26fe082..ad6f3593 100644 --- a/src/EasMe.Logging/Internal/Extensions.cs +++ b/src/EasMe.Logging/Internal/Extensions.cs @@ -2,26 +2,27 @@ namespace EasMe.Logging.Internal; -public static class Extensions { +public static class Extensions +{ public static EasLogLevel ToEasLogLevel(this ResultSeverity resultSeverity) { return resultSeverity switch { - ResultSeverity.Info => EasLogLevel.Information, - ResultSeverity.Warn => EasLogLevel.Warning, - ResultSeverity.Error => EasLogLevel.Error, - ResultSeverity.Fatal => EasLogLevel.Fatal, - _ => EasLogLevel.Off - }; + ResultSeverity.Info => EasLogLevel.Information, + ResultSeverity.Warn => EasLogLevel.Warning, + ResultSeverity.Error => EasLogLevel.Error, + ResultSeverity.Fatal => EasLogLevel.Fatal, + _ => EasLogLevel.Off + }; } internal static EasLogLevel ToEasLogLevel(this string logLevel) { return logLevel switch { - "Debug" => EasLogLevel.Debug, - "Information" => EasLogLevel.Information, - "Warning" => EasLogLevel.Warning, - "Error" => EasLogLevel.Error, - "Fatal" => EasLogLevel.Fatal, - _ => EasLogLevel.Off - }; + "Debug" => EasLogLevel.Debug, + "Information" => EasLogLevel.Information, + "Warning" => EasLogLevel.Warning, + "Error" => EasLogLevel.Error, + "Fatal" => EasLogLevel.Fatal, + _ => EasLogLevel.Off + }; } internal static string ToLogString(this object[] param) { diff --git a/src/EasMe.Logging/Internal/SelfLog.cs b/src/EasMe.Logging/Internal/SelfLog.cs index 27e82b23..ab6bcb4d 100644 --- a/src/EasMe.Logging/Internal/SelfLog.cs +++ b/src/EasMe.Logging/Internal/SelfLog.cs @@ -1,5 +1,6 @@ namespace EasMe.Logging.Internal; -internal static class SelfLog { +internal static class SelfLog +{ internal static IEasLog Logger { get; set; } = EasLogFactory.CreateLogger(); } \ No newline at end of file diff --git a/src/EasMe.Logging/Models/LogModel.cs b/src/EasMe.Logging/Models/LogModel.cs index d79ff156..7e595e99 100644 --- a/src/EasMe.Logging/Models/LogModel.cs +++ b/src/EasMe.Logging/Models/LogModel.cs @@ -1,23 +1,23 @@ -using EasMe.Logging.Internal; -using EasMe.Models; +using EasMe.Models; using Newtonsoft.Json; namespace EasMe.Logging.Models; -public class LogModel { +public class LogModel +{ private LogModel() { } private LogModel(EasLogLevel logLevel, string source, object log, Exception? exception = null, - WebInfo? webInfo = null) { + WebInfo? webInfo = null) { Level = logLevel; Source = source; Log = log; WebInfo = webInfo; if (exception == null) return; Exception = EasLogFactory.Config.ExceptionHideSensitiveInfo - ? new CleanException(exception.Message) - : new CleanException(exception); + ? new CleanException(exception.Message) + : new CleanException(exception); } public DateTime Date { get; } = DateTime.Now; @@ -33,7 +33,7 @@ private LogModel(EasLogLevel logLevel, string source, object log, Exception? exc public WebInfo? WebInfo { get; set; } public static LogModel Create(EasLogLevel logLevel, string source, object log, Exception? exception = null, - WebInfo? webInfo = null) { + WebInfo? webInfo = null) { return new LogModel(logLevel, source, log, exception, webInfo); } } \ No newline at end of file diff --git a/src/EasMe.Logging/Models/TraceInfo.cs b/src/EasMe.Logging/Models/TraceInfo.cs index 14afecdf..bbd2f030 100644 --- a/src/EasMe.Logging/Models/TraceInfo.cs +++ b/src/EasMe.Logging/Models/TraceInfo.cs @@ -1,6 +1,7 @@ namespace EasMe.Logging.Models; -public class TraceInfo { +public class TraceInfo +{ public string? MethodName { get; set; } public string? ClassName { get; set; } } \ No newline at end of file diff --git a/src/EasMe.Logging/Models/WebInfo.cs b/src/EasMe.Logging/Models/WebInfo.cs index 8997f836..fe18cab5 100644 --- a/src/EasMe.Logging/Models/WebInfo.cs +++ b/src/EasMe.Logging/Models/WebInfo.cs @@ -4,7 +4,8 @@ namespace EasMe.Logging.Models; -public class WebInfo { +public class WebInfo +{ public WebInfo() { if (HttpContextHelper.Current is null) return; try { diff --git a/src/EasMe.Logging/README.md b/src/EasMe.Logging/README.md index 28086c4d..b35f1ebc 100644 --- a/src/EasMe.Logging/README.md +++ b/src/EasMe.Logging/README.md @@ -1,6 +1,7 @@ # EasMe.Logging ### Table of Contents + - EasLog - EasLogFactory - EasLogConfiguration diff --git a/src/EasMe.PostSharp/CacheAspects/CacheAspect.cs b/src/EasMe.PostSharp/CacheAspects/CacheAspect.cs index 0bf6457c..8760ecae 100644 --- a/src/EasMe.PostSharp/CacheAspects/CacheAspect.cs +++ b/src/EasMe.PostSharp/CacheAspects/CacheAspect.cs @@ -4,7 +4,8 @@ namespace EasMe.PostSharp.CacheAspects; [Serializable] -public class CacheAspect : MethodInterceptionAspect { +public class CacheAspect : MethodInterceptionAspect +{ private int _cacheBySeconds; private IMemoryCache _memoryCache; @@ -15,9 +16,9 @@ public CacheAspect(IMemoryCache memoryCache, int cacheBySeconds = 60) { public override void OnInvoke(MethodInterceptionArgs args) { var methodName = string.Format("{0}.{1}.{2}", - args.Method.ReflectedType?.Namespace, - args.Method.ReflectedType?.Name, - args.Method.Name); + args.Method.ReflectedType?.Namespace, + args.Method.ReflectedType?.Name, + args.Method.Name); var arguments = args.Arguments.ToList(); var key = $"{methodName}({string.Join(",", arguments.Select(x => x != null ? x.ToString() : ""))})"; diff --git a/src/EasMe.PostSharp/EasMe.PostSharp.csproj b/src/EasMe.PostSharp/EasMe.PostSharp.csproj index 5cc83168..0578ac0a 100644 --- a/src/EasMe.PostSharp/EasMe.PostSharp.csproj +++ b/src/EasMe.PostSharp/EasMe.PostSharp.csproj @@ -1,21 +1,21 @@ - - net6.0 - enable - enable - 3.5 + + net6.0 + enable + enable + 3.5 - + - - - - + + + + - - - + + + diff --git a/src/EasMe.PostSharp/ExceptionAspects/ExceptionLogAspect.cs b/src/EasMe.PostSharp/ExceptionAspects/ExceptionLogAspect.cs index 07c1ec3e..16800847 100644 --- a/src/EasMe.PostSharp/ExceptionAspects/ExceptionLogAspect.cs +++ b/src/EasMe.PostSharp/ExceptionAspects/ExceptionLogAspect.cs @@ -4,8 +4,10 @@ namespace EasMe.PostSharp.ExceptionAspects; [Serializable] -public class ExceptionLogAspect : OnExceptionAspect { - [NonSerialized] private readonly IEasLog _logger; +public class ExceptionLogAspect : OnExceptionAspect +{ + [NonSerialized] + private readonly IEasLog _logger; public ExceptionLogAspect(IEasLog logger) { diff --git a/src/EasMe.PostSharp/LogAspects/LogAspect.cs b/src/EasMe.PostSharp/LogAspects/LogAspect.cs index eff4608b..997eab5d 100644 --- a/src/EasMe.PostSharp/LogAspects/LogAspect.cs +++ b/src/EasMe.PostSharp/LogAspects/LogAspect.cs @@ -7,7 +7,8 @@ namespace EasMe.PostSharp.LogAspects; [Serializable] [MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Instance)] -public class LogAspect : OnMethodBoundaryAspect { +public class LogAspect : OnMethodBoundaryAspect +{ private readonly IEasLog _logger; public LogAspect(IEasLog logger) { @@ -24,7 +25,7 @@ public override void OnEntry(MethodExecutionArgs args) { try { var logParameters = args.Method.GetParameters().Select((t, i) => args.Arguments.GetArgument(i)).ToList(); _logger.Info($"FullName:{args.Method.DeclaringType?.Name}", $"MethodName:{args.Method.Name}", - $"Params:{logParameters.ToJsonString()}"); + $"Params:{logParameters.ToJsonString()}"); } catch (Exception e) { // ignored diff --git a/src/EasMe.PostSharp/PerformanceAspects/PerformanceCounterAspect.cs b/src/EasMe.PostSharp/PerformanceAspects/PerformanceCounterAspect.cs index fc63ce47..a09f41c0 100644 --- a/src/EasMe.PostSharp/PerformanceAspects/PerformanceCounterAspect.cs +++ b/src/EasMe.PostSharp/PerformanceAspects/PerformanceCounterAspect.cs @@ -5,11 +5,13 @@ namespace EasMe.PostSharp.PerformanceAspects; [Serializable] -public class PerformanceCounterAspect : OnMethodBoundaryAspect { +public class PerformanceCounterAspect : OnMethodBoundaryAspect +{ private static Action? _logAction; private int _interval; - [NonSerialized] private Stopwatch _stopwatch; + [NonSerialized] + private Stopwatch _stopwatch; public PerformanceCounterAspect(int intervalSeconds = 5) { _interval = intervalSeconds; @@ -29,10 +31,10 @@ public override void OnExit(MethodExecutionArgs args) { if (_stopwatch.Elapsed.TotalSeconds > _interval) { if (_logAction is null) Debug.WriteLine("Performance:{0}.{1}-->{2}", args.Method.DeclaringType?.FullName, args.Method.Name, - _stopwatch.Elapsed.TotalSeconds); + _stopwatch.Elapsed.TotalSeconds); else _logAction( - $"Performance:{args.Method.DeclaringType?.FullName}.{args.Method.Name}-->{_stopwatch.Elapsed.TotalSeconds}"); + $"Performance:{args.Method.DeclaringType?.FullName}.{args.Method.Name}-->{_stopwatch.Elapsed.TotalSeconds}"); } _stopwatch.Reset(); diff --git a/src/EasMe.Result/EasMe.Result.csproj b/src/EasMe.Result/EasMe.Result.csproj index 865f5896..eefcc0dd 100644 --- a/src/EasMe.Result/EasMe.Result.csproj +++ b/src/EasMe.Result/EasMe.Result.csproj @@ -1,30 +1,30 @@ - - net6.0 - enable - enable - C:\Users\kkass\source\build\easme - 2.0.2 - 2.0.2 - - true - EasMe.Result - bberka - Simple Lightweight Result type provider library with various helpul methods. - https://github.com/bberka/EasMe - https://github.com/bberka/EasMe/blob/master/LICENSE.txt - https://github.com/bberka/EasMe + + net6.0 + enable + enable + C:\Users\kkass\source\build\easme + 2.0.2 + 2.0.2 + + true + EasMe.Result + bberka + Simple Lightweight Result type provider library with various helpul methods. + https://github.com/bberka/EasMe + https://github.com/bberka/EasMe/blob/master/LICENSE.txt + https://github.com/bberka/EasMe - + - - - + + + - - - + + + diff --git a/src/EasMe.Result/ExtensionMethods.cs b/src/EasMe.Result/ExtensionMethods.cs index 208b7433..0dd4173b 100644 --- a/src/EasMe.Result/ExtensionMethods.cs +++ b/src/EasMe.Result/ExtensionMethods.cs @@ -1,6 +1,7 @@ namespace EasMe.Result; -public static class ExtensionMethods { +public static class ExtensionMethods +{ /// /// Merges multiple Results into one. /// Result will be Success if all results are Success @@ -78,7 +79,7 @@ public static Result CombineAll( var errorArrayOfErrors = list.Where(x => x.IsFailure).SelectMany(x => x.Errors).ToList(); errorArray = errorArray.Concat(errorArrayOfErrors).ToList(); var validationErrors = list.Where(x => x.IsFailure).SelectMany(x => x.ValidationErrors).ToList(); - return Result.Create(isAllSuccess, severity, errorCode, errorArray , validationErrors); + return Result.Create(isAllSuccess, severity, errorCode, errorArray, validationErrors); } /// @@ -106,10 +107,10 @@ public static Result CombineErrorCodes( var isAllSuccess = list.All(x => x.IsSuccess); var errorArray = list.Where(x => x.IsFailure).Select(x => x.ErrorCode).ToList(); var exceptions = list.Where(x => x.IsFailure && x.ExceptionInfo != null).Select(x => x.ExceptionInfo!.Message) - .ToList(); + .ToList(); errorArray = errorArray.Concat(exceptions).ToList(); var validationErrors = list.Where(x => x.IsFailure).SelectMany(x => x.ValidationErrors).ToList(); - return Result.Create(isAllSuccess, severity, errorCode, errorArray , validationErrors); + return Result.Create(isAllSuccess, severity, errorCode, errorArray, validationErrors); //var errorArrayOfErrors = list.Where(x => x.IsFailure).SelectMany(x => x.Errors).ToArray(); //errorArray = errorArray.Concat(errorArrayOfErrors).ToArray(); // return Result.Create(isAllSuccess, severity, errorCode, errorArray , validationErrors); diff --git a/src/EasMe.Result/Result.cs b/src/EasMe.Result/Result.cs index b3ceb75c..b468ce5f 100644 --- a/src/EasMe.Result/Result.cs +++ b/src/EasMe.Result/Result.cs @@ -1,5 +1,4 @@ -using System.Net; -using EasMe.Models; +using EasMe.Models; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; @@ -12,28 +11,28 @@ namespace EasMe.Result; /// public readonly struct Result { - - public Result() { } + public Result() { + } /// /// Indicates success status of . /// - public bool IsSuccess { get; init; } = false; + public bool IsSuccess { get; init; } = false; /// /// Indicates fail status of . /// public bool IsFailure => !IsSuccess; - public string ErrorCode { get; init; } = "None"; + public string ErrorCode { get; init; } = "None"; public List Errors { get; init; } = new(); public List ValidationErrors { get; init; } = new(); - public ResultSeverity Severity { get; init; } = ResultSeverity.None; + public ResultSeverity Severity { get; init; } = ResultSeverity.None; [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public CleanException? ExceptionInfo { get; init; } = null; -#region OPERATORS + #region OPERATORS public static implicit operator Result(bool value) { return !value ? Error("UnsetError") : Success("Success"); @@ -42,28 +41,29 @@ public static implicit operator Result(bool value) { public static implicit operator bool(Result value) { return value.IsSuccess; } - + public static implicit operator ActionResult(Result result) { return result.ToActionResult(); } -#endregion + #endregion -#region CONVERTERS + #region CONVERTERS public ResultData ToResultData(T? data = default) { - return new ResultData() { - ErrorCode = this.ErrorCode, - Severity = this.Severity, - Data = data, - IsSuccess = this.IsSuccess, - ExceptionInfo = this.ExceptionInfo, - }; + return new ResultData { + ErrorCode = ErrorCode, + Severity = Severity, + Data = data, + IsSuccess = IsSuccess, + ExceptionInfo = ExceptionInfo + }; } /// - /// Converts to . If result is failure, returns . If result is success, returns . + /// Converts to . If result is failure, returns + /// . If result is success, returns . /// /// public ActionResult ToActionResult() { @@ -71,7 +71,9 @@ public ActionResult ToActionResult() { } /// - /// Converts to . If result is failure, returns with . If result is success, returns . + /// Converts to . If result is failure, returns + /// with . If result is success, returns + /// . /// /// /// @@ -79,204 +81,213 @@ public ActionResult ToActionResult(int failStatusCode) { return IsSuccess ? new OkObjectResult(this) : new ObjectResult(this) { StatusCode = failStatusCode }; } -#endregion + #endregion -#region CREATE METHODS - public static Result Create(bool isSuccess, ResultSeverity severity, string errCode, List errors, List validationErrors) { - return new Result() { - IsSuccess = isSuccess, - Severity = severity, - ErrorCode = errCode, - Errors = errors, - ExceptionInfo = null, - ValidationErrors = validationErrors - }; + #region CREATE METHODS + public static Result Create(bool isSuccess, ResultSeverity severity, string errCode, List errors, List validationErrors) { + return new Result { + IsSuccess = isSuccess, + Severity = severity, + ErrorCode = errCode, + Errors = errors, + ExceptionInfo = null, + ValidationErrors = validationErrors + }; } - + public static Result Success(string errorCode) { - return new Result() { - ErrorCode = errorCode, - IsSuccess = true, - Severity = ResultSeverity.Info, - ExceptionInfo = null, - - }; + return new Result { + ErrorCode = errorCode, + IsSuccess = true, + Severity = ResultSeverity.Info, + ExceptionInfo = null + }; } public static Result Success(string errorCode, List errors) { - return new Result() { - ErrorCode = errorCode, - Errors = errors, - IsSuccess = true, - Severity = ResultSeverity.Info - }; + return new Result { + ErrorCode = errorCode, + Errors = errors, + IsSuccess = true, + Severity = ResultSeverity.Info + }; } + public static Result Success(List errors) { - return new Result() { - ErrorCode = "Success", - Errors = errors, - IsSuccess = true, - Severity = ResultSeverity.Info - }; + return new Result { + ErrorCode = "Success", + Errors = errors, + IsSuccess = true, + Severity = ResultSeverity.Info + }; } public static Result Exception(Exception exception) { - return new Result() { - ErrorCode = "Exception", - IsSuccess = false, - Severity = ResultSeverity.Exception - }; + return new Result { + ErrorCode = "Exception", + IsSuccess = false, + Severity = ResultSeverity.Exception + }; } + public static Result Exception(Exception exception, List errors) { - return new Result() { - ErrorCode = "Exception", - Errors = errors, - IsSuccess = false, - Severity = ResultSeverity.Exception - }; + return new Result { + ErrorCode = "Exception", + Errors = errors, + IsSuccess = false, + Severity = ResultSeverity.Exception + }; } + public static Result Exception(Exception exception, params string[] errors) { - return new Result() { - ErrorCode = "Exception", - Errors = errors.ToList(), - IsSuccess = false, - Severity = ResultSeverity.Exception - }; + return new Result { + ErrorCode = "Exception", + Errors = errors.ToList(), + IsSuccess = false, + Severity = ResultSeverity.Exception + }; } - + public static Result Warn(string errorCode) { - return new Result() { - ErrorCode = errorCode, - IsSuccess = false, - Severity = ResultSeverity.Warn, - }; + return new Result { + ErrorCode = errorCode, + IsSuccess = false, + Severity = ResultSeverity.Warn + }; } - public static Result Warn(T errorEnum) where T : Enum{ - return new Result() { - ErrorCode = errorEnum.ToString(), - IsSuccess = false, - Severity = ResultSeverity.Warn, - }; + public static Result Warn(T errorEnum) where T : Enum { + return new Result { + ErrorCode = errorEnum.ToString(), + IsSuccess = false, + Severity = ResultSeverity.Warn + }; } + public static Result Warn(string errorCode, List errors) { - return new Result() { - ErrorCode = errorCode, - Errors = errors, - IsSuccess = false, - Severity = ResultSeverity.Warn - }; + return new Result { + ErrorCode = errorCode, + Errors = errors, + IsSuccess = false, + Severity = ResultSeverity.Warn + }; } + public static Result Warn(string errorCode, params string[] errors) { - return new Result() { - ErrorCode = errorCode, - Errors = errors.ToList(), - IsSuccess = false, - Severity = ResultSeverity.Warn - }; + return new Result { + ErrorCode = errorCode, + Errors = errors.ToList(), + IsSuccess = false, + Severity = ResultSeverity.Warn + }; } + public static Result Fatal(string errorCode) { - return new Result() { - ErrorCode = errorCode, - IsSuccess = false, - Severity = ResultSeverity.Fatal, - }; + return new Result { + ErrorCode = errorCode, + IsSuccess = false, + Severity = ResultSeverity.Fatal + }; } - public static Result Fatal(T errorEnum) where T : Enum{ - return new Result() { - ErrorCode = errorEnum.ToString(), - IsSuccess = false, - Severity = ResultSeverity.Fatal, - }; + + public static Result Fatal(T errorEnum) where T : Enum { + return new Result { + ErrorCode = errorEnum.ToString(), + IsSuccess = false, + Severity = ResultSeverity.Fatal + }; } public static Result Fatal(string errorCode, List errors) { - return new Result() { - ErrorCode = errorCode, - Errors = errors, - IsSuccess = false, - Severity = ResultSeverity.Fatal - }; + return new Result { + ErrorCode = errorCode, + Errors = errors, + IsSuccess = false, + Severity = ResultSeverity.Fatal + }; } + public static Result Fatal(string errorCode, params string[] errors) { - return new Result() { - ErrorCode = errorCode, - Errors = errors.ToList(), - IsSuccess = false, - Severity = ResultSeverity.Fatal - }; + return new Result { + ErrorCode = errorCode, + Errors = errors.ToList(), + IsSuccess = false, + Severity = ResultSeverity.Fatal + }; } - public static Result Error(string errorCode, List errors) { - return new Result() { - ErrorCode = errorCode, - Errors = errors, - IsSuccess = false, - Severity = ResultSeverity.Error - }; + return new Result { + ErrorCode = errorCode, + Errors = errors, + IsSuccess = false, + Severity = ResultSeverity.Error + }; } public static Result Error(string errorCode) { - return new Result() { - ErrorCode = errorCode, - IsSuccess = false, - Severity = ResultSeverity.Error, - }; + return new Result { + ErrorCode = errorCode, + IsSuccess = false, + Severity = ResultSeverity.Error + }; } public static Result Error(string errorCode, params string[] errors) { - return new Result() { - ErrorCode = errorCode, - Errors = errors.ToList(), - IsSuccess = false, - Severity = ResultSeverity.Error - }; + return new Result { + ErrorCode = errorCode, + Errors = errors.ToList(), + IsSuccess = false, + Severity = ResultSeverity.Error + }; } - public static Result Error(T errorEnum) where T : Enum{ - return new Result() { - ErrorCode = errorEnum.ToString(), - IsSuccess = false, - Severity = ResultSeverity.Error, - }; + + public static Result Error(T errorEnum) where T : Enum { + return new Result { + ErrorCode = errorEnum.ToString(), + IsSuccess = false, + Severity = ResultSeverity.Error + }; } + public static Result NotFound() { - return new Result() { - ErrorCode = "NotFound", - }; + return new Result { + ErrorCode = "NotFound" + }; } public static Result Unauthorized() { - return new Result() { - ErrorCode = "Unauthorized", - }; + return new Result { + ErrorCode = "Unauthorized" + }; } public static Result Forbidden() { - return new Result() { - ErrorCode = "Forbidden", - }; + return new Result { + ErrorCode = "Forbidden" + }; } public static Result ValidationError(List validationErrors) { - return new Result() { - ValidationErrors = validationErrors, - Severity = ResultSeverity.Validation, - IsSuccess = false, - ErrorCode = "ValidationError", - }; + return new Result { + ValidationErrors = validationErrors, + Severity = ResultSeverity.Validation, + IsSuccess = false, + ErrorCode = "ValidationError" + }; } public static Result MultipleErrors(List errors, string errorCode = "MultipleErrors", ResultSeverity severity = ResultSeverity.Error) { - return new Result() { - ErrorCode = errorCode, - Errors = errors, - IsSuccess = false, - Severity = severity, - }; + return new Result { + ErrorCode = errorCode, + Errors = errors, + IsSuccess = false, + Severity = severity + }; } -#endregion + + #endregion } \ No newline at end of file diff --git a/src/EasMe.Result/ResultData.cs b/src/EasMe.Result/ResultData.cs index 352a6319..847088b9 100644 --- a/src/EasMe.Result/ResultData.cs +++ b/src/EasMe.Result/ResultData.cs @@ -9,10 +9,10 @@ namespace EasMe.Result; ///
/// In order to avoid using 's and the performance downside from it. ///
-public readonly struct ResultData { - - - public ResultData() {} +public readonly struct ResultData +{ + public ResultData() { + } public ResultSeverity Severity { get; init; } = ResultSeverity.None; public bool IsSuccess { get; init; } = false; @@ -31,45 +31,46 @@ public ResultData() {} #region OPERATORS public static implicit operator ResultData(Result res) { - return new ResultData() { - ErrorCode = res.ErrorCode, - Severity = res.Severity, - ExceptionInfo = res.ExceptionInfo, - IsSuccess = res.IsSuccess, - Errors = res.Errors, - ValidationErrors = res.ValidationErrors, - }; + return new ResultData { + ErrorCode = res.ErrorCode, + Severity = res.Severity, + ExceptionInfo = res.ExceptionInfo, + IsSuccess = res.IsSuccess, + Errors = res.Errors, + ValidationErrors = res.ValidationErrors + }; } + public static implicit operator Result(ResultData res) { - return new Result() { - ErrorCode = res.ErrorCode, - Severity = res.Severity, - ExceptionInfo = res.ExceptionInfo, - IsSuccess = res.IsSuccess, - Errors = res.Errors, - ValidationErrors = res.ValidationErrors - }; + return new Result { + ErrorCode = res.ErrorCode, + Severity = res.Severity, + ExceptionInfo = res.ExceptionInfo, + IsSuccess = res.IsSuccess, + Errors = res.Errors, + ValidationErrors = res.ValidationErrors + }; } - + public static implicit operator T?(ResultData res) { return res.Data; } public static implicit operator ResultData(T? value) { return value is null - ? new ResultData() { - ErrorCode = "UnsetError", - ExceptionInfo = null, - Severity = ResultSeverity.Error, - IsSuccess = false, - } - : new ResultData() { - ErrorCode = "Success", - Severity = ResultSeverity.Info, - ExceptionInfo = null, - Data = value, - IsSuccess = true, - }; + ? new ResultData { + ErrorCode = "UnsetError", + ExceptionInfo = null, + Severity = ResultSeverity.Error, + IsSuccess = false + } + : new ResultData { + ErrorCode = "Success", + Severity = ResultSeverity.Info, + ExceptionInfo = null, + Data = value, + IsSuccess = true + }; } public static implicit operator bool(ResultData value) { @@ -79,45 +80,48 @@ public static implicit operator bool(ResultData value) { public static implicit operator ActionResult(ResultData result) { return result.ToActionResult(); } + #endregion - - + + #region MethodConverters public Result ToResult() { - return new Result() { - ErrorCode = this.ErrorCode, - Severity = Severity, - ExceptionInfo = ExceptionInfo, - IsSuccess = IsSuccess, - Errors = Errors, - ValidationErrors = ValidationErrors - }; + return new Result { + ErrorCode = ErrorCode, + Severity = Severity, + ExceptionInfo = ExceptionInfo, + IsSuccess = IsSuccess, + Errors = Errors, + ValidationErrors = ValidationErrors + }; } - public ResultData Map(Func action) { + public ResultData Map(Func action) { var res = action(Data); - return new ResultData() { - ErrorCode = ErrorCode, - Severity = Severity, - Data = res, - IsSuccess = IsSuccess, - ExceptionInfo = ExceptionInfo, - }; - + return new ResultData { + ErrorCode = ErrorCode, + Severity = Severity, + Data = res, + IsSuccess = IsSuccess, + ExceptionInfo = ExceptionInfo + }; } /// - /// Converts to . If result is failure, returns with . If result is success, returns . + /// Converts to . If result is failure, returns + /// with . If result is success, returns + /// . /// /// /// public ActionResult ToActionResult(int failStatusCode) { return IsSuccess ? new OkObjectResult(this) : new ObjectResult(this) { StatusCode = failStatusCode }; } - + /// - /// Converts to . If result is failure, returns . If result is success, returns . + /// Converts to . If result is failure, returns + /// . If result is success, returns . /// /// public ActionResult ToActionResult() { diff --git a/src/EasMe.Result/ResultErrorCode.cs b/src/EasMe.Result/ResultErrorCode.cs index e4392428..a379d0c5 100644 --- a/src/EasMe.Result/ResultErrorCode.cs +++ b/src/EasMe.Result/ResultErrorCode.cs @@ -3,7 +3,8 @@ /// /// Built-in Result Error Codes /// -public enum ResultErrorCode { +public enum ResultErrorCode +{ Ok, Warning, Error, diff --git a/src/EasMe.Result/ResultSeverity.cs b/src/EasMe.Result/ResultSeverity.cs index f0125d3e..f3eeb1cc 100644 --- a/src/EasMe.Result/ResultSeverity.cs +++ b/src/EasMe.Result/ResultSeverity.cs @@ -1,11 +1,12 @@ namespace EasMe.Result; -public enum ResultSeverity { +public enum ResultSeverity +{ None, Info, Validation, Warn, Error, Exception, - Fatal, + Fatal } \ No newline at end of file diff --git a/src/EasMe.Result/ResultT.cs b/src/EasMe.Result/ResultT.cs index e1b9f348..e1fb3bd4 100644 --- a/src/EasMe.Result/ResultT.cs +++ b/src/EasMe.Result/ResultT.cs @@ -5,7 +5,8 @@ ///
/// In order to avoid using 's and the performance downside from it. /// -public readonly struct ResultT { +public readonly struct ResultT +{ internal ResultT(T? data, Result result) { Data = data; Result = result; diff --git a/src/EasMe.Result/ValidationError.cs b/src/EasMe.Result/ValidationError.cs index 1d925ef0..01a4ae69 100644 --- a/src/EasMe.Result/ValidationError.cs +++ b/src/EasMe.Result/ValidationError.cs @@ -5,5 +5,4 @@ public class ValidationError public string Message { get; set; } public string? Property { get; set; } public string? ErrorCode { get; set; } - } \ No newline at end of file diff --git a/src/EasMe.SharpBuilder/EasMe.SharpBuilder.csproj b/src/EasMe.SharpBuilder/EasMe.SharpBuilder.csproj index 22982340..d4cf59b6 100644 --- a/src/EasMe.SharpBuilder/EasMe.SharpBuilder.csproj +++ b/src/EasMe.SharpBuilder/EasMe.SharpBuilder.csproj @@ -1,23 +1,23 @@ - - net6.0 - enable - enable - 1.0.0 - 1.1.0 - EasMe.SharpBuilder - bberka - C# code and class builder, for creating models from various type of files. Excel, text, json files. - https://github.com/bberka/EasMe/tree/master - https://github.com/bberka/EasMe/blob/master/LICENSE.txt - https://github.com/bberka/EasMe/tree/master - true + + net6.0 + enable + enable + 1.0.0 + 1.1.0 + EasMe.SharpBuilder + bberka + C# code and class builder, for creating models from various type of files. Excel, text, json files. + https://github.com/bberka/EasMe/tree/master + https://github.com/bberka/EasMe/blob/master/LICENSE.txt + https://github.com/bberka/EasMe/tree/master + true - + - - - + + + diff --git a/src/EasMe.SharpBuilder/Models/SharpClass.cs b/src/EasMe.SharpBuilder/Models/SharpClass.cs index e4fc11d2..62f69a6f 100644 --- a/src/EasMe.SharpBuilder/Models/SharpClass.cs +++ b/src/EasMe.SharpBuilder/Models/SharpClass.cs @@ -1,6 +1,7 @@ namespace EasMe.SharpBuilder.Models; -public class SharpClass { +public class SharpClass +{ public string AccessModifierString { get; set; } = "public"; public string Name { get; set; } public List Properties { get; set; } = new(); diff --git a/src/EasMe.SharpBuilder/Models/SharpFile.cs b/src/EasMe.SharpBuilder/Models/SharpFile.cs index c5e4fd80..6e13bf1e 100644 --- a/src/EasMe.SharpBuilder/Models/SharpFile.cs +++ b/src/EasMe.SharpBuilder/Models/SharpFile.cs @@ -1,6 +1,7 @@ namespace EasMe.SharpBuilder.Models; -public class SharpFile { +public class SharpFile +{ public List UsingList { get; set; } = new(); public string NameSpace { get; set; } public List Classes { get; set; } = new(); diff --git a/src/EasMe.SharpBuilder/Models/SharpProperty.cs b/src/EasMe.SharpBuilder/Models/SharpProperty.cs index cac7f4f3..209029ef 100644 --- a/src/EasMe.SharpBuilder/Models/SharpProperty.cs +++ b/src/EasMe.SharpBuilder/Models/SharpProperty.cs @@ -1,6 +1,7 @@ namespace EasMe.SharpBuilder.Models; -public class SharpProperty { +public class SharpProperty +{ public string AccessModifierString { get; set; } = "public"; public string GetterAccessModifierString { get; set; } = ""; public string SetterAccessModifierString { get; set; } = ""; diff --git a/src/EasMe.SharpBuilder/SharpClassBuilder.cs b/src/EasMe.SharpBuilder/SharpClassBuilder.cs index 455b020a..5cf03057 100644 --- a/src/EasMe.SharpBuilder/SharpClassBuilder.cs +++ b/src/EasMe.SharpBuilder/SharpClassBuilder.cs @@ -2,7 +2,8 @@ namespace EasMe.SharpBuilder; -public class SharpClassBuilder { +public class SharpClassBuilder +{ private readonly SharpClass _sharpClass; public SharpClassBuilder() { @@ -110,4 +111,4 @@ public SharpClassBuilder WithIsConst(bool isConst) { public SharpClass Build() { return _sharpClass; } -} +} \ No newline at end of file diff --git a/src/EasMe.SharpBuilder/SharpExtensions.cs b/src/EasMe.SharpBuilder/SharpExtensions.cs index f1b60d9f..5e74d6d4 100644 --- a/src/EasMe.SharpBuilder/SharpExtensions.cs +++ b/src/EasMe.SharpBuilder/SharpExtensions.cs @@ -3,77 +3,52 @@ namespace EasMe.SharpBuilder; -public static class SharpExtensions { +public static class SharpExtensions +{ public static void Export(this SharpFile file) { var sb = new StringBuilder(); - foreach (var item in file.UsingList) { - sb.AppendLine("using " + item + ";"); - } + foreach (var item in file.UsingList) sb.AppendLine("using " + item + ";"); sb.AppendLine(); sb.AppendLine("namespace " + file.NameSpace + " {"); foreach (var item in file.Classes) { sb.Append(item.AccessModifierString); - if (item.IsStatic) { - sb.Append(" static"); - } - if (item.IsPartial) { - sb.Append(" partial"); - } - if (item.IsAbstract) { - sb.Append(" abstract"); - } - if (item.IsSealed) { - sb.Append(" sealed"); - } - if (item.IsInterface) { - sb.Append(" interface"); - } - if (item.IsEnum) { - sb.Append(" enum"); - } - if (item.IsStruct) { - sb.Append(" struct"); - } - if (item.IsDelegate) { - sb.Append(" delegate"); - } - if (item.IsRecord) { - sb.Append(" record"); - } + if (item.IsStatic) sb.Append(" static"); + if (item.IsPartial) sb.Append(" partial"); + if (item.IsAbstract) sb.Append(" abstract"); + if (item.IsSealed) sb.Append(" sealed"); + if (item.IsInterface) sb.Append(" interface"); + if (item.IsEnum) sb.Append(" enum"); + if (item.IsStruct) sb.Append(" struct"); + if (item.IsDelegate) sb.Append(" delegate"); + if (item.IsRecord) sb.Append(" record"); sb.Append(" class " + item.Name + " {"); sb.AppendLine(); foreach (var prop in item.Properties) { sb.Append(prop.AccessModifierString); - if (prop.IsStatic) { - sb.Append(" static"); - } - sb.Append(prop.ValueType.Name.ToString()); - if (prop.IsReadOnly) { - sb.Append(" readonly"); - } + if (prop.IsStatic) sb.Append(" static"); + sb.Append(prop.ValueType.Name); + if (prop.IsReadOnly) sb.Append(" readonly"); if (prop.IsField) { sb.Append(prop.Name + ";"); sb.AppendLine(); continue; } + sb.Append(" " + prop.Name + " { "); - if (prop.GetterAccessModifierString != "") { - sb.Append(prop.GetterAccessModifierString +" "); - } + if (prop.GetterAccessModifierString != "") sb.Append(prop.GetterAccessModifierString + " "); sb.Append("get;"); - if (prop.SetterAccessModifierString != "") { - sb.Append(prop.SetterAccessModifierString + " "); - } + if (prop.SetterAccessModifierString != "") sb.Append(prop.SetterAccessModifierString + " "); sb.Append("set;"); sb.Append("}"); sb.AppendLine(); - } + sb.AppendLine("}"); sb.AppendLine(); } + sb.AppendLine("}"); var text = sb.ToString(); File.WriteAllText("exported.cs", text); diff --git a/src/EasMe.SharpBuilder/SharpFileBuilder.cs b/src/EasMe.SharpBuilder/SharpFileBuilder.cs index ce37db01..93dc2b0f 100644 --- a/src/EasMe.SharpBuilder/SharpFileBuilder.cs +++ b/src/EasMe.SharpBuilder/SharpFileBuilder.cs @@ -2,7 +2,8 @@ namespace EasMe.SharpBuilder; -public class SharpFileBuilder { +public class SharpFileBuilder +{ private readonly SharpFile _sharpFile; public SharpFileBuilder() { diff --git a/src/EasMe.SharpBuilder/SharpPropertyBuilder.cs b/src/EasMe.SharpBuilder/SharpPropertyBuilder.cs index 0afe58fa..fa0006c8 100644 --- a/src/EasMe.SharpBuilder/SharpPropertyBuilder.cs +++ b/src/EasMe.SharpBuilder/SharpPropertyBuilder.cs @@ -2,7 +2,8 @@ namespace EasMe.SharpBuilder; -public class SharpPropertyBuilder { +public class SharpPropertyBuilder +{ private readonly SharpProperty _property; public SharpPropertyBuilder() { @@ -48,6 +49,7 @@ public SharpPropertyBuilder ReadOnly() { _property.IsReadOnly = true; return this; } + public SharpProperty Build() { return _property; } diff --git a/src/EasMe.System/EasMe.System.csproj b/src/EasMe.System/EasMe.System.csproj index a535d738..d1625498 100644 --- a/src/EasMe.System/EasMe.System.csproj +++ b/src/EasMe.System/EasMe.System.csproj @@ -1,29 +1,29 @@ - - net6.0 - enable - enable - C:\Users\kkass\source\build\easme - 2.0.0 - 2.0.0 - EasMe.System - bberka - Windows System information helper for creating device id or retreiving device information. Only windows supported. - https://github.com/bberka/EasMe/tree/master - https://github.com/bberka/EasMe/blob/master/LICENSE.txt - https://github.com/bberka/EasMe/tree/master - true + + net6.0 + enable + enable + C:\Users\kkass\source\build\easme + 2.0.0 + 2.0.0 + EasMe.System + bberka + Windows System information helper for creating device id or retreiving device information. Only windows supported. + https://github.com/bberka/EasMe/tree/master + https://github.com/bberka/EasMe/blob/master/LICENSE.txt + https://github.com/bberka/EasMe/tree/master + true - + - - - + + + - - - + + + diff --git a/src/EasMe.System/EasStartup.cs b/src/EasMe.System/EasStartup.cs index 5c042a16..1d08889c 100644 --- a/src/EasMe.System/EasStartup.cs +++ b/src/EasMe.System/EasStartup.cs @@ -2,7 +2,8 @@ namespace EasMe.System; -public static class EasStartup { +public static class EasStartup +{ public static void AddToLaunchOnOSStartup(string applicationName, string applicationExecutablePath) { var rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); rk?.SetValue(applicationName, applicationExecutablePath); diff --git a/src/EasMe.System/EasSystem.cs b/src/EasMe.System/EasSystem.cs index 16337718..023a1bc4 100644 --- a/src/EasMe.System/EasSystem.cs +++ b/src/EasMe.System/EasSystem.cs @@ -7,17 +7,18 @@ namespace EasMe.System; -public static class EasSystem { +public static class EasSystem +{ /// /// Returns this computers MAC Address. /// /// public static string GetMACAddress() { var macAddr = ( - from nic in NetworkInterface.GetAllNetworkInterfaces() - where nic.OperationalStatus == OperationalStatus.Up - select nic.GetPhysicalAddress().ToString() - ).FirstOrDefault(); + from nic in NetworkInterface.GetAllNetworkInterfaces() + where nic.OperationalStatus == OperationalStatus.Up + select nic.GetPhysicalAddress().ToString() + ).FirstOrDefault(); if (!string.IsNullOrEmpty(macAddr)) return macAddr; var active = GetMACAddresses_Active(); @@ -37,18 +38,18 @@ select nic.GetPhysicalAddress().ToString() public static List GetMACAddresses_Active() { return NetworkInterface.GetAllNetworkInterfaces() - .Where(x => x.OperationalStatus == OperationalStatus.Up) - .Select(x => x.GetPhysicalAddress().ToString()) - .Where(x => !string.IsNullOrEmpty(x)) - .ToList(); + .Where(x => x.OperationalStatus == OperationalStatus.Up) + .Select(x => x.GetPhysicalAddress().ToString()) + .Where(x => !string.IsNullOrEmpty(x)) + .ToList(); } public static List GetMACAddresses_All() { return NetworkInterface.GetAllNetworkInterfaces() - .OrderBy(x => x.OperationalStatus == OperationalStatus.Up) - .Select(x => x.GetPhysicalAddress().ToString()) - .Where(x => !string.IsNullOrEmpty(x)) - .ToList(); + .OrderBy(x => x.OperationalStatus == OperationalStatus.Up) + .Select(x => x.GetPhysicalAddress().ToString()) + .Where(x => !string.IsNullOrEmpty(x)) + .ToList(); } /// @@ -133,7 +134,7 @@ public static string GetGpuName() { public static string GetProcessorName() { var CPUName = Convert.ToString(Registry.GetValue( - "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\SYSTEM\\CentralProcessor\\0", "ProcessorNameString", null)); + "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\SYSTEM\\CentralProcessor\\0", "ProcessorNameString", null)); return CPUName?.Trim() ?? ""; } @@ -388,7 +389,7 @@ public static string GetDiskUUID() { oProcess.Start(); oProcess.WaitForExit(); var result = oProcess.StandardOutput.ReadToEnd(); - return result.TrimAbsolute().RemoveLineEndings(); + return result.RemoveWhiteSpace().RemoveLineEndings(); } public static NetworkInfoModel GetNetworkInfo_Client() { @@ -401,11 +402,11 @@ public static NetworkInfoModel GetNetworkInfo_Client() { var warp = bodyLines[12].Split("=")[1].StringConversion(); var gateway = bodyLines[13].Split("=")[1].StringConversion(); return new NetworkInfoModel { - IpAddress = ip, - IsGatewayOn = gateway, - IsWarpOn = warp, - Location = loc - }; + IpAddress = ip, + IsGatewayOn = gateway, + IsWarpOn = warp, + Location = loc + }; } #region Read System.Management diff --git a/src/EasMe.System/Models/BiosModel.cs b/src/EasMe.System/Models/BiosModel.cs index 4ead5067..3a57b3e1 100644 --- a/src/EasMe.System/Models/BiosModel.cs +++ b/src/EasMe.System/Models/BiosModel.cs @@ -1,6 +1,7 @@ namespace EasMe.System.Models; -public class BiosModel { +public class BiosModel +{ public string? BiosCharacteristics { get; set; } public string? BiosVersion { get; set; } public string? Caption { get; set; } @@ -11,7 +12,9 @@ public class BiosModel { public string? Name { get; set; } public string? PrimaryBios { get; set; } public string? ReleaseDate { get; set; } + public string? SerialNumber { get; set; } + // public string? SMBIOSBIOSVersion { get; set; } // public string? SMBIOSMajorVersion { get; set; } // public string? SMBIOSMinorVersion { get; set; } diff --git a/src/EasMe.System/Models/CpuModel.cs b/src/EasMe.System/Models/CpuModel.cs index 2b357e15..ba446f78 100644 --- a/src/EasMe.System/Models/CpuModel.cs +++ b/src/EasMe.System/Models/CpuModel.cs @@ -1,6 +1,7 @@ namespace EasMe.System.Models; -public class CpuModel { +public class CpuModel +{ public string? AddressWidth { get; set; } public string? Architecture { get; set; } public string? AssetTag { get; set; } diff --git a/src/EasMe.System/Models/DiskModel.cs b/src/EasMe.System/Models/DiskModel.cs index a0362b98..5bec0403 100644 --- a/src/EasMe.System/Models/DiskModel.cs +++ b/src/EasMe.System/Models/DiskModel.cs @@ -1,6 +1,7 @@ namespace EasMe.System.Models; -public class DiskModel { +public class DiskModel +{ public string? BytesPerSector { get; set; } public string? Capabilities { get; set; } public string? CapabilityDescriptions { get; set; } diff --git a/src/EasMe.System/Models/GpuModel.cs b/src/EasMe.System/Models/GpuModel.cs index 84fa1ae4..1d7b485e 100644 --- a/src/EasMe.System/Models/GpuModel.cs +++ b/src/EasMe.System/Models/GpuModel.cs @@ -1,6 +1,7 @@ namespace EasMe.System.Models; -public class GpuModel { +public class GpuModel +{ public string? AdapterCompatibility { get; set; } public string? AdapterDACType { get; set; } public string? AdapterRAM { get; set; } diff --git a/src/EasMe.System/Models/MotherboardModel.cs b/src/EasMe.System/Models/MotherboardModel.cs index 8621d47a..8f6b4cc7 100644 --- a/src/EasMe.System/Models/MotherboardModel.cs +++ b/src/EasMe.System/Models/MotherboardModel.cs @@ -1,6 +1,7 @@ namespace EasMe.System.Models; -public class MotherboardModel { +public class MotherboardModel +{ public string? Caption { get; set; } public string? ConfigOptions { get; set; } public string? CreationClassName { get; set; } diff --git a/src/EasMe.System/Models/NetworkInfoModel.cs b/src/EasMe.System/Models/NetworkInfoModel.cs index 32d8f449..601cecf2 100644 --- a/src/EasMe.System/Models/NetworkInfoModel.cs +++ b/src/EasMe.System/Models/NetworkInfoModel.cs @@ -2,7 +2,8 @@ namespace EasMe.System.Models; -public class NetworkInfoModel { +public class NetworkInfoModel +{ private string? _IpAddress; public string? IpAddress { diff --git a/src/EasMe.System/Models/RamModel.cs b/src/EasMe.System/Models/RamModel.cs index 625d4a20..fa9a0a54 100644 --- a/src/EasMe.System/Models/RamModel.cs +++ b/src/EasMe.System/Models/RamModel.cs @@ -1,6 +1,7 @@ namespace EasMe.System.Models; -public class RamModel { +public class RamModel +{ public string? Attributes { get; set; } public string? BankLabel { get; set; } public string? Capacity { get; set; } diff --git a/src/EasMe.Test/EasMe.Test.csproj b/src/EasMe.Test/EasMe.Test.csproj index 13a0a5d5..254f5da8 100644 --- a/src/EasMe.Test/EasMe.Test.csproj +++ b/src/EasMe.Test/EasMe.Test.csproj @@ -1,20 +1,20 @@ - - Exe - net6.0 - enable - enable - 3.5 - + + Exe + net6.0 + enable + enable + 3.5 + - - - - + + + + - - - + + + diff --git a/src/EasMe.Test/Program.cs b/src/EasMe.Test/Program.cs index d8acdfbd..56db5079 100644 --- a/src/EasMe.Test/Program.cs +++ b/src/EasMe.Test/Program.cs @@ -1,6 +1,33 @@ -using System.Text; -using EasMe; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; +Console.WriteLine(); -Console.WriteLine(); +// DateTime pastDateTime = DateTime.Now.AddHours(-5); +// string pastReadableString = pastDateTime.ToReadableDateString(); +// Console.WriteLine(pastReadableString); // Output: 5 hours ago +// +// var futureDateTime = DateTime.Now.AddHours(5); +// var futureReadableString = futureDateTime.ToReadableDateString(); +// Console.WriteLine(futureReadableString); // Output: 5 hours from now +// +// DateTime pastDateTime2 = DateTime.Now.AddDays(-2).AddHours(-3); +// string pastReadableString2 = pastDateTime2.ToReadableDateString(); +// Console.WriteLine(pastReadableString2); // Output: 2 days, 3 hours ago +// +// DateTime futureDateTime2 = DateTime.Now.AddDays(2).AddHours(3); +// string futureReadableString2 = futureDateTime2.ToReadableDateString(); +// Console.WriteLine(futureReadableString2); // Output: 2 days, 3 hours from now +// +// DateTime pastDateTime3 = DateTime.Now.AddMonths(-1).AddDays(-2).AddHours(-3); +// string pastReadableString3 = pastDateTime3.ToReadableDateString(); +// Console.WriteLine(pastReadableString3); // Output: 1 month, 2 days, 3 hours ago +// +// DateTime futureDateTime3 = DateTime.Now.AddMonths(1).AddDays(2).AddHours(3); +// string futureReadableString3 = futureDateTime3.ToReadableDateString(); +// Console.WriteLine(futureReadableString3); // Output: 1 month, 2 days, 3 hours from now +// +// DateTime pastDateTime4 = DateTime.Now.AddYears(-2).AddMonths(-1).AddDays(-2).AddHours(-3); +// string pastReadableString4 = pastDateTime4.ToReadableDateString(); +// Console.WriteLine(pastReadableString4); // Output: 2 years, 1 month, 2 days, 3 hours ago +// +// DateTime futureDateTime4 = DateTime.Now.AddYears(2).AddMonths(1).AddDays(2).AddHours(3); +// string futureReadableString4 = futureDateTime4.ToReadableDateString(); +// Console.WriteLine(futureReadableString4); \ No newline at end of file diff --git a/src/EasMe.Test/bin/Release/net6.0/EasMe.Test.dll b/src/EasMe.Test/bin/Release/net6.0/EasMe.Test.dll index 0e5ad57b..9646d505 100644 Binary files a/src/EasMe.Test/bin/Release/net6.0/EasMe.Test.dll and b/src/EasMe.Test/bin/Release/net6.0/EasMe.Test.dll differ diff --git a/src/EasMe.Test/bin/Release/net6.0/EasMe.Test.pdb b/src/EasMe.Test/bin/Release/net6.0/EasMe.Test.pdb index e288cddd..8e87db87 100644 Binary files a/src/EasMe.Test/bin/Release/net6.0/EasMe.Test.pdb and b/src/EasMe.Test/bin/Release/net6.0/EasMe.Test.pdb differ diff --git a/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.csproj.AssemblyReference.cache b/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.csproj.AssemblyReference.cache index 84d62e4b..8151d401 100644 Binary files a/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.csproj.AssemblyReference.cache and b/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.csproj.AssemblyReference.cache differ diff --git a/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.dll b/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.dll index 0e5ad57b..9646d505 100644 Binary files a/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.dll and b/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.dll differ diff --git a/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.pdb b/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.pdb index e288cddd..8e87db87 100644 Binary files a/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.pdb and b/src/EasMe.Test/obj/Release/net6.0/EasMe.Test.pdb differ diff --git a/src/EasMe/EasAPI.cs b/src/EasMe/EasAPI.cs index bc7cb750..ade21abd 100644 --- a/src/EasMe/EasAPI.cs +++ b/src/EasMe/EasAPI.cs @@ -3,125 +3,143 @@ namespace EasMe; -public static class EasAPI { - //Install-Package Microsoft.AspNet.WebApi.Client -Version 5.2.8 - - - public static HttpResponseMessage SendGetRequest(string URL, string? TOKEN = null, int timeout = 10) { +public static class EasAPI +{ + public static HttpResponseMessage SendGetRequest(string url, + string? token = null, + int timeout = 10) { var client = new HttpClient(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); client.Timeout = TimeSpan.FromSeconds(timeout); - client.BaseAddress = new Uri(URL); + client.BaseAddress = new Uri(url); var postTask = client.GetAsync(client.BaseAddress); postTask.Wait(); return postTask.Result; } - public static T? SendGetRequestAndGetResponseAsJson(string URL, string? TOKEN = null, int timeout = 10) { + public static T? SendGetRequestAndGetResponseAsJson(string url, + string? token = null, + int timeout = 10) { var client = new HttpClient(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); client.Timeout = TimeSpan.FromSeconds(timeout); - client.BaseAddress = new Uri(URL); + client.BaseAddress = new Uri(url); var postTask = client.GetAsync(client.BaseAddress); postTask.Wait(); var content = postTask.Result.Content.ReadFromJsonAsync().GetAwaiter().GetResult(); return content; } - public static T? SendPostRequestAsJsonAndGetResponseAsJson(string URL, object Data, string? TOKEN = null, - int timeout = 10) { + public static T? SendPostRequestAsJsonAndGetResponseAsJson(string url, + object data, + string? token = null, + int timeout = 10) { HttpClient client = new(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); - client.BaseAddress = new Uri(URL); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromSeconds(timeout); - var postTask = client.PostAsJsonAsync(URL, Data); + var postTask = client.PostAsJsonAsync(url, data); postTask.Wait(); var content = postTask.Result.Content.ReadFromJsonAsync().GetAwaiter().GetResult(); return content; } - public static HttpResponseMessage SendPostRequestAsJson(string URL, object Data, string? TOKEN = null, - int timeout = 10) { + public static HttpResponseMessage SendPostRequestAsJson(string url, + object data, + string? token = null, + int timeout = 10) { HttpClient client = new(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); - client.BaseAddress = new Uri(URL); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromSeconds(timeout); - var postTask = client.PostAsJsonAsync(URL, Data); + var postTask = client.PostAsJsonAsync(url, data); postTask.Wait(); return postTask.Result; } - public static HttpResponseMessage SendPostRequest(string URL, HttpContent Content, string? TOKEN = null, - int timeout = 10) { + public static HttpResponseMessage SendPostRequest(string url, + HttpContent content, + string? token = null, + int timeout = 10) { HttpClient client = new(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); - client.BaseAddress = new Uri(URL); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromSeconds(timeout); - var postTask = client.PostAsync(URL, Content); + var postTask = client.PostAsync(url, content); postTask.Wait(); return postTask.Result; } - public static HttpResponseMessage SendDeleteRequest(string URL, string? TOKEN = null, int timeout = 10) { + public static HttpResponseMessage SendDeleteRequest(string url, + string? token = null, + int timeout = 10) { HttpClient client = new(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); - client.BaseAddress = new Uri(URL); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromSeconds(timeout); - var postTask = client.DeleteAsync(URL); + var postTask = client.DeleteAsync(url); postTask.Wait(); return postTask.Result; } - public static HttpResponseMessage SendPatchRequest(string URL, HttpContent Content, string? TOKEN = null, - int timeout = 10) { + public static HttpResponseMessage SendPatchRequest(string url, + HttpContent content, + string? token = null, + int timeout = 10) { var client = new HttpClient(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); - client.BaseAddress = new Uri(URL); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromSeconds(timeout); - var postTask = client.PatchAsync(URL, Content); + var postTask = client.PatchAsync(url, content); postTask.Wait(); return postTask.Result; } - public static HttpResponseMessage SendPutRequest(string URL, HttpContent Content, string? TOKEN = null, - int timeout = 10) { + public static HttpResponseMessage SendPutRequest(string url, + HttpContent content, + string? token = null, + int timeout = 10) { HttpClient client = new(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); - client.BaseAddress = new Uri(URL); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromSeconds(timeout); - var postTask = client.PutAsync(URL, Content); + var postTask = client.PutAsync(url, content); postTask.Wait(); return postTask.Result; } - public static HttpResponseMessage SendPutRequestAsJson(string URL, object Data, string? TOKEN = null, - int timeout = 10) { + public static HttpResponseMessage SendPutRequestAsJson(string url, + object data, + string? token = null, + int timeout = 10) { var client = new HttpClient(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); - client.BaseAddress = new Uri(URL); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromSeconds(timeout); - var postTask = client.PutAsJsonAsync(URL, Data); + var postTask = client.PutAsJsonAsync(url, data); postTask.Wait(); return postTask.Result; } - public static HttpResponseMessage Send(string URL, HttpRequestMessage Data, string? TOKEN = null, - int timeout = 10) { + public static HttpResponseMessage Send(string url, + HttpRequestMessage data, + string? token = null, + int timeout = 10) { var client = new HttpClient(); - if (!string.IsNullOrEmpty(TOKEN)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN); - client.BaseAddress = new Uri(URL); + if (!string.IsNullOrEmpty(token)) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromSeconds(timeout); - var postTask = client.Send(Data); + var postTask = client.Send(data); return postTask; } } \ No newline at end of file diff --git a/src/EasMe/EasArgument.cs b/src/EasMe/EasArgument.cs deleted file mode 100644 index 435f90a2..00000000 --- a/src/EasMe/EasArgument.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace EasMe; - -public static class EasArgument { - //public static T GetReadByOrder(int index) - //{ - // var arg = EasArgumentManager.GetArgument(index); - // return - //} - - //public static string[] GetArgumentNames(int index) - //{ - // return - //} -} diff --git a/src/EasMe/EasCache.cs b/src/EasMe/EasCache.cs index fd453623..ad18849e 100644 --- a/src/EasMe/EasCache.cs +++ b/src/EasMe/EasCache.cs @@ -4,22 +4,23 @@ /// Simple thread-safe variable cache helper. /// /// -public class EasCache { +public class EasCache +{ private static readonly object _locker = new(); private readonly Func _action; - private readonly int INTERVAL; + private readonly int _interval; + private DateTime _lastUpdate; private TData _result; - private DateTime LAST_UPDATE; public EasCache(Func action, int intervalMinutes) { - INTERVAL = intervalMinutes; + _interval = intervalMinutes; _action = action; //_result = _action(); - LAST_UPDATE = DateTime.MinValue; + _lastUpdate = DateTime.MinValue; } public TData Get() { - var isUpdateTime = LAST_UPDATE.AddMinutes(INTERVAL) < DateTime.Now; + var isUpdateTime = _lastUpdate.AddMinutes(_interval) < DateTime.Now; if (!isUpdateTime) return _result; lock (_locker) { if (!isUpdateTime) return _result; @@ -31,7 +32,7 @@ public TData Get() { public void Refresh() { _result = _action(); - LAST_UPDATE = DateTime.Now; + _lastUpdate = DateTime.Now; } } @@ -41,7 +42,8 @@ public void Refresh() { /// public class EasCache where TData : class - where TIn : class { + where TIn : class +{ private static readonly object _locker = new(); private readonly Func _action; private readonly int INTERVAL; diff --git a/src/EasMe/EasCheck.cs b/src/EasMe/EasCheck.cs index c6634bd8..200d256a 100644 --- a/src/EasMe/EasCheck.cs +++ b/src/EasMe/EasCheck.cs @@ -2,7 +2,8 @@ namespace EasMe; -public enum PasswordScore { +public enum PasswordScore +{ Blank = 0, VeryWeak = 1, Weak = 2, @@ -11,7 +12,8 @@ public enum PasswordScore { VeryStrong = 5 } -public class EasCheck { +public class EasCheck +{ public static PasswordScore CheckPasswordStrength(string password) { var score = 0; diff --git a/src/EasMe/EasConfig.cs b/src/EasMe/EasConfig.cs index b26d3ef7..ba84c519 100644 --- a/src/EasMe/EasConfig.cs +++ b/src/EasMe/EasConfig.cs @@ -2,7 +2,8 @@ namespace EasMe; -public static class EasConfig { +public static class EasConfig +{ public static string? GetConnectionString(string key) { return ConfigurationManager.ConnectionStrings[key]?.ConnectionString; } diff --git a/src/EasMe/EasDirectory.cs b/src/EasMe/EasDirectory.cs index e1a9eeab..f0ed2a6c 100644 --- a/src/EasMe/EasDirectory.cs +++ b/src/EasMe/EasDirectory.cs @@ -2,7 +2,8 @@ namespace EasMe; -public enum KnownFolder { +public enum KnownFolder +{ /// /// Guid: 56784854-C6CB-462B-8169-88E350ACB882 /// @@ -34,22 +35,23 @@ public enum KnownFolder { SavedSearches } -public static class EasDirectory { +public static class EasDirectory +{ private static readonly IReadOnlyDictionary _guids = new Dictionary { - [KnownFolder.Contacts] = new("56784854-C6CB-462B-8169-88E350ACB882"), - [KnownFolder.Downloads] = new("374DE290-123F-4565-9164-39C4925E467B"), - [KnownFolder.Favorites] = new("1777F761-68AD-4D8A-87BD-30B759FA33DD"), - [KnownFolder.Links] = new("BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968"), - [KnownFolder.SavedGames] = new("4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4"), - [KnownFolder.SavedSearches] = new("7D1D3A04-DEBB-4115-95CF-2F29DA2920DA") - }; + [KnownFolder.Contacts] = new("56784854-C6CB-462B-8169-88E350ACB882"), + [KnownFolder.Downloads] = new("374DE290-123F-4565-9164-39C4925E467B"), + [KnownFolder.Favorites] = new("1777F761-68AD-4D8A-87BD-30B759FA33DD"), + [KnownFolder.Links] = new("BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968"), + [KnownFolder.SavedGames] = new("4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4"), + [KnownFolder.SavedSearches] = new("7D1D3A04-DEBB-4115-95CF-2F29DA2920DA") + }; public static string GetPath(KnownFolder knownFolder) { return SHGetKnownFolderPath(_guids[knownFolder], 0); } [DllImport("shell32", - CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)] + CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)] private static extern string SHGetKnownFolderPath( [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, nint hToken = 0); diff --git a/src/EasMe/EasEncrypt.cs b/src/EasMe/EasEncrypt.cs index 06120fac..a62c6b2d 100644 --- a/src/EasMe/EasEncrypt.cs +++ b/src/EasMe/EasEncrypt.cs @@ -4,45 +4,107 @@ namespace EasMe; /// -/// Basic string encryption and decryption class. +/// Encryption manager for encrypting and decrypting strings. Different instances of this class will have different +/// keys. +/// For client and server matching key, key is generated based on a time formula. It will be same if created in same +/// second. /// -public class EasEncrypt { - private static string _encryptKey = null!; +public class EasEncrypt +{ + private static string _additionalKey = "XmMqPLuQkkrKaNmCvRGyceZNDdquhTJokckfPdcKPjeekkooeaSmBGDNwEaqDFJq"; + private static short _seed; + private static bool _dontUseEncryption; + private readonly byte[] _ivBytes; + private readonly byte[] _keyBytes; - private static readonly byte[] _salt = - { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }; + public EasEncrypt() { + var key = CreateKey(); + using var sha256 = SHA256.Create(); + var keyHash = sha256.ComputeHash(key); + _keyBytes = new byte[32]; + _ivBytes = new byte[16]; + Array.Copy(keyHash, _keyBytes, 32); + Array.Copy(keyHash, 0, _ivBytes, 0, 16); + } + + /// + /// Set whether to use encryption or not. If set to false, encryption will not be used. You can pass debug variables + /// here for testing. + /// + /// + public static void SetDontUseEncryption(bool dontUseEncryption) { + _dontUseEncryption = dontUseEncryption; + } + + public static void SetAdditionalKey(string key) { + _additionalKey = key; + } - public EasEncrypt(string key) { - _encryptKey = key; + public static void SetSeed(short seed) { + _seed = seed; } + private static DateTime GetDate() { + var now = DateTime.UtcNow; + var second = now.Second; + var ms = now.Millisecond; + now = now.AddHours(+second + _seed); + now = now.AddYears(-second - _seed); + now = now.AddMonths(+second + _seed); + now = now.AddDays(-second - _seed); + now = now.AddMinutes(+second + _seed); + now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); + return now; + } + + + private static byte[] CreateKey() { + var time = GetDate(); + var ticks = time.Ticks; + var str = ticks + "|" + _additionalKey; + var key = str.SHA256Hash(); + return key; + } - public string EncryptString(string clearText) { - var clearBytes = Encoding.Unicode.GetBytes(clearText); + public string Encrypt(string plainText) { + if (_dontUseEncryption) return plainText; + var plainBytes = Encoding.UTF8.GetBytes(plainText); using var aes = Aes.Create(); - var pdb = new Rfc2898DeriveBytes(_encryptKey, _salt); - aes.Key = pdb.GetBytes(32); - aes.IV = pdb.GetBytes(16); - using var ms = new MemoryStream(); - using var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write); - cs.Write(clearBytes, 0, clearBytes.Length); - cs.Close(); - clearText = Convert.ToBase64String(ms.ToArray()); - return clearText; - } - - public string DecryptString(string cipherText) { - cipherText = cipherText.Replace(" ", "+"); - var cipherBytes = Convert.FromBase64String(cipherText); + aes.Key = _keyBytes; + aes.IV = _ivBytes; + var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); + var encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length); + return Convert.ToBase64String(encryptedBytes); + } + + public string Decrypt(string encryptedText) { + if (_dontUseEncryption) return encryptedText; + var encryptedBytes = Convert.FromBase64String(encryptedText); + using var aes = Aes.Create(); + aes.Key = _keyBytes; + aes.IV = _ivBytes; + var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); + var decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); + return Encoding.UTF8.GetString(decryptedBytes); + } + + public Stream DecryptStream(Stream stream) { + if (_dontUseEncryption) return stream; + using var aes = Aes.Create(); + aes.Key = _keyBytes; + aes.IV = _ivBytes; + var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); + var cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read); + return cryptoStream; + } + + public Stream EncryptStream(Stream stream) { + if (_dontUseEncryption) return stream; using var aes = Aes.Create(); - var pdb = new Rfc2898DeriveBytes(_encryptKey, _salt); - aes.Key = pdb.GetBytes(32); - aes.IV = pdb.GetBytes(16); - using var ms = new MemoryStream(); - using var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write); - cs.Write(cipherBytes, 0, cipherBytes.Length); - cs.Close(); - cipherText = Encoding.Unicode.GetString(ms.ToArray()); - return cipherText; + aes.Key = _keyBytes; + aes.IV = _ivBytes; + var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); + var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Read); + return cryptoStream; } } \ No newline at end of file diff --git a/src/EasMe/EasFile.cs b/src/EasMe/EasFile.cs index 573f5877..0e295455 100644 --- a/src/EasMe/EasFile.cs +++ b/src/EasMe/EasFile.cs @@ -1,13 +1,13 @@ using System.Data.HashFunction.xxHash; using System.Security.Cryptography; -using EasMe.Exceptions; namespace EasMe; /// /// File or folder deletion with logging options, uses EasLog /// -public static class EasFile { +public static class EasFile +{ private const int BYTES_TO_READ = sizeof(long); private static readonly ReaderWriterLock _locker = new(); @@ -31,7 +31,7 @@ public static void DeleteAll(string filePath) { else if (File.Exists(filePath)) File.Delete(filePath); else - throw new NotExistException("Error in DeleteAll: Given File or folder does not exist => Path: " + filePath); + throw new FileNotFoundException("File or folder not found", filePath); } /// @@ -48,13 +48,13 @@ public static void MoveAll(string sourcePath, string destPath, bool overwrite) { var subdirs = Directory.GetDirectories(sourcePath); Parallel.ForEach(files, file => { File.Move(file, destPath + "\\" + Path.GetFileName(file), true); }); Parallel.ForEach(subdirs, - subdir => { MoveAll(subdir, destPath + "\\" + Path.GetFileName(subdir), overwrite); }); + subdir => { MoveAll(subdir, destPath + "\\" + Path.GetFileName(subdir), overwrite); }); } else if (File.Exists(sourcePath)) { File.Move(sourcePath, destPath + "\\" + Path.GetFileName(sourcePath), true); } else { - throw new NotExistException("Error in MoveAll: Given source path not exist."); + throw new FileNotFoundException("Given source path not exist.", sourcePath); } } @@ -63,22 +63,20 @@ public static void MoveAll(string sourcePath, string destPath, bool overwrite) { /// the actual folder. /// /// - /// - /// - /// - public static void CopyAll(string sourcePath, string destPath, bool overWrite = false) { - if (!Directory.Exists(destPath)) Directory.CreateDirectory(destPath); + /// + public static void CopyAll(string sourcePath, string destinationPath, bool overwrite = false) { + if (!Directory.Exists(destinationPath)) Directory.CreateDirectory(destinationPath); if (Directory.Exists(sourcePath)) { var files = Directory.GetFiles(sourcePath); var subdirs = Directory.GetDirectories(sourcePath); - Parallel.ForEach(files, file => { File.Copy(file, destPath + "\\" + Path.GetFileName(file), overWrite); }); - Parallel.ForEach(subdirs, subdir => { CopyAll(subdir, destPath + "\\" + Path.GetFileName(subdir)); }); + Parallel.ForEach(files, file => { File.Copy(file, destinationPath + "\\" + Path.GetFileName(file), overwrite); }); + Parallel.ForEach(subdirs, subdir => { CopyAll(subdir, destinationPath + "\\" + Path.GetFileName(subdir)); }); } else if (File.Exists(sourcePath)) { - File.Copy(sourcePath, destPath + "\\" + Path.GetFileName(sourcePath), overWrite); + File.Copy(sourcePath, destinationPath + "\\" + Path.GetFileName(sourcePath), overwrite); } else { - throw new NotExistException("Error in CopyAll: Given source path not exist."); + throw new FileNotFoundException("Given source path not exist.", sourcePath); } } @@ -109,19 +107,15 @@ public static bool FilesAreEqual(FileInfo first, FileInfo second) { if (first.Length != second.Length) return false; var iterations = (int)Math.Ceiling((double)first.Length / BYTES_TO_READ); - - using (var fs1 = first.OpenRead()) - using (var fs2 = second.OpenRead()) { - var one = new byte[BYTES_TO_READ]; - var two = new byte[BYTES_TO_READ]; - - for (var i = 0; i < iterations; i++) { - fs1.Read(one, 0, BYTES_TO_READ); - fs2.Read(two, 0, BYTES_TO_READ); - - if (BitConverter.ToInt64(one, 0) != BitConverter.ToInt64(two, 0)) - return false; - } + using var fs1 = first.OpenRead(); + using var fs2 = second.OpenRead(); + var one = new byte[BYTES_TO_READ]; + var two = new byte[BYTES_TO_READ]; + for (var i = 0; i < iterations; i++) { + var r1 = fs1.Read(one, 0, BYTES_TO_READ); + var r2 = fs2.Read(two, 0, BYTES_TO_READ); + if (r1 != r2) + return false; } return true; @@ -134,12 +128,11 @@ public static bool FilesAreEqual_OneByte(FileInfo first, FileInfo second) { if (string.Equals(first.FullName, second.FullName, StringComparison.OrdinalIgnoreCase)) return true; - using (var fs1 = first.OpenRead()) - using (var fs2 = second.OpenRead()) { - for (var i = 0; i < first.Length; i++) - if (fs1.ReadByte() != fs2.ReadByte()) - return false; - } + using var fs1 = first.OpenRead(); + using var fs2 = second.OpenRead(); + for (var i = 0; i < first.Length; i++) + if (fs1.ReadByte() != fs2.ReadByte()) + return false; return true; } @@ -147,11 +140,7 @@ public static bool FilesAreEqual_OneByte(FileInfo first, FileInfo second) { public static bool FilesAreEqual_MD5Hash(FileInfo first, FileInfo second) { var firstHash = MD5.Create().ComputeHash(first.OpenRead()); var secondHash = MD5.Create().ComputeHash(second.OpenRead()); - - for (var i = 0; i < firstHash.Length; i++) - if (firstHash[i] != secondHash[i]) - return false; - return true; + return !firstHash.Where((t, i) => t != secondHash[i]).Any(); } public static bool FilesAreEqual_XXHash(FileInfo first, FileInfo second) { diff --git a/src/EasMe/EasGenerate.cs b/src/EasMe/EasGenerate.cs index f224cf98..658c418b 100644 --- a/src/EasMe/EasGenerate.cs +++ b/src/EasMe/EasGenerate.cs @@ -1,22 +1,22 @@ using System.Security.Cryptography; using System.Text; -using EasMe.Exceptions; namespace EasMe; -public static class EasGenerate { - private const string CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; +public static class EasGenerate +{ + private const string Characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; /// /// Generates and returns a random GUID string without "-" /// /// - public static string GenerateGuidString() { + public static string GenerateCleanGuidString() { return Guid.NewGuid().ToString().Replace("-", ""); } public static string GetRandomString(ushort length) { - var charArray = CHARACTERS.ToCharArray(); + var charArray = Characters.ToCharArray(); var result = new StringBuilder(length); for (var i = 0; i < length; i++) { var random = RandomNumberGenerator.GetInt32(charArray.Length); @@ -34,16 +34,19 @@ public static string GetRandomString(ushort length) { /// /// private static string GenerateString(string chars, int length) { - if (length > 2048) - throw new TooBigValueException( - "Given length to create random string is too big. Max allowed length value is 1024."); - if (length < 1) - throw new TooSmallValueException( - "Given length to create random string is too small. Min allowed length value is 1."); + switch (length) { + case > 2048: + throw new InvalidDataException( + "Given length to create random string is too big. Max allowed length value is 1024."); + case < 1: + throw new InvalidDataException( + "Given length to create random string is too small. Min allowed length value is 1."); + } + var random = new Random(); string resultToken = new( - Enumerable.Repeat(chars, length) - .Select(token => token[random.Next(token.Length)]).ToArray()); + Enumerable.Repeat(chars, length) + .Select(token => token[random.Next(token.Length)]).ToArray()); return resultToken; } diff --git a/src/EasMe/EasHash.cs b/src/EasMe/EasHash.cs index b37a7276..ff896092 100644 --- a/src/EasMe/EasHash.cs +++ b/src/EasMe/EasHash.cs @@ -7,7 +7,8 @@ namespace EasMe; -public static class EasHash { +public static class EasHash +{ private static byte[] ComputeHash(HashAlgorithm algorithm, string rawData) { return algorithm.ComputeHash(rawData.ConvertToByteArray()); } diff --git a/src/EasMe/EasHttp.cs b/src/EasMe/EasHttp.cs index 5515eeb0..be932f1c 100644 --- a/src/EasMe/EasHttp.cs +++ b/src/EasMe/EasHttp.cs @@ -2,7 +2,8 @@ namespace EasMe; -public static class EasHttp { +public static class EasHttp +{ public static string GetStatusCodeShortMessage(uint httpStatusCode) { var statusCode = (HttpStatusCode)httpStatusCode; var str = statusCode.ToString(); @@ -19,66 +20,66 @@ public static string GetHostIpAddress() { public static string GetStatusCodeLongMessage(uint httpStatusCode) { return httpStatusCode switch { - 100 => "Continue", - 101 => "Switching Protocols", - 102 => "Processing", - 103 => "Early Hints", - 200 => "OK", - 201 => "Created", - 202 => "Accepted", - 203 => "Non-Authoritative Information", - 204 => "No Content", - 205 => "Reset Content", - 206 => "Partial Content", - 207 => "Multi-Status", - 208 => "Already Reported", - 226 => "Used", - 300 => "Multiple Choices", - 301 => "Moved Permanently", - 302 => "Found", - 303 => "See Other", - 304 => "Not Modified", - 305 => "Use Proxy", - 306 => "Switch Proxy", - 307 => "Temporary Redirect", - 308 => "Permanent Redirect", - 400 => "Bad Request", - 401 => "Unauthorized", - 402 => "Payment Required", - 403 => "Forbidden", - 404 => "Not Found", - 405 => "Method Not Allowed", - 406 => "Not Acceptable", - 407 => "Proxy Authentication Required", - 408 => "Request Timeout", - 409 => "Conflict", - 410 => "Gone", - 411 => "Length Required", - 412 => "Precondition Failed", - 413 => "Payload Too Large", - 414 => "URI Too Long", - 415 => "Unsupported Media Type", - 416 => "Range Not Satisfiable", - 417 => "Expectation Failed", - 418 => "I'm a teapot", - 421 => "Misdirected Request", - 422 => "Unprocessable Entity", - 423 => "Locked", - 424 => "Failed Dependency", - 425 => "Too Early", - 426 => "Upgrade Required", - 428 => "Precondition Required", - 429 => "Too Many Requests", - 431 => "Request Header Fields Too Large", - 451 => "Unavailable For Legal Reasons", - 500 => "Internal Server Error", - 501 => "Not Implemented", - 502 => "Bad Gateway", - 503 => "Service Unavailable", - 504 => "Gateway Timeout", - 505 => "HTTP Version Not Supported", - 506 => "Variant Also Negot", - _ => "" - }; + 100 => "Continue", + 101 => "Switching Protocols", + 102 => "Processing", + 103 => "Early Hints", + 200 => "OK", + 201 => "Created", + 202 => "Accepted", + 203 => "Non-Authoritative Information", + 204 => "No Content", + 205 => "Reset Content", + 206 => "Partial Content", + 207 => "Multi-Status", + 208 => "Already Reported", + 226 => "Used", + 300 => "Multiple Choices", + 301 => "Moved Permanently", + 302 => "Found", + 303 => "See Other", + 304 => "Not Modified", + 305 => "Use Proxy", + 306 => "Switch Proxy", + 307 => "Temporary Redirect", + 308 => "Permanent Redirect", + 400 => "Bad Request", + 401 => "Unauthorized", + 402 => "Payment Required", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 406 => "Not Acceptable", + 407 => "Proxy Authentication Required", + 408 => "Request Timeout", + 409 => "Conflict", + 410 => "Gone", + 411 => "Length Required", + 412 => "Precondition Failed", + 413 => "Payload Too Large", + 414 => "URI Too Long", + 415 => "Unsupported Media Type", + 416 => "Range Not Satisfiable", + 417 => "Expectation Failed", + 418 => "I'm a teapot", + 421 => "Misdirected Request", + 422 => "Unprocessable Entity", + 423 => "Locked", + 424 => "Failed Dependency", + 425 => "Too Early", + 426 => "Upgrade Required", + 428 => "Precondition Required", + 429 => "Too Many Requests", + 431 => "Request Header Fields Too Large", + 451 => "Unavailable For Legal Reasons", + 500 => "Internal Server Error", + 501 => "Not Implemented", + 502 => "Bad Gateway", + 503 => "Service Unavailable", + 504 => "Gateway Timeout", + 505 => "HTTP Version Not Supported", + 506 => "Variant Also Negot", + _ => "" + }; } } \ No newline at end of file diff --git a/src/EasMe/EasINI.cs b/src/EasMe/EasINI.cs index 6644d3cd..22a9ce49 100644 --- a/src/EasMe/EasINI.cs +++ b/src/EasMe/EasINI.cs @@ -1,27 +1,27 @@ using System.Runtime.InteropServices; using System.Text; -using EasMe.Exceptions; namespace EasMe; -public class EasINI { - private readonly string _path = string.Empty; +public class EasINI +{ + private readonly string _path; public EasINI(string? iniFilePath = null) { - if (iniFilePath == null) iniFilePath = Directory.GetCurrentDirectory() + @"\service.ini"; + iniFilePath ??= Directory.GetCurrentDirectory() + @"\service.ini"; if (!File.Exists(iniFilePath)) - throw new NotExistException("Given INI file path does not exist: " + iniFilePath); + throw new ArgumentNullException("iniFilePath"); _path = iniFilePath; } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, - string lpFileName); + string lpFileName); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, - int size, string filePath); + int size, string filePath); /// /// Writes a value to the INI file @@ -100,22 +100,26 @@ private static string WriteToString(IniFile model) { } } -public class IniFile { +public class IniFile +{ public List Sections { get; set; } = new(); } -public class IniSection { +public class IniSection +{ public string? Name { get; set; } public List Data { get; set; } = new(); public List Comments { get; set; } = new(); } -public class IniData { +public class IniData +{ public string? Key { get; set; } public string? Value { get; set; } } -public class IniComment { +public class IniComment +{ public int LineNo { get; set; } = -1; public string? Comment { get; set; } } \ No newline at end of file diff --git a/src/EasMe/EasJWT.cs b/src/EasMe/EasJWT.cs index ec659fd2..a3255a14 100644 --- a/src/EasMe/EasJWT.cs +++ b/src/EasMe/EasJWT.cs @@ -8,8 +8,9 @@ namespace EasMe; /// /// JWT Authentication helper, generating and reading tokens. /// -public class EasJWT { - private readonly JwtSecurityTokenHandler TokenHandler = new(); +public class EasJWT +{ + private readonly JwtSecurityTokenHandler _tokenHandler = new(); public EasJWT(string secret, string? issuer = null, string? audience = null) { Issuer = issuer; @@ -38,13 +39,13 @@ public string GenerateJwtToken(ClaimsIdentity claimsIdentity, int expireMinutes) public string GenerateJwtToken(ClaimsIdentity claimsIdentity, DateTime expire) { var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { - Subject = claimsIdentity, - Expires = expire, - SigningCredentials = - new SigningCredentials(new SymmetricSecurityKey(Secret), SecurityAlgorithms.HmacSha256Signature), - Issuer = Issuer, - Audience = Audience - }; + Subject = claimsIdentity, + Expires = expire, + SigningCredentials = + new SigningCredentials(new SymmetricSecurityKey(Secret), SecurityAlgorithms.HmacSha256Signature), + Issuer = Issuer, + Audience = Audience + }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } @@ -62,19 +63,19 @@ public string GenerateJwtToken(Dictionary claims, int expireMin public string GenerateJwtToken(Dictionary claims, DateTime expire) { var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { - Claims = claims, - Expires = expire, - SigningCredentials = - new SigningCredentials(new SymmetricSecurityKey(Secret), SecurityAlgorithms.HmacSha256Signature), - Issuer = Issuer, - Audience = Audience - }; + Claims = claims, + Expires = expire, + SigningCredentials = + new SigningCredentials(new SymmetricSecurityKey(Secret), SecurityAlgorithms.HmacSha256Signature), + Issuer = Issuer, + Audience = Audience + }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } /// - /// Validates JWT token and returns ClaimsPrincipal. + /// Validates JWT token and returns ClaimsPrincipal. Throws if validation fails /// /// /// @@ -82,15 +83,15 @@ public string GenerateJwtToken(Dictionary claims, DateTime expi /// public ClaimsPrincipal? ValidateJwtToken(string token) { var tokenValidationParameters = new TokenValidationParameters { - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(Secret), - ValidateIssuer = ValidateIssuer, - ValidateAudience = ValidateAudience, - ValidateLifetime = true, - RequireExpirationTime = true, - ClockSkew = TimeSpan.Zero - }; - var claims = TokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken); + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Secret), + ValidateIssuer = ValidateIssuer, + ValidateAudience = ValidateAudience, + ValidateLifetime = true, + RequireExpirationTime = true, + ClockSkew = TimeSpan.Zero + }; + var claims = _tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken); return claims; } } \ No newline at end of file diff --git a/src/EasMe/EasMail.cs b/src/EasMe/EasMail.cs index 696b902f..6ae86960 100644 --- a/src/EasMe/EasMail.cs +++ b/src/EasMe/EasMail.cs @@ -1,31 +1,31 @@ using System.Net; using System.Net.Mail; -using EasMe.Exceptions; namespace EasMe; /// /// Simple mail sender /// -public class EasMail { +public class EasMail +{ /// /// Mail sender class, uses SMTP protocol. /// - /// - /// - /// - /// - /// + /// + /// + /// + /// + /// public EasMail(string host, - string mailAddress, - string password, - int port, - bool enableSSL = false) { + string mailAddress, + string password, + int port, + bool enableSsl = false) { Host = host; MailAddress = mailAddress; Password = password; Port = port; - EnableSSL = enableSSL; + EnableSSL = enableSsl; } private string Host { get; } @@ -37,27 +37,28 @@ public EasMail(string host, /// /// Sends mail, better to create thread for this function. /// - /// - /// - /// - public void SendMail(string Subject, string Body, string SendTo, bool isBodyHtml = false) { + /// + /// + /// + /// + public void SendMail(string subject, string body, string sendTo, bool isBodyHtml = false) { try { var fromAddress = new MailAddress(MailAddress); - var toAddress = new MailAddress(SendTo); + var toAddress = new MailAddress(sendTo); using var smtp = new SmtpClient { - Host = Host, - Port = Port, - EnableSsl = EnableSSL, - DeliveryMethod = SmtpDeliveryMethod.Network, - UseDefaultCredentials = false, - Credentials = new NetworkCredential(fromAddress.Address, Password) - }; - using var message = new MailMessage(fromAddress, toAddress) { Subject = Subject, Body = Body }; + Host = Host, + Port = Port, + EnableSsl = EnableSSL, + DeliveryMethod = SmtpDeliveryMethod.Network, + UseDefaultCredentials = false, + Credentials = new NetworkCredential(fromAddress.Address, Password) + }; + using var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }; message.IsBodyHtml = isBodyHtml; smtp.Send(message); } catch (Exception ex) { - throw new EmailSendFailedException("Failed to send email.", ex); + throw new Exception("Failed to send email.", ex); } } } \ No newline at end of file diff --git a/src/EasMe/EasMe.csproj b/src/EasMe/EasMe.csproj index f42c05ff..66634a24 100644 --- a/src/EasMe/EasMe.csproj +++ b/src/EasMe/EasMe.csproj @@ -1,43 +1,43 @@  - - net6.0 - enable - enable - MIT - true - Debug;Release - C:\Users\kkass\source\build\easme - AnyCPU - 3.5.0 - 3.5.0 - true - EasMe - bberka - CSharp extender library. Contains various extension methods, helper classes. - https://github.com/bberka/EasMe/tree/master - https://github.com/bberka/EasMe/blob/master/LICENSE.txt - https://github.com/bberka/EasMe/tree/master - + + net6.0 + enable + enable + MIT + true + Debug;Release + C:\Users\kkass\source\build\easme + AnyCPU + 3.5.0 + 4.0.0 + true + EasMe + bberka + CSharp extender library. Contains various extension methods, helper classes. + https://github.com/bberka/EasMe/tree/master + https://github.com/bberka/EasMe/blob/master/LICENSE.txt + https://github.com/bberka/EasMe/tree/master + - - - + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/EasMe/EasMemoryCache.cs b/src/EasMe/EasMemoryCache.cs index 1aeb5a7b..89e7f5c2 100644 --- a/src/EasMe/EasMemoryCache.cs +++ b/src/EasMe/EasMemoryCache.cs @@ -1,9 +1,10 @@ namespace EasMe; -public class EasMemoryCache { - private static EasMemoryCache? Instance; +public class EasMemoryCache +{ + private static EasMemoryCache? _instance; - private static readonly Dictionary cacheDictionary = new(); + private static readonly Dictionary CacheDictionary = new(); private EasMemoryCache() { ClearLoop(); @@ -11,33 +12,33 @@ private EasMemoryCache() { public static EasMemoryCache This { get { - Instance ??= new EasMemoryCache(); - return Instance; + _instance ??= new EasMemoryCache(); + return _instance; } } private void ClearLoop() { Task.Run(() => { - while (true) { - var items = cacheDictionary.Where(x => x.Value.ExpireDateTime < DateTime.Now).Select(x => x.Key) - .ToList(); - if (items.Count > 0) - lock (cacheDictionary) { - foreach (var key in items) cacheDictionary.Remove(key); - } - - Thread.Sleep(1000); - } - }); + while (true) { + var items = CacheDictionary.Where(x => x.Value.ExpireDateTime < DateTime.Now).Select(x => x.Key) + .ToList(); + if (items.Count > 0) + lock (CacheDictionary) { + foreach (var key in items) CacheDictionary.Remove(key); + } + + Thread.Sleep(1000); + } + }); } public T? Get(string key) { //return cacheDictionary.ContainsKey(key) ? cacheDictionary[key].Value.ToString().StringConversion() : default; - return cacheDictionary.ContainsKey(key) ? (T?)cacheDictionary[key].Value : default; + return CacheDictionary.TryGetValue(key, out var value) ? (T?)value.Value : default; } public T GetOrSet(string key, Func func, int expireSeconds = 60) { - if (cacheDictionary.ContainsKey(key)) return (T)cacheDictionary[key].Value; + if (CacheDictionary.TryGetValue(key, out var value)) return (T)value.Value; var res = func(); if (res is null) return default; Set(key, res, expireSeconds); @@ -45,39 +46,40 @@ public T GetOrSet(string key, Func func, int expireSeconds = 60) { } public object? Get(string key) { - return cacheDictionary.ContainsKey(key) ? cacheDictionary[key].Value : null; + return CacheDictionary.TryGetValue(key, out var value) ? value.Value : null; } public void Set(string key, object value, int expireSeconds = 60) { - if (cacheDictionary.ContainsKey(key)) - lock (cacheDictionary) { - cacheDictionary.Remove(key); + if (CacheDictionary.ContainsKey(key)) + lock (CacheDictionary) { + CacheDictionary.Remove(key); } var data = new CacheData(value, DateTime.Now + TimeSpan.FromSeconds(expireSeconds)); - lock (cacheDictionary) { - cacheDictionary.Add(key, data); + lock (CacheDictionary) { + CacheDictionary.Add(key, data); } } public bool Exists(string key) { - return cacheDictionary.ContainsKey(key); + return CacheDictionary.ContainsKey(key); } public void Remove(string key) { - if (cacheDictionary.ContainsKey(key)) - lock (cacheDictionary) { - cacheDictionary.Remove(key); - } + if (!CacheDictionary.ContainsKey(key)) return; + lock (CacheDictionary) { + CacheDictionary.Remove(key); + } } public void Clear() { - lock (cacheDictionary) { - cacheDictionary.Clear(); + lock (CacheDictionary) { + CacheDictionary.Clear(); } } - private class CacheData { + private class CacheData + { public CacheData(object value, DateTime expireDateTime) { Value = value; ExpireDateTime = expireDateTime; diff --git a/src/EasMe/EasQL.cs b/src/EasMe/EasQL.cs index 3b08b7be..62429d34 100644 --- a/src/EasMe/EasQL.cs +++ b/src/EasMe/EasQL.cs @@ -1,5 +1,4 @@ using System.Data; -using EasMe.Exceptions; using EasMe.Extensions; using Microsoft.Data.SqlClient; @@ -8,90 +7,80 @@ namespace EasMe; /// /// SQL helper, used to execute SQL queries, and get data from SQL database. /// -public class EasQL { +public class EasQL +{ + private readonly string _connection; + public EasQL(string connection) { if (!connection.IsValidConnectionString()) - throw new NotValidException("EasQL given connection string is not valid"); - Connection = connection; + throw new InvalidDataException("EasQL given connection string is not valid"); + _connection = connection; } - private static string? Connection { get; set; } /// /// Executes SQL query and returns DataTable. /// - /// /// - /// + /// /// - /// - public DataTable GetTable(SqlCommand cmd, int Timeout = 0) { - return GetTable(Connection, cmd, Timeout); + public DataTable GetTable(SqlCommand cmd, int timeout = 0) { + return GetTable(_connection, cmd, timeout); } /// /// Exectues SQL query and returns affected row count. /// - /// /// /// /// - /// public int ExecNonQuery(SqlCommand cmd, int Timeout = 0) { - return ExecNonQuery(Connection, cmd, Timeout); + return ExecNonQuery(_connection, cmd, Timeout); } public async Task ExecNonQueryAsync(SqlCommand cmd, int timeout = 0) { - return await Task.Run(() => { return ExecNonQuery(Connection, cmd, timeout); }); + return await Task.Run(() => { return ExecNonQuery(_connection, cmd, timeout); }); } /// /// Exectues SQL query and returns the first column of first row in the result set returned by query. Additional /// columns or rows ignored. /// - /// /// - /// + /// /// - /// - public object ExecScalar(SqlCommand cmd, int Timeout = 0) { - return ExecScalar(Connection, cmd, Timeout); + public object ExecScalar(SqlCommand cmd, int timeout = 0) { + return ExecScalar(_connection, cmd, timeout); } public async Task ExecScalarAsync(SqlCommand cmd, int timeout = 0) { - return await Task.Run(() => { return ExecScalar(Connection, cmd, timeout); }); + return await Task.Run(() => { return ExecScalar(_connection, cmd, timeout); }); } /// /// Executes a SQL query to backup database to the given folder path. /// - /// - /// - /// - /// - /// - public void BackupDatabase(string BackupPath, int Timeout = 0) { - BackupDatabase(Connection, BackupPath, Timeout); + /// + /// + public void BackupDatabase(string backupPath, int timeout = 0) { + BackupDatabase(_connection, backupPath, timeout); } - public async Task BackupDatabaseAsync(string BackupPath, int Timeout = 0) { - await Task.Run(() => { BackupDatabase(BackupPath, Timeout); }); + public async Task BackupDatabaseAsync(string backupPath, int timeout = 0) { + await Task.Run(() => { BackupDatabase(backupPath, timeout); }); } /// /// Executes a SQL query to shrink your database and SQL log data. This action will not lose you any real data but /// still you should backup first. /// - /// - /// - /// - /// - public void ShrinkDatabase(string DatabaseLogName = "_log") { - ShrinkDatabase(Connection, DatabaseLogName); + /// + public void ShrinkDatabase(string databaseLogName = "_log") { + ShrinkDatabase(_connection, databaseLogName); } - public async Task ShrinkDatabaseAsync(string DatabaseLogName = "_log") { - await Task.Run(() => { ShrinkDatabase(DatabaseLogName); }); + public async Task ShrinkDatabaseAsync(string databaseLogName = "_log") { + await Task.Run(() => { ShrinkDatabase(databaseLogName); }); } @@ -99,15 +88,13 @@ public async Task ShrinkDatabaseAsync(string DatabaseLogName = "_log") { /// Deletes all records in given table but keeps the table. This action can not be undone, be aware of the risks before /// running this. /// - /// - /// - /// - public void TruncateTable(string TableName) { - TruncateTable(Connection, TableName); + /// + public void TruncateTable(string tableName) { + TruncateTable(_connection, tableName); } - public async Task TruncateTableAsync(string TableName) { - await Task.Run(() => { TruncateTable(TableName); }); + public async Task TruncateTableAsync(string tableName) { + await Task.Run(() => { TruncateTable(tableName); }); } @@ -115,36 +102,30 @@ public async Task TruncateTableAsync(string TableName) { /// Deletes all records in the table and the table from database. This action can not be undone, be aware of the risks /// before running this. /// - /// - /// - /// - public void DropTable(string TableName) { - DropTable(Connection, TableName); + /// + public void DropTable(string tableName) { + DropTable(_connection, tableName); } - public async Task DropTableAsync(string TableName) { - await Task.Run(() => { DropTable(TableName); }); + public async Task DropTableAsync(string tableName) { + await Task.Run(() => { DropTable(tableName); }); } /// /// Deletes all records and all tables and the database entirely. This action can not be undone, be aware of the risks /// before running this. /// - /// - /// - /// - public void DropDatabase(string DatabaseName) { - DropDatabase(Connection, DatabaseName); + /// + public void DropDatabase(string databaseName) { + DropDatabase(_connection, databaseName); } /// /// Gets all table names in SQL database and returns. /// - /// /// - /// public List GetAllTableName() { - return GetAllTableName(Connection); + return GetAllTableName(_connection); } @@ -157,7 +138,6 @@ public List GetAllTableName() { /// /// /// - /// public static DataTable GetTable(string connection, SqlCommand cmd, int timeout = 0) { DataTable dt = new(); using var conn = new SqlConnection(connection); @@ -176,42 +156,40 @@ public static async Task GetTableAsync(string connection, SqlCommand /// /// Exectues SQL query and returns affected row count. /// - /// + /// /// - /// + /// /// - /// - public static int ExecNonQuery(string Connection, SqlCommand cmd, int Timeout = 0) { - using SqlConnection conn = new(Connection); + public static int ExecNonQuery(string connection, SqlCommand cmd, int timeout = 0) { + using SqlConnection conn = new(connection); cmd.Connection = conn; - cmd.CommandTimeout = Timeout; + cmd.CommandTimeout = timeout; conn.Open(); return cmd.ExecuteNonQuery(); } public static async Task ExecNonQueryAsync(string connection, SqlCommand cmd, int timeout = 0) { - return await Task.Run(() => { return ExecNonQuery(connection, cmd, timeout); }); + return await Task.Run(() => ExecNonQuery(connection, cmd, timeout)); } /// /// Exectues SQL query and returns the first column of first row in the result set returned by query. Additional /// columns or rows ignored. /// - /// + /// /// - /// + /// /// - /// - public static object ExecScalar(string Connection, SqlCommand cmd, int Timeout = 0) { - using SqlConnection conn = new(Connection); + public static object ExecScalar(string connection, SqlCommand cmd, int timeout = 0) { + using SqlConnection conn = new(connection); cmd.Connection = conn; - cmd.CommandTimeout = Timeout; + cmd.CommandTimeout = timeout; conn.Open(); return cmd.ExecuteScalar(); } public static async Task ExecScalarAsync(string connection, SqlCommand cmd, int timeout = 0) { - return await Task.Run(() => { return ExecScalar(connection, cmd, timeout); }); + return await Task.Run(() => ExecScalar(connection, cmd, timeout)); } public static void BackupDatabase(string connection, string backupFolderPath, int timeout = 0) { @@ -227,80 +205,77 @@ public static async Task BackupDatabaseAsync(string connection, string backupFol await Task.Run(() => { BackupDatabase(connection, backupFolderPath, timeout); }); } - public static void ShrinkDatabase(string Connection, string DatabaseLogName = "_log") { - var DatabaseName = Connection.ParseDatabaseName(); - if (DatabaseLogName == "_log") DatabaseLogName = DatabaseName + DatabaseLogName; + public static void ShrinkDatabase(string connection, string databaseLogName = "_log") { + var databaseName = connection.ParseDatabaseName() ?? throw new ArgumentNullException("connection.ParseDatabaseName()"); + if (databaseLogName == "_log") databaseLogName = databaseName + databaseLogName; var query = $@"BEGIN - ALTER DATABASE [{DatabaseName}] SET RECOVERY SIMPLE WITH NO_WAIT - DBCC SHRINKFILE(N'{DatabaseLogName}', 1) - ALTER DATABASE [{DatabaseName}] SET RECOVERY FULL WITH NO_WAIT + ALTER DATABASE [{databaseName}] SET RECOVERY SIMPLE WITH NO_WAIT + DBCC SHRINKFILE(N'{databaseLogName}', 1) + ALTER DATABASE [{databaseName}] SET RECOVERY FULL WITH NO_WAIT END BEGIN - ALTER DATABASE [{DatabaseName}] SET RECOVERY SIMPLE WITH NO_WAIT - DBCC SHRINKFILE(N'{DatabaseName}', 1) - ALTER DATABASE [{DatabaseName}] SET RECOVERY FULL WITH NO_WAIT + ALTER DATABASE [{databaseName}] SET RECOVERY SIMPLE WITH NO_WAIT + DBCC SHRINKFILE(N'{databaseName}', 1) + ALTER DATABASE [{databaseName}] SET RECOVERY FULL WITH NO_WAIT END"; var cmd = new SqlCommand(query); - ExecNonQuery(Connection, cmd); + ExecNonQuery(connection, cmd); } - public static async Task ShrinkDatabaseAsync(string Connection, string DatabaseLogName = "_log") { - await Task.Run(() => { ShrinkDatabase(Connection, DatabaseLogName); }); + public static async Task ShrinkDatabaseAsync(string connection, string databaseLogName = "_log") { + await Task.Run(() => { ShrinkDatabase(connection, databaseLogName); }); } - public static void TruncateTable(string Connection, string TableName) { - var query = $@"TRUNCATE TABLE {TableName}"; + public static void TruncateTable(string connection, string tableName) { + var query = $@"TRUNCATE TABLE {tableName}"; var cmd = new SqlCommand(query); - ExecNonQuery(Connection, cmd); + ExecNonQuery(connection, cmd); } - public static async Task TruncateTableAsync(string Connection, string TableName) { - await Task.Run(() => { TruncateTable(Connection, TableName); }); + public static async Task TruncateTableAsync(string connection, string tableName) { + await Task.Run(() => { TruncateTable(connection, tableName); }); } /// /// Deletes all records in the table and the table from database. This action can not be undone, be aware of the risks /// before running this. /// - /// - /// - /// - public static void DropTable(string Connection, string TableName) { - var query = $@"DROP TABLE {TableName}"; + /// + /// + public static void DropTable(string connection, string tableName) { + var query = $@"DROP TABLE {tableName}"; var cmd = new SqlCommand(query); - ExecNonQuery(Connection, cmd); + ExecNonQuery(connection, cmd); } - public static async Task DropTableAsync(string Connection, string TableName) { - await Task.Run(() => { DropTable(Connection, TableName); }); + public static async Task DropTableAsync(string connection, string tableName) { + await Task.Run(() => { DropTable(connection, tableName); }); } /// /// Deletes all records and all tables and the database entirely. This action can not be undone, be aware of the risks /// before running this. /// - /// - /// - /// - public static void DropDatabase(string Connection, string DatabaseName) { - var query = $@"DROP DATABASE {DatabaseName}"; + /// + /// + public static void DropDatabase(string connection, string databaseName) { + var query = $@"DROP DATABASE {databaseName}"; var cmd = new SqlCommand(query); - ExecNonQuery(Connection, cmd); + ExecNonQuery(connection, cmd); } /// /// Gets all table names in SQL database and returns. /// - /// + /// /// - /// - public static List GetAllTableName(string Connection) { + public static List GetAllTableName(string connection) { var query = @"SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']' FROM sys.tables"; var list = new List(); var cmd = new SqlCommand(query); - var dt = GetTable(Connection, cmd); + var dt = GetTable(connection, cmd); foreach (DataRow row in dt.Rows) list.Add(row[0].ToString()); return list; } diff --git a/src/EasMe/EasReCaptcha.cs b/src/EasMe/EasReCaptcha.cs index da9b6d76..2f9b597f 100644 --- a/src/EasMe/EasReCaptcha.cs +++ b/src/EasMe/EasReCaptcha.cs @@ -1,29 +1,29 @@ -using System.Net; -using EasMe.Exceptions; +using System.ComponentModel.DataAnnotations; +using System.Net; using EasMe.Extensions; using EasMe.Models; using Newtonsoft.Json.Linq; namespace EasMe; -public static class EasReCaptcha { +public static class EasReCaptcha +{ /// /// Validates given CaptchtaResponse from Google by SecretKey. /// - /// - /// + /// + /// /// - /// - public static CaptchaResponseModel Validate(string Secret, string? CaptchaResponse) { + public static CaptchaResponseModel Validate(string secret, string? captchaResponse) { try { - if (CaptchaResponse.IsNullOrEmpty()) + if (captchaResponse.IsNullOrEmpty()) return new CaptchaResponseModel { - Success = false - }; + Success = false + }; var response = new CaptchaResponseModel(); var client = new WebClient(); var result = client.DownloadString(string.Format( - $"https://www.google.com/recaptcha/api/siteverify?secret={Secret}&response={CaptchaResponse}")); + $"https://www.google.com/recaptcha/api/siteverify?secret={secret}&response={captchaResponse}")); var obj = JObject.Parse(result); response.Success = (bool)obj.SelectToken("success"); response.ChallengeTS = (DateTime)obj.SelectToken("challenge_ts"); @@ -32,7 +32,7 @@ public static CaptchaResponseModel Validate(string Secret, string? CaptchaRespon return response; } catch (Exception ex) { - throw new FailedToValidateException("Could not validate reCaptcha.", ex); + throw new ValidationException("Could not validate reCaptcha.", ex); } } } \ No newline at end of file diff --git a/src/EasMe/EasTask.cs b/src/EasMe/EasTask.cs index 9ab419e3..90050c37 100644 --- a/src/EasMe/EasTask.cs +++ b/src/EasMe/EasTask.cs @@ -3,7 +3,8 @@ /// /// Runs a queue of Tasks in the background with a single thread /// -public class EasTask : IDisposable { +public class EasTask : IDisposable +{ private readonly ManualResetEvent _hasNewItems = new(false); private readonly Queue _queue = new(); private readonly ManualResetEvent _terminate = new(false); @@ -13,8 +14,8 @@ public class EasTask : IDisposable { public EasTask() { _thread = new Thread(ProcessQueue) { - IsBackground = true - }; + IsBackground = true + }; // this is performed from a bg thread, to ensure the queue is serviced from a single thread _thread.Start(); } @@ -58,4 +59,4 @@ public void AddToQueue(Action action) { public void Flush() { _waiting.WaitOne(); } -} +} \ No newline at end of file diff --git a/src/EasMe/EasValidate.cs b/src/EasMe/EasValidate.cs index 35d44eb4..3501f373 100644 --- a/src/EasMe/EasValidate.cs +++ b/src/EasMe/EasValidate.cs @@ -2,11 +2,11 @@ using System.Net; using System.Net.Mail; using System.Text.RegularExpressions; -using EasMe.Exceptions; namespace EasMe; -public static class EasValidate { +public static class EasValidate +{ /// /// Returns true if given string is valid email address. /// @@ -29,12 +29,12 @@ public static bool IsValidEmail(this string str) { /// returns true if given string is valid IP address. /// /// - /// + /// /// - public static bool IsValidIPAddress(this string value, out IPAddress? IpAddress) { - IpAddress = null; + public static bool IsValidIpAddress(this string value, out IPAddress? ipAddress) { + ipAddress = null; if (IPAddress.TryParse(value, out var address)) { - IpAddress = address; + ipAddress = address; return true; } @@ -44,10 +44,10 @@ public static bool IsValidIPAddress(this string value, out IPAddress? IpAddress) /// /// Return true if given string is valid IP address. /// - /// + /// /// - public static bool IsValidIPAddress(this string IpAddress) { - return IpAddress.IsValidIPAddress(out var IpVersion); + public static bool IsValidIpAddress(this string ipAddress) { + return ipAddress.IsValidIpAddress(out _); } //It's not quite possible make %100 sure it is correct but this will do for most cases @@ -66,9 +66,9 @@ public static bool IsValidFilePath(this string path) { /// /// /// - public static bool IsValidMACAddress(this string macAddress) { - var MACRegex = "^[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}$"; - if (!Regex.IsMatch(macAddress, MACRegex)) + public static bool IsValidMacAddress(this string macAddress) { + const string macRegex = "^[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}$"; + if (!Regex.IsMatch(macAddress, macRegex)) return false; return true; } @@ -79,8 +79,8 @@ public static bool IsValidMACAddress(this string macAddress) { /// /// public static bool IsValidPort(this int port) { - var PortRegex = "^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"; - if (!Regex.IsMatch(port.ToString(), PortRegex)) + const string portRegex = "^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"; + if (!Regex.IsMatch(port.ToString(), portRegex)) return false; return true; } @@ -115,8 +115,8 @@ public static bool HasSpecialChars(this string yourString, string allowedChars = /// /// public static bool IsStrongPassword(this string password, string allowedChars, byte minLength = 6, - byte maxLength = 16, byte minUpperCaseCount = 1, byte minLowerCaseCount = 1, byte minNumberCount = 1, - byte minSpecialCharCount = 1) { + byte maxLength = 16, byte minUpperCaseCount = 1, byte minLowerCaseCount = 1, byte minNumberCount = 1, + byte minSpecialCharCount = 1) { if (password.Length < minLength || password.Length > maxLength) return false; if (HasSpecialChars(password, allowedChars)) @@ -139,7 +139,7 @@ public static bool IsStrongPassword(this string password, string allowedChars, b /// public static bool IsUrlImage(this string URL) { try { - if (!URL.IsValidURL()) return false; + if (!URL.IsValidUrl()) return false; var client = new HttpClient(); var req = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, URL)).Result.Content.Headers.ContentType; if (req != null) @@ -149,31 +149,31 @@ public static bool IsUrlImage(this string URL) { return false; } catch (Exception ex) { - throw new FailedToCheck("Failed to check if URL is image: " + URL, ex); + throw new Exception("Failed to check if URL is image: " + URL, ex); } } /// /// Returns true if given URL is Video. /// - /// + /// /// - public static bool IsUrlVideo(this string URL) { + public static bool IsUrlVideo(this string url) { try { - if (!URL.IsValidURL()) return false; + if (!url.IsValidUrl()) return false; var client = new HttpClient(); - var req = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, URL)).Result.Content.Headers.ContentType; + var req = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url)).Result.Content.Headers.ContentType; if (req != null) return req.ToString().ToLower().StartsWith("video/"); - if (URL.Contains(".mp4") || URL.Contains(".avi") || URL.Contains(".mkv") || URL.Contains(".wmv") || - URL.Contains(".flv") || URL.Contains(".mov") || URL.Contains(".mpeg") || URL.Contains(".mpg") || - URL.Contains(".webm")) + if (url.Contains(".mp4") || url.Contains(".avi") || url.Contains(".mkv") || url.Contains(".wmv") || + url.Contains(".flv") || url.Contains(".mov") || url.Contains(".mpeg") || url.Contains(".mpg") || + url.Contains(".webm")) return true; return false; } catch (Exception ex) { - throw new FailedToCheck("Failed to check if given URL is video: " + URL, ex); + throw new Exception("Failed to check if given URL is video: " + url, ex); } } @@ -182,15 +182,14 @@ public static bool IsUrlVideo(this string URL) { /// /// /// - public static bool IsValidURL(this string url) { + public static bool IsValidUrl(this string url) { return Uri.IsWellFormedUriString(url, UriKind.Absolute); } /// /// Returns true if given string is a valid database connection string. /// - /// - /// + /// /// public static bool IsValidConnectionString(this string yourConn) { try { diff --git a/src/EasMe/EasZip.cs b/src/EasMe/EasZip.cs index 0826c869..0bf97561 100644 --- a/src/EasMe/EasZip.cs +++ b/src/EasMe/EasZip.cs @@ -2,8 +2,9 @@ namespace EasMe; -public static class EasZip { - public static void MakeZip(string[] files, string destination) { +public static class EasZip +{ + public static void MakeZip(IEnumerable files, string destination) { var index = destination.LastIndexOf("\\", StringComparison.Ordinal); var destinationFolder = destination[..index]; if (!Directory.Exists(destinationFolder)) Directory.CreateDirectory(destinationFolder); diff --git a/src/EasMe/Exceptions/AlreadyExistsException.cs b/src/EasMe/Exceptions/AlreadyExistsException.cs deleted file mode 100644 index 3c30d4a3..00000000 --- a/src/EasMe/Exceptions/AlreadyExistsException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class AlreadyExistsException : Exception { - public AlreadyExistsException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public AlreadyExistsException(string message) : base(message) { - } - - public AlreadyExistsException(Exception? Inner = null) : base("AlreadyExistsException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/AlreadyInUseException.cs b/src/EasMe/Exceptions/AlreadyInUseException.cs deleted file mode 100644 index d5ec5821..00000000 --- a/src/EasMe/Exceptions/AlreadyInUseException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class AlreadyInUseException : Exception { - public AlreadyInUseException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public AlreadyInUseException(string message) : base(message) { - } - - public AlreadyInUseException(Exception? Inner = null) : base("AlreadyInUseException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/AlreadyLoadedException.cs b/src/EasMe/Exceptions/AlreadyLoadedException.cs deleted file mode 100644 index 0f7e0653..00000000 --- a/src/EasMe/Exceptions/AlreadyLoadedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class AlreadyLoadedException : Exception { - public AlreadyLoadedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public AlreadyLoadedException(string message) : base(message) { - } - - public AlreadyLoadedException(Exception? Inner = null) : base("AlreadyLoadedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/AlreadyUsedException.cs b/src/EasMe/Exceptions/AlreadyUsedException.cs deleted file mode 100644 index 920d26a0..00000000 --- a/src/EasMe/Exceptions/AlreadyUsedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class AlreadyUsedException : Exception { - public AlreadyUsedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public AlreadyUsedException(string message) : base(message) { - } - - public AlreadyUsedException(Exception? Inner = null) : base("AlreadyUsedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/ApiFailedToGetResponseException.cs b/src/EasMe/Exceptions/ApiFailedToGetResponseException.cs deleted file mode 100644 index 74d5b549..00000000 --- a/src/EasMe/Exceptions/ApiFailedToGetResponseException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class ApiFailedToGetResponseException : Exception { - public ApiFailedToGetResponseException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public ApiFailedToGetResponseException(string message) : base(message) { - } - - public ApiFailedToGetResponseException(Exception? Inner = null) : base("ApiFailedToGetResponseException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/ApiSendFailedToDeleteException.cs b/src/EasMe/Exceptions/ApiSendFailedToDeleteException.cs deleted file mode 100644 index a2551fdd..00000000 --- a/src/EasMe/Exceptions/ApiSendFailedToDeleteException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class ApiSendFailedToDeleteException : Exception { - public ApiSendFailedToDeleteException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public ApiSendFailedToDeleteException(string message) : base(message) { - } - - public ApiSendFailedToDeleteException(Exception? Inner = null) : base("ApiSendFailedToDeleteException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/ApiSendFailedToGetException.cs b/src/EasMe/Exceptions/ApiSendFailedToGetException.cs deleted file mode 100644 index 294b65ab..00000000 --- a/src/EasMe/Exceptions/ApiSendFailedToGetException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class ApiSendFailedToGetException : Exception { - public ApiSendFailedToGetException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public ApiSendFailedToGetException(string message) : base(message) { - } - - public ApiSendFailedToGetException(Exception? Inner = null) : base("ApiSendFailedToGetException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/ApiSendFailedToPatchException.cs b/src/EasMe/Exceptions/ApiSendFailedToPatchException.cs deleted file mode 100644 index cd928b98..00000000 --- a/src/EasMe/Exceptions/ApiSendFailedToPatchException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class ApiSendFailedToPatchException : Exception { - public ApiSendFailedToPatchException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public ApiSendFailedToPatchException(string message) : base(message) { - } - - public ApiSendFailedToPatchException(Exception? Inner = null) : base("ApiSendFailedToPatchException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/ApiSendFailedToPostException.cs b/src/EasMe/Exceptions/ApiSendFailedToPostException.cs deleted file mode 100644 index 6d1e8126..00000000 --- a/src/EasMe/Exceptions/ApiSendFailedToPostException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class ApiSendFailedToPostException : Exception { - public ApiSendFailedToPostException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public ApiSendFailedToPostException(string message) : base(message) { - } - - public ApiSendFailedToPostException(Exception? Inner = null) : base("ApiSendFailedToPostException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/ApiSendFailedToPutException.cs b/src/EasMe/Exceptions/ApiSendFailedToPutException.cs deleted file mode 100644 index f076a7ab..00000000 --- a/src/EasMe/Exceptions/ApiSendFailedToPutException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class ApiSendFailedToPutException : Exception { - public ApiSendFailedToPutException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public ApiSendFailedToPutException(string message) : base(message) { - } - - public ApiSendFailedToPutException(Exception? Inner = null) : base("ApiSendFailedToPutException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/ApiSendFailedToSendException.cs b/src/EasMe/Exceptions/ApiSendFailedToSendException.cs deleted file mode 100644 index 42f403ef..00000000 --- a/src/EasMe/Exceptions/ApiSendFailedToSendException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class ApiSendFailedToSendException : Exception { - public ApiSendFailedToSendException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public ApiSendFailedToSendException(string message) : base(message) { - } - - public ApiSendFailedToSendException(Exception? Inner = null) : base("ApiSendFailedToSendException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/CannotConnectException.cs b/src/EasMe/Exceptions/CannotConnectException.cs deleted file mode 100644 index 66637db5..00000000 --- a/src/EasMe/Exceptions/CannotConnectException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class CannotConnectException : Exception { - public CannotConnectException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public CannotConnectException(string message) : base(message) { - } - - public CannotConnectException(Exception? Inner = null) : base("CannotConnectException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/EmailAlreadySentException.cs b/src/EasMe/Exceptions/EmailAlreadySentException.cs deleted file mode 100644 index 999910ce..00000000 --- a/src/EasMe/Exceptions/EmailAlreadySentException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class EmailAlreadySentException : Exception { - public EmailAlreadySentException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public EmailAlreadySentException(string message) : base(message) { - } - - public EmailAlreadySentException(Exception? Inner = null) : base("EmailAlreadySentException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/EmailIncorrectException.cs b/src/EasMe/Exceptions/EmailIncorrectException.cs deleted file mode 100644 index c80c9d38..00000000 --- a/src/EasMe/Exceptions/EmailIncorrectException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class EmailIncorrectException : Exception { - public EmailIncorrectException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public EmailIncorrectException(string message) : base(message) { - } - - public EmailIncorrectException(Exception? Inner = null) : base("EmailIncorrectException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/EmailSendFailedException.cs b/src/EasMe/Exceptions/EmailSendFailedException.cs deleted file mode 100644 index aa1e5d6e..00000000 --- a/src/EasMe/Exceptions/EmailSendFailedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class EmailSendFailedException : Exception { - public EmailSendFailedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public EmailSendFailedException(string message) : base(message) { - } - - public EmailSendFailedException(Exception? Inner = null) : base("EmailSendFailedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/EmptyFileException.cs b/src/EasMe/Exceptions/EmptyFileException.cs deleted file mode 100644 index de493bb6..00000000 --- a/src/EasMe/Exceptions/EmptyFileException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class EmptyFileException : Exception { - public EmptyFileException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public EmptyFileException(string message) : base(message) { - } - - public EmptyFileException(Exception? Inner = null) : base("EmptyFileException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/ExpiredException.cs b/src/EasMe/Exceptions/ExpiredException.cs deleted file mode 100644 index a54ba618..00000000 --- a/src/EasMe/Exceptions/ExpiredException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class ExpiredException : Exception { - public ExpiredException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public ExpiredException(string message) : base(message) { - } - - public ExpiredException(Exception? Inner = null) : base("ExpiredException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToAddException.cs b/src/EasMe/Exceptions/FailedToAddException.cs deleted file mode 100644 index cec2a56a..00000000 --- a/src/EasMe/Exceptions/FailedToAddException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToAddException : Exception { - public FailedToAddException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToAddException(string message) : base(message) { - } - - public FailedToAddException(Exception? Inner = null) : base("FailedToAddException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToApplyException.cs b/src/EasMe/Exceptions/FailedToApplyException.cs deleted file mode 100644 index cdeba67a..00000000 --- a/src/EasMe/Exceptions/FailedToApplyException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToApplyException : Exception { - public FailedToApplyException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToApplyException(string message) : base(message) { - } - - public FailedToApplyException(Exception? Inner = null) : base("FailedToApplyException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToAuthenticateException.cs b/src/EasMe/Exceptions/FailedToAuthenticateException.cs deleted file mode 100644 index a5d8183d..00000000 --- a/src/EasMe/Exceptions/FailedToAuthenticateException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToAuthenticateException : Exception { - public FailedToAuthenticateException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToAuthenticateException(string message) : base(message) { - } - - public FailedToAuthenticateException(Exception? Inner = null) : base("FailedToAuthenticateException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToCheck.cs b/src/EasMe/Exceptions/FailedToCheck.cs deleted file mode 100644 index d676fc06..00000000 --- a/src/EasMe/Exceptions/FailedToCheck.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToCheck : Exception { - public FailedToCheck(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToCheck(string message) : base(message) { - } - - public FailedToCheck(Exception? Inner = null) : base("FailedToCheck", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToConvertException.cs b/src/EasMe/Exceptions/FailedToConvertException.cs deleted file mode 100644 index 3da4cd38..00000000 --- a/src/EasMe/Exceptions/FailedToConvertException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToConvertException : Exception { - public FailedToConvertException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToConvertException(string message) : base(message) { - } - - public FailedToConvertException(Exception? Inner = null) : base("FailedToConvertException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToCopyException.cs b/src/EasMe/Exceptions/FailedToCopyException.cs deleted file mode 100644 index c0ad4171..00000000 --- a/src/EasMe/Exceptions/FailedToCopyException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToCopyException : Exception { - public FailedToCopyException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToCopyException(string message) : base(message) { - } - - public FailedToCopyException(Exception? Inner = null) : base("FailedToCopyException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToCreateException.cs b/src/EasMe/Exceptions/FailedToCreateException.cs deleted file mode 100644 index 097fdbad..00000000 --- a/src/EasMe/Exceptions/FailedToCreateException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToCreateException : Exception { - public FailedToCreateException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToCreateException(string message) : base(message) { - } - - public FailedToCreateException(Exception? Inner = null) : base("FailedToCreateException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToDeleteException.cs b/src/EasMe/Exceptions/FailedToDeleteException.cs deleted file mode 100644 index 7dddf508..00000000 --- a/src/EasMe/Exceptions/FailedToDeleteException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToDeleteException : Exception { - public FailedToDeleteException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToDeleteException(string message) : base(message) { - } - - public FailedToDeleteException(Exception? Inner = null) : base("FailedToDeleteException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToDeserializeException.cs b/src/EasMe/Exceptions/FailedToDeserializeException.cs deleted file mode 100644 index 70c79b9e..00000000 --- a/src/EasMe/Exceptions/FailedToDeserializeException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToDeserializeException : Exception { - public FailedToDeserializeException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToDeserializeException(string message) : base(message) { - } - - public FailedToDeserializeException(Exception? Inner = null) : base("FailedToDeserializeException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToGetException.cs b/src/EasMe/Exceptions/FailedToGetException.cs deleted file mode 100644 index 84213db9..00000000 --- a/src/EasMe/Exceptions/FailedToGetException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToGetException : Exception { - public FailedToGetException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToGetException(string message) : base(message) { - } - - public FailedToGetException(Exception? Inner = null) : base("FailedToGetException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToInitializeException.cs b/src/EasMe/Exceptions/FailedToInitializeException.cs deleted file mode 100644 index 69b90207..00000000 --- a/src/EasMe/Exceptions/FailedToInitializeException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToInitializeException : Exception { - public FailedToInitializeException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToInitializeException(string message) : base(message) { - } - - public FailedToInitializeException(Exception? Inner = null) : base("FailedToInitializeException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToLoadException.cs b/src/EasMe/Exceptions/FailedToLoadException.cs deleted file mode 100644 index e162a484..00000000 --- a/src/EasMe/Exceptions/FailedToLoadException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToLoadException : Exception { - public FailedToLoadException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToLoadException(string message) : base(message) { - } - - public FailedToLoadException(Exception? Inner = null) : base("FailedToLoadException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToLogException.cs b/src/EasMe/Exceptions/FailedToLogException.cs deleted file mode 100644 index 86078368..00000000 --- a/src/EasMe/Exceptions/FailedToLogException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToLogException : Exception { - public FailedToLogException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToLogException(string message) : base(message) { - } - - public FailedToLogException(Exception? Inner = null) : base("FailedToLogException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToMoveException.cs b/src/EasMe/Exceptions/FailedToMoveException.cs deleted file mode 100644 index a9a8d1dc..00000000 --- a/src/EasMe/Exceptions/FailedToMoveException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToMoveException : Exception { - public FailedToMoveException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToMoveException(string message) : base(message) { - } - - public FailedToMoveException(Exception? Inner = null) : base("FailedToMoveException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToParseException.cs b/src/EasMe/Exceptions/FailedToParseException.cs deleted file mode 100644 index 2c65fda3..00000000 --- a/src/EasMe/Exceptions/FailedToParseException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToParseException : Exception { - public FailedToParseException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToParseException(string message) : base(message) { - } - - public FailedToParseException(Exception? Inner = null) : base("FailedToParseException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToReadException.cs b/src/EasMe/Exceptions/FailedToReadException.cs deleted file mode 100644 index e84747e7..00000000 --- a/src/EasMe/Exceptions/FailedToReadException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToReadException : Exception { - public FailedToReadException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToReadException(string message) : base(message) { - } - - public FailedToReadException(Exception? Inner = null) : base("FailedToReadException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToReloadException.cs b/src/EasMe/Exceptions/FailedToReloadException.cs deleted file mode 100644 index 01b893d7..00000000 --- a/src/EasMe/Exceptions/FailedToReloadException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToReloadException : Exception { - public FailedToReloadException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToReloadException(string message) : base(message) { - } - - public FailedToReloadException(Exception? Inner = null) : base("FailedToReloadException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToRemoveException.cs b/src/EasMe/Exceptions/FailedToRemoveException.cs deleted file mode 100644 index b3a595fd..00000000 --- a/src/EasMe/Exceptions/FailedToRemoveException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToRemoveException : Exception { - public FailedToRemoveException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToRemoveException(string message) : base(message) { - } - - public FailedToRemoveException(Exception? Inner = null) : base("FailedToRemoveException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToSaveException.cs b/src/EasMe/Exceptions/FailedToSaveException.cs deleted file mode 100644 index ea4365f7..00000000 --- a/src/EasMe/Exceptions/FailedToSaveException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToSaveException : Exception { - public FailedToSaveException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToSaveException(string message) : base(message) { - } - - public FailedToSaveException(Exception? Inner = null) : base("FailedToSaveException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToSearchException.cs b/src/EasMe/Exceptions/FailedToSearchException.cs deleted file mode 100644 index 748da830..00000000 --- a/src/EasMe/Exceptions/FailedToSearchException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToSearchException : Exception { - public FailedToSearchException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToSearchException(string message) : base(message) { - } - - public FailedToSearchException(Exception? Inner = null) : base("FailedToSearchException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToSendException.cs b/src/EasMe/Exceptions/FailedToSendException.cs deleted file mode 100644 index ff57927c..00000000 --- a/src/EasMe/Exceptions/FailedToSendException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToSendException : Exception { - public FailedToSendException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToSendException(string message) : base(message) { - } - - public FailedToSendException(Exception? Inner = null) : base("FailedToSendException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToSerializeException.cs b/src/EasMe/Exceptions/FailedToSerializeException.cs deleted file mode 100644 index 8407fb3d..00000000 --- a/src/EasMe/Exceptions/FailedToSerializeException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToSerializeException : Exception { - public FailedToSerializeException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToSerializeException(string message) : base(message) { - } - - public FailedToSerializeException(Exception? Inner = null) : base("FailedToSerializeException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToUpdateException.cs b/src/EasMe/Exceptions/FailedToUpdateException.cs deleted file mode 100644 index 675a6afe..00000000 --- a/src/EasMe/Exceptions/FailedToUpdateException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToUpdateException : Exception { - public FailedToUpdateException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToUpdateException(string message) : base(message) { - } - - public FailedToUpdateException(Exception? Inner = null) : base("FailedToUpdateException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToValidateException.cs b/src/EasMe/Exceptions/FailedToValidateException.cs deleted file mode 100644 index 1288a0d1..00000000 --- a/src/EasMe/Exceptions/FailedToValidateException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToValidateException : Exception { - public FailedToValidateException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToValidateException(string message) : base(message) { - } - - public FailedToValidateException(Exception? Inner = null) : base("FailedToValidateException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/FailedToWriteException.cs b/src/EasMe/Exceptions/FailedToWriteException.cs deleted file mode 100644 index c0ce1af4..00000000 --- a/src/EasMe/Exceptions/FailedToWriteException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class FailedToWriteException : Exception { - public FailedToWriteException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public FailedToWriteException(string message) : base(message) { - } - - public FailedToWriteException(Exception? Inner = null) : base("FailedToWriteException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/InternalDbException.cs b/src/EasMe/Exceptions/InternalDbException.cs deleted file mode 100644 index 85e0a472..00000000 --- a/src/EasMe/Exceptions/InternalDbException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class InternalDbException : Exception { - public InternalDbException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public InternalDbException(string message) : base(message) { - } - - public InternalDbException(Exception? Inner = null) : base("InternalDbException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/InvalidTokenException.cs b/src/EasMe/Exceptions/InvalidTokenException.cs deleted file mode 100644 index f3702f03..00000000 --- a/src/EasMe/Exceptions/InvalidTokenException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class InvalidTokenException : Exception { - public InvalidTokenException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public InvalidTokenException(string message) : base(message) { - } - - public InvalidTokenException(Exception? Inner = null) : base("InvalidTokenException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/LoggingFailedException.cs b/src/EasMe/Exceptions/LoggingFailedException.cs deleted file mode 100644 index dacca132..00000000 --- a/src/EasMe/Exceptions/LoggingFailedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class LoggingFailedException : Exception { - public LoggingFailedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public LoggingFailedException(string message) : base(message) { - } - - public LoggingFailedException(Exception? Inner = null) : base("LoggingFailedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NoEntryFoundException.cs b/src/EasMe/Exceptions/NoEntryFoundException.cs deleted file mode 100644 index 60df9e41..00000000 --- a/src/EasMe/Exceptions/NoEntryFoundException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NoEntryFoundException : Exception { - public NoEntryFoundException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NoEntryFoundException(string message) : base(message) { - } - - public NoEntryFoundException(Exception? Inner = null) : base("NoEntryFoundException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NoOnlineNetworkException.cs b/src/EasMe/Exceptions/NoOnlineNetworkException.cs deleted file mode 100644 index 90272dd4..00000000 --- a/src/EasMe/Exceptions/NoOnlineNetworkException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NoOnlineNetworkException : Exception { - public NoOnlineNetworkException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NoOnlineNetworkException(string message) : base(message) { - } - - public NoOnlineNetworkException(Exception? Inner = null) : base("NoOnlineNetworkException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotAllowedException.cs b/src/EasMe/Exceptions/NotAllowedException.cs deleted file mode 100644 index c06616a7..00000000 --- a/src/EasMe/Exceptions/NotAllowedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotAllowedException : Exception { - public NotAllowedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotAllowedException(string message) : base(message) { - } - - public NotAllowedException(Exception? Inner = null) : base("NotAllowedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotAuthenticatedException.cs b/src/EasMe/Exceptions/NotAuthenticatedException.cs deleted file mode 100644 index 3b9613da..00000000 --- a/src/EasMe/Exceptions/NotAuthenticatedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotAuthenticatedException : Exception { - public NotAuthenticatedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotAuthenticatedException(string message) : base(message) { - } - - public NotAuthenticatedException(Exception? Inner = null) : base("NotAuthenticatedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotAuthorizedException.cs b/src/EasMe/Exceptions/NotAuthorizedException.cs deleted file mode 100644 index aa5131f9..00000000 --- a/src/EasMe/Exceptions/NotAuthorizedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotAuthorizedException : Exception { - public NotAuthorizedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotAuthorizedException(string message) : base(message) { - } - - public NotAuthorizedException(Exception? Inner = null) : base("NotAuthorizedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotAvaliableException.cs b/src/EasMe/Exceptions/NotAvaliableException.cs deleted file mode 100644 index 48bfbe5d..00000000 --- a/src/EasMe/Exceptions/NotAvaliableException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotAvaliableException : Exception { - public NotAvaliableException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotAvaliableException(string message) : base(message) { - } - - public NotAvaliableException(Exception? Inner = null) : base("NotAvaliableException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotConnectedException.cs b/src/EasMe/Exceptions/NotConnectedException.cs deleted file mode 100644 index 04c6edbe..00000000 --- a/src/EasMe/Exceptions/NotConnectedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotConnectedException : Exception { - public NotConnectedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotConnectedException(string message) : base(message) { - } - - public NotConnectedException(Exception? Inner = null) : base("NotConnectedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotEnabledException.cs b/src/EasMe/Exceptions/NotEnabledException.cs deleted file mode 100644 index dee0f272..00000000 --- a/src/EasMe/Exceptions/NotEnabledException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotEnabledException : Exception { - public NotEnabledException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotEnabledException(string message) : base(message) { - } - - public NotEnabledException(Exception? Inner = null) : base("NotEnabledException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotExistException.cs b/src/EasMe/Exceptions/NotExistException.cs deleted file mode 100644 index 871565a6..00000000 --- a/src/EasMe/Exceptions/NotExistException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotExistException : Exception { - public NotExistException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotExistException(string message) : base(message) { - } - - public NotExistException(Exception? Inner = null) : base("NotExistException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotFoundException.cs b/src/EasMe/Exceptions/NotFoundException.cs deleted file mode 100644 index c3a40c9d..00000000 --- a/src/EasMe/Exceptions/NotFoundException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotFoundException : Exception { - public NotFoundException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotFoundException(string message) : base(message) { - } - - public NotFoundException(Exception? Inner = null) : base("NotFoundException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotInitializedException.cs b/src/EasMe/Exceptions/NotInitializedException.cs deleted file mode 100644 index 6031133a..00000000 --- a/src/EasMe/Exceptions/NotInitializedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotInitializedException : Exception { - public NotInitializedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotInitializedException(string message) : base(message) { - } - - public NotInitializedException(Exception? Inner = null) : base("NotInitializedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotLoadedException.cs b/src/EasMe/Exceptions/NotLoadedException.cs deleted file mode 100644 index 8ba02691..00000000 --- a/src/EasMe/Exceptions/NotLoadedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotLoadedException : Exception { - public NotLoadedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotLoadedException(string message) : base(message) { - } - - public NotLoadedException(Exception? Inner = null) : base("NotLoadedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotReadyException.cs b/src/EasMe/Exceptions/NotReadyException.cs deleted file mode 100644 index 15d16a75..00000000 --- a/src/EasMe/Exceptions/NotReadyException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotReadyException : Exception { - public NotReadyException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotReadyException(string message) : base(message) { - } - - public NotReadyException(Exception? Inner = null) : base("NotReadyException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotSupportedException.cs b/src/EasMe/Exceptions/NotSupportedException.cs deleted file mode 100644 index 422f65ae..00000000 --- a/src/EasMe/Exceptions/NotSupportedException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotSupportedException : Exception { - public NotSupportedException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotSupportedException(string message) : base(message) { - } - - public NotSupportedException(Exception? Inner = null) : base("NotSupportedException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/NotValidException.cs b/src/EasMe/Exceptions/NotValidException.cs deleted file mode 100644 index 1b28c92a..00000000 --- a/src/EasMe/Exceptions/NotValidException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class NotValidException : Exception { - public NotValidException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public NotValidException(string message) : base(message) { - } - - public NotValidException(Exception? Inner = null) : base("NotValidException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/PasswordIncorrectException.cs b/src/EasMe/Exceptions/PasswordIncorrectException.cs deleted file mode 100644 index 73c9c035..00000000 --- a/src/EasMe/Exceptions/PasswordIncorrectException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class PasswordIncorrectException : Exception { - public PasswordIncorrectException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public PasswordIncorrectException(string message) : base(message) { - } - - public PasswordIncorrectException(Exception? Inner = null) : base("PasswordIncorrectException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/SqlErrorException.cs b/src/EasMe/Exceptions/SqlErrorException.cs deleted file mode 100644 index 307b85e0..00000000 --- a/src/EasMe/Exceptions/SqlErrorException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class SqlErrorException : Exception { - public SqlErrorException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public SqlErrorException(string message) : base(message) { - } - - public SqlErrorException(Exception? Inner = null) : base("SqlErrorException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/TooBigValueException.cs b/src/EasMe/Exceptions/TooBigValueException.cs deleted file mode 100644 index ed3da7af..00000000 --- a/src/EasMe/Exceptions/TooBigValueException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class TooBigValueException : Exception { - public TooBigValueException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public TooBigValueException(string message) : base(message) { - } - - public TooBigValueException(Exception? Inner = null) : base("TooBigValueException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/TooSmallValueException.cs b/src/EasMe/Exceptions/TooSmallValueException.cs deleted file mode 100644 index 0609e618..00000000 --- a/src/EasMe/Exceptions/TooSmallValueException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class TooSmallValueException : Exception { - public TooSmallValueException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public TooSmallValueException(string message) : base(message) { - } - - public TooSmallValueException(Exception? Inner = null) : base("TooSmallValueException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Exceptions/UsernameIncorrectException.cs b/src/EasMe/Exceptions/UsernameIncorrectException.cs deleted file mode 100644 index 7fa3bf42..00000000 --- a/src/EasMe/Exceptions/UsernameIncorrectException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace EasMe.Exceptions; - -public class UsernameIncorrectException : Exception { - public UsernameIncorrectException(string message, Exception? Inner = null) : base(message, Inner) { - } - - public UsernameIncorrectException(string message) : base(message) { - } - - public UsernameIncorrectException(Exception? Inner = null) : base("UsernameIncorrectException", Inner) { - } -} \ No newline at end of file diff --git a/src/EasMe/Extensions/BoolExtensions.cs b/src/EasMe/Extensions/BoolExtensions.cs index 1d145113..0317ae42 100644 --- a/src/EasMe/Extensions/BoolExtensions.cs +++ b/src/EasMe/Extensions/BoolExtensions.cs @@ -1,6 +1,7 @@ namespace EasMe.Extensions; -public static class BoolExtensions { +public static class BoolExtensions +{ public static bool ToBoolean(bool? value) { if (value == null) return false; return (bool)value; diff --git a/src/EasMe/Extensions/ByteExtensions.cs b/src/EasMe/Extensions/ByteExtensions.cs index c376aceb..0789406b 100644 --- a/src/EasMe/Extensions/ByteExtensions.cs +++ b/src/EasMe/Extensions/ByteExtensions.cs @@ -1,53 +1,13 @@ -using System.Text; - -namespace EasMe.Extensions; - -public static class ByteExtensions { - /// - /// Converts hashed byte array to string - /// - /// - /// - public static string BuildString(this byte[] bytes) { - bytes.ToString(); - StringBuilder builder = new(); - for (var i = 0; i < bytes.Length; i++) builder.Append(bytes[i].ToString("x2")); - return builder.ToString(); - } +namespace EasMe.Extensions; +public static class ByteExtensions +{ public static string ToBase64String(this byte[] bytes) { return Convert.ToBase64String(bytes); } - public static string ConvertToString(this byte[] byteArray) { - return Encoding.ASCII.GetString(byteArray); - } - - public static string BytesToHexString(this byte[] bt) { - try { - var s = string.Empty; - for (var i = 0; i < bt.Length; i++) { - var b = bt[i]; - int n, n1, n2; - n = b; - n1 = n & 15; - n2 = (n >> 4) & 15; - if (n2 > 9) - s += ((char)(n2 - 10 + 'A')).ToString(); - else - s += n2.ToString(); - if (n1 > 9) - s += ((char)(n1 - 10 + 'A')).ToString(); - else - s += n1.ToString(); - if (i + 1 != bt.Length && (i + 1) % 2 == 0) s += "-"; - } - - return s; - } - catch { - return ""; - } + public static string BytesToHexString(this byte[] bytes) { + return Convert.ToHexString(bytes); } /// diff --git a/src/EasMe/Extensions/ClaimsExtensions.cs b/src/EasMe/Extensions/ClaimsExtensions.cs index 30c8ba11..55ba5d0a 100644 --- a/src/EasMe/Extensions/ClaimsExtensions.cs +++ b/src/EasMe/Extensions/ClaimsExtensions.cs @@ -1,9 +1,10 @@ using System.Security.Claims; -using EasMe.Exceptions; +using log4net.Util.TypeConverters; namespace EasMe.Extensions; -public static class ClaimsExtensions { +public static class ClaimsExtensions +{ /// /// Converts given model to claims identity. /// @@ -12,16 +13,9 @@ public static class ClaimsExtensions { /// /// public static Dictionary AsDictionary(this IEnumerable claims) { - var dic = new Dictionary(); - //var type = claims.GetType(); - //var props = type.GetProperties(); - foreach (var item in claims) { - var name = item.Type; - var value = item.Value; - dic[name] = value; - } - - return dic; + var dictionary = new Dictionary(); + foreach (var claim in claims) dictionary.TryAdd(claim.Type, claim.Value); + return dictionary; } @@ -29,19 +23,18 @@ public static Dictionary AsDictionary(this IEnumerable cl /// Converts given model to claims identity. /// /// - /// + /// /// - /// - public static ClaimsIdentity ToClaimsIdentity(this T Model) { + /// + public static ClaimsIdentity ToClaimsIdentity(this T model) { var claimsIdentity = new ClaimsIdentity(); - var props = Model?.GetType().GetProperties(); - if (props == null) - throw new FailedToConvertException("Failed to convert model to claims identity. Model has no properties"); + var props = model?.GetType().GetProperties(); + if (props is null || props.Length == 0) + throw new ConversionNotSupportedException("Failed to convert model to claims identity. Model has no properties"); foreach (var property in props) { - if (property == null) continue; - var value = property.GetValue(Model); - if (value == null) continue; - claimsIdentity.AddClaim(new Claim(property.Name, value.ToString())); + var value = property.GetValue(model); + if (value is null) continue; + claimsIdentity.AddClaim(new Claim(property.Name, value.ToString() ?? string.Empty)); } return claimsIdentity; @@ -52,22 +45,23 @@ public static ClaimsIdentity ToClaimsIdentity(this T Model) { /// properties. This adds one claim that /// /// - /// - /// + /// + /// /// - /// - public static ClaimsIdentity ToClaimsIdentity(this T Model, out List ExceptionMessages) { - ExceptionMessages = new List(); + public static ClaimsIdentity ToClaimsIdentity(this T model, out List exceptionMessages) { + exceptionMessages = new List(); var claimsIdentity = new ClaimsIdentity(); - foreach (var property in Model.GetType().GetProperties()) + var props = model?.GetType().GetProperties(); + if (props is null || props.Length == 0) + throw new ConversionNotSupportedException("Failed to convert model to claims identity. Model has no properties"); + foreach (var property in props) try { - if (property == null) continue; - var value = property.GetValue(Model); + var value = property.GetValue(model); if (value == null) continue; claimsIdentity.AddClaim(new Claim(property.Name, value.ToString())); } catch (Exception ex) { - ExceptionMessages.Add(ex); + exceptionMessages.Add(ex); } return claimsIdentity; diff --git a/src/EasMe/Extensions/DateTimeExtensions.cs b/src/EasMe/Extensions/DateTimeExtensions.cs index 521c65a7..e19caaeb 100644 --- a/src/EasMe/Extensions/DateTimeExtensions.cs +++ b/src/EasMe/Extensions/DateTimeExtensions.cs @@ -1,11 +1,12 @@ namespace EasMe.Extensions; -public static class DateTimeExtensions { +public static class DateTimeExtensions +{ public static bool IsBetween(this DateTime date, DateTime start, DateTime end) { return date >= start && date <= end; } - public static bool IsInPass(this DateTime date) { + public static bool IsPassed(this DateTime date) { return date <= DateTime.Now; } @@ -13,91 +14,32 @@ public static bool IsInFuture(this DateTime date) { return date >= DateTime.Now; } - public static bool IsValidDate(this string date) { + public static bool IsValidDateTime(this string date) { return DateTime.TryParse(date, out var _); } + /// + /// Converts a nullable datetime to datetime. If null, returns DateTime.UnixEpoch + /// + /// + /// public static DateTime ToDateTime(this DateTime? datetime) { if (datetime is null) return DateTime.UnixEpoch; return (DateTime)datetime; } - public static string ToReadableDateString(this DateTime datetime) { - if (datetime < DateTime.Now) { - var timeSpan = DateTime.Now - datetime; - var seconds = timeSpan.TotalSeconds; - var minutes = timeSpan.TotalMinutes; - var hours = timeSpan.TotalHours; - var days = timeSpan.TotalDays; - var months = days / 30; - var years = days / 365; - - - if (seconds < 60) return $"{(int)seconds} seconds ago"; - - if (minutes < 60) return $"{(int)minutes} minutes ago"; - - if (hours < 24) { - var leftMins = (int)minutes % 60; - if (leftMins > 0) - return $"{(int)hours} hours and {leftMins} minutes ago"; - - return $"{(int)hours} hours ago"; - } - - if (days < 30) { - var leftHours = (int)hours % 24; - if (leftHours > 0) - return $"{(int)days} days and {leftHours} hours ago"; - return $"{(int)days} days "; - } - - if (months < 12) - return $"{(int)months} months ago"; - return $"{(int)years} years ago"; - } - else { - var timeSpan = datetime - DateTime.Now; - var seconds = timeSpan.TotalSeconds; - var minutes = timeSpan.TotalMinutes; - var hours = timeSpan.TotalHours; - var days = timeSpan.TotalDays; - var months = days / 30; - var years = days / 365; - if (seconds < 60) return $"in {(int)seconds} seconds"; - - if (minutes < 60) return $"in {(int)minutes} minutes"; - - if (hours < 24) { - var leftMins = (int)minutes % 60; - if (leftMins > 0) - return $"in {(int)hours} hours and {leftMins} minutes"; - - return $"in {(int)hours} hours"; - } - - if (days < 30) { - var leftHours = (int)hours % 24; - if (leftHours > 0) - return $"in {(int)days} days and {leftHours} hours"; - return $"in {(int)days} days"; - } - - if (months < 12) - return $"in {(int)months} months"; - return $"in {(int)years} years"; - } - } - public static DateTime UnixTimeStampToDateTime(this long unixTimeStamp) { DateTime dateTime = new(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddSeconds(unixTimeStamp).ToLocalTime(); return dateTime; } + public static DateTime TicksToDateTime(long ticks) { + return new DateTime(ticks); + } + public static long ToUnixTime(this DateTime date) { return ((DateTimeOffset)date).ToUnixTimeSeconds(); - //return (long)(date - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; } public static bool IsDayOlder(this DateTime date, int day) { @@ -123,4 +65,62 @@ public static bool IsMonthOlder(this DateTime date, int months) { public static bool IsYearOlder(this DateTime date, int years) { return date.AddYears(years) < DateTime.Now; } + + public static string ToReadableDateString(this DateTime dateTime) { + var isPassed = dateTime.IsPassed(); + var timeSpan = isPassed ? DateTime.Now - dateTime : dateTime - DateTime.Now; + var text = isPassed ? "ago" : "from now"; + if (timeSpan.TotalSeconds < 60) { + var seconds = (int)timeSpan.TotalSeconds; + return FormatTimeSpan(seconds, "second", text); + } + + if (timeSpan.TotalMinutes < 60) { + var minutes = (int)timeSpan.TotalMinutes; + return FormatTimeSpan(minutes, "minute", text); + } + + if (timeSpan.TotalHours < 24) { + var hours = (int)timeSpan.TotalHours; + var leftMinutes = (int)timeSpan.TotalMinutes % 60; + return FormatTimeSpan(hours, "hour", leftMinutes, "minute", text); + } + + if (timeSpan.TotalDays < 30) { + var days = (int)timeSpan.TotalDays; + var leftHours = (int)timeSpan.TotalHours % 24; + return FormatTimeSpan(days, "day", leftHours, "hour", text); + } + + if (timeSpan.TotalDays < 365) { + var months = (int)(timeSpan.TotalDays / 30); + var leftDays = (int)timeSpan.TotalDays % 30; + return FormatTimeSpan(months, "month", leftDays, "day", text); + } + + var years = (int)(timeSpan.TotalDays / 365); + var leftMonths = (int)(timeSpan.TotalDays / 30) % 12; + return FormatTimeSpan(years, "year", leftMonths, "month", text); + } + + private static string FormatTimeSpan(int value1, string unit1, int value2, string unit2, string text) { + var result = $"{value1} {unit1}"; + if (value1 != 1) + result += "s"; + if (value2 > 0) { + result += $" and {value2} {unit2}"; + if (value2 != 1) + result += "s"; + } + + return $"{result} {text}"; + } + + private static string FormatTimeSpan(int value, string unit, string text) { + var result = $"{value} {unit}"; + if (value != 1) + result += "s"; + + return $"{result} {text}"; + } } \ No newline at end of file diff --git a/src/EasMe/Extensions/DictionaryExtensions.cs b/src/EasMe/Extensions/DictionaryExtensions.cs index 0a10b10e..1eb55bb4 100644 --- a/src/EasMe/Extensions/DictionaryExtensions.cs +++ b/src/EasMe/Extensions/DictionaryExtensions.cs @@ -1,39 +1,17 @@ namespace EasMe.Extensions; -public static class DictionaryExtensions { - // public static T ToObject(this IDictionary source) where T : class, new() - // { - // var obj = new T(); - // var type = obj.GetType(); - // foreach (var item in source) - // { - // var prop = type.GetProperty(item.Key); - //var str = item.Value?.ToString(); - //if (prop is not null && !str.IsNullOrEmpty() && prop.CanWrite) - // { - // var ptype = prop.PropertyType; - // //var converter = TypeDescriptor.GetConverter(ptype); - // var converted = Convert.ChangeType(str, ptype); - // //var convertedObject = converter.ConvertFromString(str); - // prop.SetValue(obj, converted); - // } - // } - - // return obj; - // } - public static T ToObject(this IDictionary source) where T : class, new() { - var obj = new T(); - var type = obj.GetType(); - foreach (var item in source) { - var prop = type.GetProperty(item.Key); - var str = item.Value?.ToString(); - if (prop is not null && !str.IsNullOrEmpty() && prop.CanWrite) { - var ptype = prop.PropertyType; - var convert = str.ChangeType(ptype); - prop.SetValue(obj, convert); - } +public static class DictionaryExtensions +{ + public static T ToObject(this IDictionary source) { + var targetType = typeof(T); + var properties = targetType.GetProperties(); + var instance = Activator.CreateInstance(); + foreach (var property in properties) { + if (!source.TryGetValue(property.Name, out var value)) continue; + if (!property.PropertyType.IsInstanceOfType(value)) continue; + property.SetValue(instance, value); } - return obj; + return instance; } } \ No newline at end of file diff --git a/src/EasMe/Extensions/EntityFrameworkExtensions.cs b/src/EasMe/Extensions/EntityFrameworkExtensions.cs deleted file mode 100644 index 39ceaa8f..00000000 --- a/src/EasMe/Extensions/EntityFrameworkExtensions.cs +++ /dev/null @@ -1,34 +0,0 @@ -using EasMe.Exceptions; -using Microsoft.EntityFrameworkCore; - -namespace EasMe.Extensions; - -public static class EntityFrameworkExtensions { - /// - /// Truncates DbSet or Table, this action can not be undone. - /// - /// - /// - public static void Clear(this DbSet dbSet) where T : class { - dbSet.RemoveRange(dbSet); - } - - - public static void ClearAndSaveChanges(this DbSet dbSet, DbContext _dbContext) where T : class { - dbSet.RemoveRange(dbSet); - _dbContext.SaveChanges(); - } - - /// - /// Saves changes to db _dbContext, if no rows affected throws exception - /// - /// - /// - public static int SaveChangesOrThrow(this DbContext dbContext, - string message = "No changes were applied to the database.") { - var affected = dbContext.SaveChanges(); - if (affected == 0) - throw new InternalDbException(message); - return affected; - } -} \ No newline at end of file diff --git a/src/EasMe/Extensions/HttpContextExtensions.cs b/src/EasMe/Extensions/HttpContextExtensions.cs index 176d4c9e..b002f208 100644 --- a/src/EasMe/Extensions/HttpContextExtensions.cs +++ b/src/EasMe/Extensions/HttpContextExtensions.cs @@ -2,39 +2,40 @@ namespace EasMe.Extensions; -public static class HttpContextExtensions { +public static class HttpContextExtensions +{ public static string[] _HeaderList = new string[21] { - "HOST", - "ORIGIN", - "X-FORWARDED-FOR", - "ACCEPT", - "ACCESSTOKEN", - "CONTENT-LENGTH", - "CONTENT-TYPE", - //"COOKIE", - "REFERER", - "SEC-CH-UA", - "SEC-CH-UA-MOBILE", - "SEC-FETCH-SITE", - "SERVERREGION", - "USER-AGENT", - "X-ORIGINAL-HOST", - "X-ORIGINAL-URL", - "X-ORIGINAL-IP", - "X-FORWARDED-PORT", - "X-FORWARDED-PROTO", - "PC-Real-IP", - "CF-Connecting-IP", - "X-Real-IP" - }; + "HOST", + "ORIGIN", + "X-FORWARDED-FOR", + "ACCEPT", + "ACCESSTOKEN", + "CONTENT-LENGTH", + "CONTENT-TYPE", + //"COOKIE", + "REFERER", + "SEC-CH-UA", + "SEC-CH-UA-MOBILE", + "SEC-FETCH-SITE", + "SERVERREGION", + "USER-AGENT", + "X-ORIGINAL-HOST", + "X-ORIGINAL-URL", + "X-ORIGINAL-IP", + "X-FORWARDED-PORT", + "X-FORWARDED-PROTO", + "PC-Real-IP", + "CF-Connecting-IP", + "X-Real-IP" + }; public static readonly string[] _realIpHeaderList = new string[5] { - "X-FORWARDED-FOR", - "X-Real-IP", - "X-ORIGINAL-IP", - "PC-Real-IP", - "CF-Connecting-IP" - }; + "X-FORWARDED-FOR", + "X-Real-IP", + "X-ORIGINAL-IP", + "PC-Real-IP", + "CF-Connecting-IP" + }; /// @@ -63,9 +64,10 @@ public static string[] GetIpAddressList(this HttpRequest req) { foreach (var item in _realIpHeaderList) try { var ip = req.Headers[item].ToString(); - if (ip != null && ip != "") ipList.Add(ip); + if (ip != "") ipList.Add(ip); } catch { + // ignored } ipList.Add(req.HttpContext.Connection.RemoteIpAddress.ToString()); @@ -97,7 +99,7 @@ public static string GetRemoteIpAddress(this HttpRequest httpRequest) { try { foreach (var item in httpRequest.Headers) if (_realIpHeaderList.Any(x => x == item.Key)) - if (item.Value.ToString() != null || item.Value != "") + if (!string.IsNullOrEmpty(item.Value)) return item.Value.ToString() ?? ""; return httpRequest.HttpContext.Connection.RemoteIpAddress.ToString(); } diff --git a/src/EasMe/Extensions/JsonExtensions.cs b/src/EasMe/Extensions/JsonExtensions.cs index 71be5415..9888f51c 100644 --- a/src/EasMe/Extensions/JsonExtensions.cs +++ b/src/EasMe/Extensions/JsonExtensions.cs @@ -3,26 +3,26 @@ namespace EasMe.Extensions; -public static class JsonExtensions { +public static class JsonExtensions +{ /// /// Serializes given object to json string. /// /// /// - /// //[Obsolete("Use AsJson instead")] //public static string JsonSerialize(this object? obj, Newtonsoft.Json.Formatting formatting = Newtonsoft.Json.Formatting.None) //{ // return obj.ToJsonString(formatting); //} public static string ToJsonString(this object? obj, Formatting formatting = Formatting.None, - ReferenceLoopHandling referenceLoopHandling = ReferenceLoopHandling.Ignore) { + ReferenceLoopHandling referenceLoopHandling = ReferenceLoopHandling.Ignore) { if (obj == null) return default; var settings = new JsonSerializerSettings { - ContractResolver = new Resolver(), - Formatting = formatting, - ReferenceLoopHandling = referenceLoopHandling - }; + ContractResolver = new Resolver(), + Formatting = formatting, + ReferenceLoopHandling = referenceLoopHandling + }; var json = JsonConvert.SerializeObject(obj, settings); return json.RemoveLineEndings(); } @@ -30,15 +30,15 @@ public static string ToJsonString(this object? obj, Formatting formatting = Form /// /// Deserializes given json string to T model. Uses UnsafeRelaxedJsonEscaping JavaScriptEncoder. /// - /// + /// /// - /// public static T? FromJsonString(this string str) { return JsonConvert.DeserializeObject(str); } - private class Resolver : DefaultContractResolver { + private class Resolver : DefaultContractResolver + { protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) { if (!typeof(Exception).IsAssignableFrom(type)) return base.CreateProperties(type, memberSerialization); var props = base.CreateProperties(type, memberSerialization); diff --git a/src/EasMe/Extensions/ListExtensions.cs b/src/EasMe/Extensions/ListExtensions.cs index a0677a0c..e2fa3bf6 100644 --- a/src/EasMe/Extensions/ListExtensions.cs +++ b/src/EasMe/Extensions/ListExtensions.cs @@ -1,10 +1,10 @@ using System.ComponentModel; using System.Data; -using EasMe.Exceptions; namespace EasMe.Extensions; -public static class ListExtensions { +public static class ListExtensions +{ public static void ForEach(this IEnumerable list, Action action) { foreach (var item in list) action(item); @@ -76,60 +76,60 @@ public static List Shuffle(this List list) { public static T SingleOrThrow(this IEnumerable list, string message = "Item not found") { var item = list.SingleOrDefault(); if (item is null) - throw new NoEntryFoundException(message); + throw new ArgumentNullException(message); return item; } public static T SingleOrThrow(this IEnumerable list, Func predicate, - string message = "Item not found") { + string message = "Item not found") { var item = list.SingleOrDefault(predicate); if (item is null) - throw new NoEntryFoundException(message); + throw new ArgumentNullException(message); return item; } public static T SingleOrThrow(this IQueryable list, string message = "Item not found") { var item = list.SingleOrDefault(); if (item is null) - throw new NoEntryFoundException(message); + throw new ArgumentNullException(message); return item; } public static T SingleOrThrow(this IQueryable list, Func predicate, - string message = "Item not found") { + string message = "Item not found") { var item = list.SingleOrDefault(predicate); if (item is null) - throw new NoEntryFoundException(message); + throw new ArgumentNullException(message); return item; } public static T FirstOrThrow(this IEnumerable list, string message = "Item not found") { var item = list.FirstOrDefault(); if (item is null) - throw new NoEntryFoundException(message); + throw new ArgumentNullException(message); return item; } public static T FirstOrThrow(this IEnumerable list, Func predicate, - string message = "Item not found") { + string message = "Item not found") { var item = list.FirstOrDefault(predicate); if (item is null) - throw new NoEntryFoundException(message); + throw new ArgumentNullException(message); return item; } public static T FirstOrThrow(this IQueryable list, string message = "Item not found") { var item = list.FirstOrDefault(); if (item is null) - throw new NoEntryFoundException(message); + throw new ArgumentNullException(message); return item; } public static T FirstOrThrow(this IQueryable list, Func predicate, - string message = "Item not found") { + string message = "Item not found") { var item = list.FirstOrDefault(predicate); if (item is null) - throw new NoEntryFoundException(message); + throw new ArgumentNullException(message); return item; } diff --git a/src/EasMe/Extensions/NumberExtensions.cs b/src/EasMe/Extensions/NumberExtensions.cs index 814bd656..97735d8e 100644 --- a/src/EasMe/Extensions/NumberExtensions.cs +++ b/src/EasMe/Extensions/NumberExtensions.cs @@ -1,6 +1,7 @@ namespace EasMe.Extensions; -public static class NumberExtensions { +public static class NumberExtensions +{ public static bool IsBetween(this int value, int belowCheck, int aboveCheck) { return value > belowCheck && value < aboveCheck; } @@ -49,12 +50,12 @@ public static bool IsInRange(this float value, float checkValue, float belowAndA return value > checkValue - belowAndAboveCheck && value < checkValue + belowAndAboveCheck; } - public static int ToNotNullInt(this int? value) { + public static int ToInt(this int? value) { if (value is null) return default; return value.Value; } - public static long ToNotNullLong(this long? value) { + public static long ToLong(this long? value) { if (value is null) return default; return value.Value; } diff --git a/src/EasMe/Extensions/ObjectExtensions.cs b/src/EasMe/Extensions/ObjectExtensions.cs index bcd20b8a..ba3dd15f 100644 --- a/src/EasMe/Extensions/ObjectExtensions.cs +++ b/src/EasMe/Extensions/ObjectExtensions.cs @@ -3,17 +3,17 @@ namespace EasMe.Extensions; -public static class ObjectExtensions { +public static class ObjectExtensions +{ public static TDestination SelectAs(this TSource source, Func action) { return action(source); } public static bool ValidateModel(this T model) { - var _dbContext = new ValidationContext(model); - var results = new List(); - var isValid = Validator.TryValidateObject(model, _dbContext, results, true); - return isValid; + var validationResults = new List(); + var validationContext = new ValidationContext(model, null, null); + return Validator.TryValidateObject(model, validationContext, validationResults, true); } public static bool IsNull(this object? target) { @@ -29,12 +29,12 @@ public static bool IsNotNull(this object? target) { } public static Dictionary AsDictionary(this object source, - BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) { + BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) { return source.GetType().GetProperties(bindingAttr).ToDictionary - ( - propInfo => propInfo.Name, - propInfo => propInfo.GetValue(source, null) - ); + ( + propInfo => propInfo.Name, + propInfo => propInfo.GetValue(source, null) + ); } public static object? ChangeType(this object value, Type t) { @@ -47,24 +47,4 @@ public static bool IsNotNull(this object? target) { var isJson = false; return Convert.ChangeType(value, t); } - - /// - /// Converts object to string with its properties. Name:Value - /// - /// - /// - /// - public static string ToLineString(this T obj) { - if (obj is null) - return "null"; - var t = obj.GetType(); - var text = ""; - foreach (var prop in t.GetProperties()) { - var value = prop.GetValue(obj, null); - var name = prop.Name; - text += $"{name}:{value?.ToString() ?? "null"} "; - } - - return text.TrimEnd(); - } } \ No newline at end of file diff --git a/src/EasMe/Extensions/StringExtensions.cs b/src/EasMe/Extensions/StringExtensions.cs index d6b34937..361ec696 100644 --- a/src/EasMe/Extensions/StringExtensions.cs +++ b/src/EasMe/Extensions/StringExtensions.cs @@ -5,19 +5,20 @@ using System.Text; using System.Xml; using System.Xml.Linq; -using EasMe.Exceptions; +using log4net.Util.TypeConverters; using Newtonsoft.Json.Linq; namespace EasMe.Extensions; -public static class StringExtensions { +public static class StringExtensions +{ private static readonly HashSet _booleanValues = new(StringComparer.OrdinalIgnoreCase) { - "true", - "1", - "on", - "yes", - "y" - }; + "true", + "1", + "on", + "yes", + "y" + }; public static string RemoveText(this string value, string removeText) { @@ -44,8 +45,8 @@ public static string GetBetween(this string value, string startString, string en return string.Empty; var num = value.IndexOf(endString, startIndex + startString.Length, StringComparison.Ordinal); return num == -1 - ? string.Empty - : value.Substring(startIndex + startString.Length, num - startIndex - startString.Length); + ? string.Empty + : value.Substring(startIndex + startString.Length, num - startIndex - startString.Length); } public static byte[] ConvertToByteArray(this string yourStr) { @@ -143,11 +144,11 @@ public static byte[] ConvertToByteArray(this string yourStr) { return default; } catch (Exception ex) { - throw new FailedToConvertException("StringConversion failed type: " + typeof(T), ex); + throw new ConversionNotSupportedException("StringConversion failed type: " + typeof(T), ex); } } - public static string FormatString(this string str, params object[] args) { + public static string Format(this string str, params object[] args) { return string.Format(str, args); } @@ -172,7 +173,7 @@ public static bool IsNotNullOrWhiteSpace(this string? target) { /// /// /// - public static int? ToInt32(this string? value) { + public static int? ToInt(this string? value) { if (int.TryParse(value, out var i)) return i; return null; } @@ -192,7 +193,7 @@ public static bool IsNotNullOrWhiteSpace(this string? target) { /// /// /// - public static string TrimAbsolute(this string str) { + public static string RemoveWhiteSpace(this string str) { var res = str.Replace(" ", ""); return res; } @@ -299,22 +300,17 @@ public static string LastToLower(this string str) { /// /// /// - public static string TruncateString(this string value, int maxChars) { - return value.Length <= maxChars ? value : value[..maxChars] + "..."; + public static string TruncateLongString(this string str, int maxLength) { + return str[..Math.Min(str.Length, maxLength)] + (str.Length > maxLength ? "..." : null); } - public static string RemoveLineEndings(this string str) { return str.Replace("\n", "").Replace("\r", "").Replace("\t", ""); } public static string ToHexString(this string str) { - var sb = new StringBuilder(); - var bytes = Encoding.Unicode.GetBytes(str); - foreach (var t in bytes) sb.Append(t.ToString("X2")); - - return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world" + return Convert.ToHexString(bytes); } public static string FromHexString(this string hexString) { @@ -333,9 +329,6 @@ public static string FromBase64String(this string base64String) { return Encoding.UTF8.GetString(base64EncodedBytes); } - public static string TruncateLongString(this string str, int maxLength) { - return str[..Math.Min(str.Length, maxLength)]; - } public static string Replace_Reverse(this string value, string? newValue, string oldValue) { return value.Replace(oldValue, newValue); diff --git a/src/EasMe/Extensions/XmlExtensions.cs b/src/EasMe/Extensions/XmlExtensions.cs index 5e1ed718..ac6bf6c6 100644 --- a/src/EasMe/Extensions/XmlExtensions.cs +++ b/src/EasMe/Extensions/XmlExtensions.cs @@ -5,7 +5,8 @@ namespace EasMe.Extensions; -public static class XmlExtensions { +public static class XmlExtensions +{ /// /// Deserializes given XElement to T type object. /// @@ -44,16 +45,16 @@ public static class XmlExtensions { public static List XmlDeserialize(this IEnumerable xElements) { var list = new List(); Parallel.ForEach(xElements, el => { - var item = el.XmlDeserialize(); - if (item != null) - lock (list) { - list.Add(item); - } - }); + var item = el.XmlDeserialize(); + if (item != null) + lock (list) { + list.Add(item); + } + }); return list; } - public static string ToXML(this T t) { + public static string ToXml(this T t) { using var stringwriter = new StringWriter(); var serializer = new XmlSerializer(t.GetType()); serializer.Serialize(stringwriter, t); @@ -83,22 +84,21 @@ public static XElement ToXElement(this T obj) { } } - public static XElement? ToXML(this T t, string elementName, bool asAtrribute = false) { + public static XElement? ToXml(this T t, string elementName, bool asAttribute = false) { var docElement = new XElement(elementName); var type = t?.GetType(); var properties = type?.GetProperties(); if (properties == null) return default; foreach (var property in properties) { var value = property.GetValue(t); - if (value != null) { - if (asAtrribute) { - var element = new XAttribute(property.Name, value); - docElement.Add(element); - } - else { - var element = new XElement(property.Name, value); - docElement.Add(element); - } + if (value == null) continue; + if (asAttribute) { + var element = new XAttribute(property.Name, value); + docElement.Add(element); + } + else { + var element = new XElement(property.Name, value); + docElement.Add(element); } } diff --git a/src/EasMe/HttpContextHelper.cs b/src/EasMe/HttpContextHelper.cs index 944b1713..50475559 100644 --- a/src/EasMe/HttpContextHelper.cs +++ b/src/EasMe/HttpContextHelper.cs @@ -6,13 +6,13 @@ namespace EasMe; [PROGRAM.CS] => FOR WEB APPLICATIONS builder.Services.AddHttpContextAccessor(); */ -public static class HttpContextHelper { +/// +/// Access to in anywhere. Must register in +/// +/// +public static class HttpContextHelper +{ private static readonly HttpContextAccessor? Accessor = new(); public static HttpContext? Current => Accessor?.HttpContext; - - //public static void test() - //{ - // Current.Session.SetString(); - //} } \ No newline at end of file diff --git a/src/EasMe/Models/CaptchaResponseModel.cs b/src/EasMe/Models/CaptchaResponseModel.cs index 4bd7eae1..13556ff9 100644 --- a/src/EasMe/Models/CaptchaResponseModel.cs +++ b/src/EasMe/Models/CaptchaResponseModel.cs @@ -1,6 +1,7 @@ namespace EasMe.Models; -public class CaptchaResponseModel { +public class CaptchaResponseModel +{ public bool Success { get; set; } = false; public DateTime ChallengeTS { get; set; } public string ApkPackageName { get; set; } diff --git a/src/EasMe/Models/CleanException.cs b/src/EasMe/Models/CleanException.cs index c10f111d..20269a9c 100644 --- a/src/EasMe/Models/CleanException.cs +++ b/src/EasMe/Models/CleanException.cs @@ -3,7 +3,8 @@ namespace EasMe.Models; -public class CleanException { +public class CleanException +{ public CleanException() { } diff --git a/src/EasMe/Properties/PublishProfiles/FolderProfile.pubxml b/src/EasMe/Properties/PublishProfiles/FolderProfile.pubxml index f7d847ac..496b758e 100644 --- a/src/EasMe/Properties/PublishProfiles/FolderProfile.pubxml +++ b/src/EasMe/Properties/PublishProfiles/FolderProfile.pubxml @@ -3,16 +3,16 @@ https://go.microsoft.com/fwlink/?LinkID=208121. --> - - Relase - Any CPU - bin\Release\net6.0\publish\ - FileSystem - net6.0 - win-x86 - true - false - false - false - + + Relase + Any CPU + bin\Release\net6.0\publish\ + FileSystem + net6.0 + win-x86 + true + false + false + false + \ No newline at end of file diff --git a/src/EasMe/Properties/launchSettings.json b/src/EasMe/Properties/launchSettings.json index 89c04d6d..6f264646 100644 --- a/src/EasMe/Properties/launchSettings.json +++ b/src/EasMe/Properties/launchSettings.json @@ -1,7 +1,7 @@ { "profiles": { "EasMe": { - "commandName": "Project", + "commandName": "Project" } } } \ No newline at end of file diff --git a/src/EasMe/obj/Release/net6.0/EasMe.AssemblyInfo.cs b/src/EasMe/obj/Release/net6.0/EasMe.AssemblyInfo.cs index 3fd3c774..b6e9c05e 100644 --- a/src/EasMe/obj/Release/net6.0/EasMe.AssemblyInfo.cs +++ b/src/EasMe/obj/Release/net6.0/EasMe.AssemblyInfo.cs @@ -13,11 +13,11 @@ [assembly: System.Reflection.AssemblyCompanyAttribute("bberka")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyDescriptionAttribute("CSharp extender library. Contains various extension methods, helper classes.")] -[assembly: System.Reflection.AssemblyFileVersionAttribute("3.5.0")] +[assembly: System.Reflection.AssemblyFileVersionAttribute("4.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("3.5.0")] [assembly: System.Reflection.AssemblyProductAttribute("EasMe")] [assembly: System.Reflection.AssemblyTitleAttribute("EasMe")] -[assembly: System.Reflection.AssemblyVersionAttribute("3.5.0")] +[assembly: System.Reflection.AssemblyVersionAttribute("4.0.0")] [assembly: System.Reflection.AssemblyMetadataAttribute("RepositoryUrl", "https://github.com/bberka/EasMe/tree/master")] // Generated by the MSBuild WriteCodeFragment class. diff --git a/src/EasMe/obj/Release/net6.0/EasMe.AssemblyInfoInputs.cache b/src/EasMe/obj/Release/net6.0/EasMe.AssemblyInfoInputs.cache index 928b320c..5e03aef7 100644 --- a/src/EasMe/obj/Release/net6.0/EasMe.AssemblyInfoInputs.cache +++ b/src/EasMe/obj/Release/net6.0/EasMe.AssemblyInfoInputs.cache @@ -1 +1 @@ -a821788ee8f3147a139a437eb57b43c0b8a6772e +6a383f74d1a1f994b5f656eb739ebca2aab3593a diff --git a/src/EasMe/obj/Release/net6.0/EasMe.csproj.CoreCompileInputs.cache b/src/EasMe/obj/Release/net6.0/EasMe.csproj.CoreCompileInputs.cache index d2fcc7be..91b06f93 100644 --- a/src/EasMe/obj/Release/net6.0/EasMe.csproj.CoreCompileInputs.cache +++ b/src/EasMe/obj/Release/net6.0/EasMe.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -5a61467daeb2dc4355bc4ce373922f7330b797b8 +a7a7722a9db6f6d4b7af546e90a7d485a77e4751 diff --git a/src/EasMe/obj/Release/net6.0/EasMe.dll b/src/EasMe/obj/Release/net6.0/EasMe.dll index 5fb563c1..9a6cff82 100644 Binary files a/src/EasMe/obj/Release/net6.0/EasMe.dll and b/src/EasMe/obj/Release/net6.0/EasMe.dll differ diff --git a/src/EasMe/obj/Release/net6.0/EasMe.pdb b/src/EasMe/obj/Release/net6.0/EasMe.pdb index 13640935..df9c95d1 100644 Binary files a/src/EasMe/obj/Release/net6.0/EasMe.pdb and b/src/EasMe/obj/Release/net6.0/EasMe.pdb differ diff --git a/src/EasMe/obj/Release/net6.0/ref/EasMe.dll b/src/EasMe/obj/Release/net6.0/ref/EasMe.dll index 285ffd19..a806baa4 100644 Binary files a/src/EasMe/obj/Release/net6.0/ref/EasMe.dll and b/src/EasMe/obj/Release/net6.0/ref/EasMe.dll differ diff --git a/src/EasMe/obj/Release/net6.0/refint/EasMe.dll b/src/EasMe/obj/Release/net6.0/refint/EasMe.dll index 285ffd19..a806baa4 100644 Binary files a/src/EasMe/obj/Release/net6.0/refint/EasMe.dll and b/src/EasMe/obj/Release/net6.0/refint/EasMe.dll differ