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
- ///
- ///
- ///
- 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