first commit

This commit is contained in:
2026-06-02 20:48:16 +03:30
commit 8e92c983a2
233 changed files with 15744 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
namespace Complex.Application.Common
{
public class CommonRequestDto
{
/// <summary>
/// فیلد ترتیب
/// </summary>
public string? SortField { set; get; }
/// <summary>
/// نحوه ترتیب
/// </summary>
public SortDirection? sortDirection { set; get; } = SortDirection.asc;
public int Page { set; get; } = 0;
public int Length { set; get; } = 10;
}
public enum SortDirection
{
asc,
desc
}
}

View File

@@ -0,0 +1,7 @@
namespace Complex.Application.Common
{
public interface IBaseResponseDto
{
List<string> Action { set; get; }
}
}

View File

@@ -0,0 +1,26 @@
namespace Complex.Common.Dto
{
public class ResultDto
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
}
public class ResultDto<T>
{
public ResultDto()
{
}
public ResultDto(T data,bool isSuccess=true)
{
Data = data;
IsSuccess = isSuccess;
}
public bool IsSuccess { get; set; }
public string Message { get; set; }
public T Data { get; set; }
public int RowCount { set; get; }
}
}

View File

@@ -0,0 +1,71 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace Complex.Common
{
public static class EnumHelpers<T>
{
public static IList<T> GetValues(Enum value)
{
var enumValues = new List<T>();
foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
{
enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));
}
return enumValues;
}
public static T Parse(string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static IList<string> GetNames(Enum value)
{
return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();
}
public static IList<string> GetDisplayValues(Enum value)
{
return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();
}
private static string lookupResource(Type resourceManagerProvider, string resourceKey)
{
foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
{
if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
{
System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
return resourceManager.GetString(resourceKey);
}
}
return resourceKey; // Fallback with the key name
}
public static string GetDisplayValue(T value)
{
try
{
var fieldInfo = value.GetType().GetField(value.ToString());
var descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(DisplayAttribute), false) as DisplayAttribute[];
if (descriptionAttributes[0].ResourceType != null)
return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);
if (descriptionAttributes == null) return string.Empty;
return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}
catch (Exception)
{
return "نا مشخص";
}
}
}
}

View File

@@ -0,0 +1,81 @@
using System.Text;
namespace Complex.Application.Common
{
public class FileIO
{
//==============================================================
public FileIO()
{
//
// TODO: Add constructor logic here
//
}
//==============================================================
/// <summary>
/// ثبت محتوا در یک فایل
/// </summary>
/// <param name="fileName">نام فایل</param>
/// <param name="content">محتوای فایل</param>
public static void Write(string fileName, string content, bool activeInServer = false)
{
//if (!SystemDefine.IsLocal && !activeInServer)
// return;
//System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/FileIO/" + fileName), content, Encoding.UTF8);
Writeln(fileName, content, activeInServer);
}
//==============================================================
public static void Clear(string fileName)
{
//return;
System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "/FileIO/" + fileName, "", Encoding.UTF8);
}
//==============================================================
/// <summary>
/// ثبت محتوا در یک فایل در یک خط جدید
/// </summary>
/// <param name="fileName">نام فایل</param>
/// <param name="content">محتوای فایل</param>
public static void Writeln(string fileName, string content, bool activeInServer = false)
{
//try
{
System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "/FileIO/" + fileName, content + "\r\n", Encoding.UTF8);
}
//catch { }
}
//==============================================================
/// <summary>
/// ثبت محتوا در یک فایل در یک خط جدید
/// </summary>
/// <param name="fileName">نام فایل</param>
/// <param name="content">محتوای فایل</param>
public static void Writeln(string fileName, string description, Exception exc, bool activeInServer = false)
{
//if (!SystemDefine.IsLocal && !activeInServer)
// return;
try
{
Writeln(fileName, ">>>>>>");
Writeln(fileName, description);
while (exc != null)
{
Writeln(fileName, exc.Message);
Writeln(fileName, exc.StackTrace);
exc = exc.InnerException;
}
Writeln(fileName, "<<<<<<");
}
catch { }
}
//==============================================================
}
}

View File

@@ -0,0 +1,44 @@
using System.Linq.Dynamic.Core;
namespace Complex.Application.Common
{
public static class Pagination
{
public static IQueryable<TSource> ToPagedByOrder<TSource>(this IQueryable<TSource> source,
CommonRequestDto commonRequest, out int rowsCount)
{
if (commonRequest.Length < 0)
commonRequest.Length = 20000;
if (commonRequest.Length == 0)
commonRequest.Length = 10;
rowsCount = source.Count();
if (commonRequest.sortDirection == SortDirection.desc)
commonRequest.SortField += " DESC";
source = source.OrderBy(commonRequest.SortField);
return source.Skip(commonRequest.Page * commonRequest.Length).Take(commonRequest.Length);
}
public static IQueryable<TSource> ToPaged<TSource>(this IQueryable<TSource> source, int page, int pageSize, out int rowsCount)
{
if (pageSize == -1)
pageSize = 20000;
if (pageSize == 0)
pageSize = 10;
rowsCount = source.Count();
return source.Skip(page * pageSize).Take(pageSize);
}
public static IQueryable<TSource> ToPaged<TSource>(this IQueryable<TSource> source, int page, int pageSize)
{
if (pageSize == -1)
pageSize = 20000;
if (pageSize == 0)
pageSize = 10;
return source.Skip(page * pageSize).Take(pageSize);
}
}
}

View File

@@ -0,0 +1,238 @@
//using Microsoft.AspNetCore.Cryptography.KeyDerivation;
//using System;
//using System.Runtime.CompilerServices;
//using System.Security.Cryptography;
//using System.Text;
//namespace Complex.Common
//{
// public class PasswordHasher
// {
// // Format Markers:
// // IdentityV2: PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
// // IdentityV2 Format: { 0x00(byte), salt, subkey }
// // IdentityV3: PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
// // IdentityV3 Format: { 0x01(byte), prf(UInt32), iter count(UInt32), salt length(UInt32), salt, subkey }
// // Custom = PBKDF2 with custom configuration.
// // Format: { 0xC0(byte), salt, subkey } OR
// // { 0xC0(byte), prf(UInt32), iter count(UInt32), salt length(UInt32), salt, subkey }
// // Header Info: _includeHeaderInfo
// // IdentityV3 includes configuration in the header, IdentityV2 does not.
// // Use AspNetCore: _useAspNetCore
// // Microsoft.AspNetCore.Cryptography.KeyDerivation is required
// // else use System.Security.Cryptography
// private readonly bool _useAspNetCore;
// private readonly byte _formatMarker;
// private readonly KeyDerivationPrf _prf; // Requires Microsoft.AspNetCore
// private readonly HashAlgorithmName _hashAlgorithmName;
// private readonly bool _includeHeaderInfo;
// private readonly int _saltLength;
// private readonly int _requestedLength;
// private readonly int _iterCount;
// public PasswordHasher()
// {
// _useAspNetCore = true;
// // IdentityV2
// //_formatMarker = 0x00;
// //_prf = KeyDerivationPrf.HMACSHA1; // Requires Microsoft.AspNetCore
// //_hashAlgorithmName = HashAlgorithmName.SHA1;
// //_includeHeaderInfo = false;
// //_saltLength = 128 / 8; // bits/1 byte = 16
// //_requestedLength = 256 / 8; // bits/1 byte = 32
// //_iterCount = 1000;
// // IdentityV3
// _formatMarker = 0x01;
// _prf = KeyDerivationPrf.HMACSHA256; // Requires Microsoft.AspNetCore
// _hashAlgorithmName = HashAlgorithmName.SHA256;
// _includeHeaderInfo = true;
// _saltLength = 128 / 8; // bits/1 byte = 16
// _requestedLength = 256 / 8; // bits/1 byte = 32
// _iterCount = 10000;
// // Custom Max
// //_formatMarker = 0xC0;
// //_prf = KeyDerivationPrf.HMACSHA512; // Requires Microsoft.AspNetCore
// //_hashAlgorithmName = HashAlgorithmName.SHA512;
// //_includeHeaderInfo = true;
// //_saltLength = 512 / 8; // bits/1 byte = 64
// //_requestedLength = 512 / 8; // bits/1 byte = 64
// //_iterCount = 100000;
// }
// public string HashPassword(string password)
// {
// if (string.IsNullOrEmpty(password)) throw new ArgumentNullException(nameof(password));
// byte[] salt = new byte[_saltLength];
// using (var rng = RandomNumberGenerator.Create())
// {
// rng.GetBytes(salt);
// }
// byte[] subkey = new byte[_requestedLength];
// if (_useAspNetCore)
// {
// subkey = KeyDerivation.Pbkdf2(password, salt, _prf, _iterCount, _requestedLength);
// }
// else
// {
// using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, _iterCount, _hashAlgorithmName);
// subkey = pbkdf2.GetBytes(_requestedLength);
// }
// var headerByteLength = 1; // Format marker only
// if (_includeHeaderInfo) headerByteLength = 13;
// var outputBytes = new byte[headerByteLength + salt.Length + subkey.Length];
// outputBytes[0] = (byte)_formatMarker;
// if (_includeHeaderInfo)
// {
// if (_useAspNetCore)
// {
// WriteNetworkByteOrder(outputBytes, 1, (uint)_prf);
// }
// else
// {
// var shaInt = 1;
// if (_hashAlgorithmName == HashAlgorithmName.SHA1) shaInt = 0;
// else if (_hashAlgorithmName == HashAlgorithmName.SHA256) shaInt = 1;
// else if (_hashAlgorithmName == HashAlgorithmName.SHA512) shaInt = 2;
// WriteNetworkByteOrder(outputBytes, 1, (uint)shaInt);
// }
// WriteNetworkByteOrder(outputBytes, 5, (uint)_iterCount);
// WriteNetworkByteOrder(outputBytes, 9, (uint)_saltLength);
// }
// Buffer.BlockCopy(salt, 0, outputBytes, headerByteLength, salt.Length);
// Buffer.BlockCopy(subkey, 0, outputBytes, headerByteLength + _saltLength, subkey.Length);
// return Convert.ToBase64String(outputBytes);
// }
// public bool VerifyPassword(string hashedPassword, string enteredPassword)
// {
// if (string.IsNullOrEmpty(enteredPassword) || string.IsNullOrEmpty(hashedPassword)) return false;
// byte[] decodedHashedPassword;
// try
// {
// decodedHashedPassword = Convert.FromBase64String(hashedPassword);
// }
// catch (Exception)
// {
// return false;
// }
// if (decodedHashedPassword.Length == 0) return false;
// // Read the format marker
// var verifyMarker = (byte)decodedHashedPassword[0];
// if (_formatMarker != verifyMarker) return false;
// try
// {
// if (_includeHeaderInfo)
// {
// // Read header information
// var shaUInt = (uint)ReadNetworkByteOrder(decodedHashedPassword, 1);
// var verifyPrf = shaUInt switch
// {
// 0 => KeyDerivationPrf.HMACSHA1,
// 1 => KeyDerivationPrf.HMACSHA256,
// 2 => KeyDerivationPrf.HMACSHA512,
// _ => KeyDerivationPrf.HMACSHA256,
// };
// if (_prf != verifyPrf) return false;
// var verifyAlgorithmName = shaUInt switch
// {
// 0 => HashAlgorithmName.SHA1,
// 1 => HashAlgorithmName.SHA256,
// 2 => HashAlgorithmName.SHA512,
// _ => HashAlgorithmName.SHA256,
// };
// if (_hashAlgorithmName != verifyAlgorithmName) return false;
// int iterCountRead = (int)ReadNetworkByteOrder(decodedHashedPassword, 5);
// if (_iterCount != iterCountRead) return false;
// int saltLengthRead = (int)ReadNetworkByteOrder(decodedHashedPassword, 9);
// if (_saltLength != saltLengthRead) return false;
// }
// var headerByteLength = 1; // Format marker only
// if (_includeHeaderInfo) headerByteLength = 13;
// // Read the salt
// byte[] salt = new byte[_saltLength];
// Buffer.BlockCopy(decodedHashedPassword, headerByteLength, salt, 0, salt.Length);
// // Read the subkey (the rest of the payload)
// int subkeyLength = decodedHashedPassword.Length - headerByteLength - salt.Length;
// if (_requestedLength != subkeyLength) return false;
// byte[] expectedSubkey = new byte[subkeyLength];
// Buffer.BlockCopy(decodedHashedPassword, headerByteLength + salt.Length, expectedSubkey, 0, expectedSubkey.Length);
// // Hash the incoming password and verify it
// byte[] actualSubkey = new byte[_requestedLength];
// if (_useAspNetCore)
// {
// actualSubkey = KeyDerivation.Pbkdf2(enteredPassword, salt, _prf, _iterCount, subkeyLength);
// }
// else
// {
// using var pbkdf2 = new Rfc2898DeriveBytes(enteredPassword, salt, _iterCount, _hashAlgorithmName);
// actualSubkey = pbkdf2.GetBytes(_requestedLength);
// }
// return ByteArraysEqual(actualSubkey, expectedSubkey);
// }
// catch
// {
// // This should never occur except in the case of a malformed payload, where
// // we might go off the end of the array. Regardless, a malformed payload
// // implies verification failed.
// return false;
// }
// }
// // Compares two byte arrays for equality. The method is specifically written so that the loop is not optimized.
// [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
// private static bool ByteArraysEqual(byte[] a, byte[] b)
// {
// if (a == null && b == null) return true;
// if (a == null || b == null || a.Length != b.Length) return false;
// var areSame = true;
// for (var i = 0; i < a.Length; i++) { areSame &= (a[i] == b[i]); }
// return areSame;
// }
// private static uint ReadNetworkByteOrder(byte[] buffer, int offset)
// {
// return ((uint)(buffer[offset + 0]) << 24)
// | ((uint)(buffer[offset + 1]) << 16)
// | ((uint)(buffer[offset + 2]) << 8)
// | ((uint)(buffer[offset + 3]));
// }
// private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value)
// {
// buffer[offset + 0] = (byte)(value >> 24);
// buffer[offset + 1] = (byte)(value >> 16);
// buffer[offset + 2] = (byte)(value >> 8);
// buffer[offset + 3] = (byte)(value >> 0);
// }
// }
//}

View File

@@ -0,0 +1,36 @@
using AutoMapper;
using Complex.Application.Basic;
using Complex.Application.Complex;
using Complex.Application.PersonService;
using Complex.Application.Services.Basic;
using Complex.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Complex.Mapping;
public partial class MappingProfile : Profile
{
public MappingProfile()
{
//CreateMap<ComplexEntity, ComplexDto>().ReverseMap();
//CreateMap<ComplexEntity, ComplexDto>()
//.ForMember(m => m.InsertTime, m => m.MapFrom(src => EF.Property<DateTime>(src, "InsertTime")))
//.ForMember(m => m.UpdateTime, m => m.MapFrom(src => EF.Property<DateTime?>(src, "UpdateTime")));
CreateMap<ComplexDto, ComplexEntity>().ReverseMap();
//.ReverseMap();
CreateMap<UnitDto, Unit>().ReverseMap();
//CreateMap<Unit, UnitDto>()
//.ForMember(m => m.InsertTime, m => m.MapFrom(src => EF.Property<DateTime>(src, "InsertTime")))
//.ForMember(m => m.UpdateTime, m => m.MapFrom(src => EF.Property<DateTime?>(src, "UpdateTime")));
//.ReverseMap();
CreateMap<UnitStateDto, UnitState>().ReverseMap();
CreateMap<Person, PersonDto>().ReverseMap();
CreateMap<CostCycle, CostCycleDto>().ReverseMap();
}
}

View File

@@ -0,0 +1,295 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace Complex.Application.Utility
{
public class PersianDate
{
public struct PDate
{
public int Year { set; get; }
public int Month { set; get; }
public int Day { set; get; }
}
public PersianDate()
{
}
public static DateTime CurrentDate
{
get
{
return DateTime.Now;
}
}//= DateTime.Now;
public static PersianCalendar persianDate = new PersianCalendar();
public static DateTime ConvertToMiladi(string PersianDateString)
{
if (PersianDateString.IsNullOrEmpty())
return new DateTime();
DateTime date;
var splitP = PersianDateString.Substring(0, 10).Split("- /".ToCharArray()).Select(d => d.ToInt().Value).ToArray();
date = new DateTime(splitP[0], splitP[1], splitP[2], persianDate);
return date;
}
public static int CurrentPersianYear
{
get
{
return persianDate.GetYear(CurrentDate);
}
}
public static int CurrentPersianMonth
{
get
{
return persianDate.GetMonth(CurrentDate);
}
}
public static int CurrentPersianDay
{
get
{
return persianDate.GetDayOfMonth(CurrentDate);
}
}
public static List<string> PersianWeekDay = new List<string>()
{
"شنبه",
"یکشنبه",
"دوشنبه",
"سه شنبه",
"چهارشنبه",
"پنج شنبه",
"جمعه"
};
public static List<string> PersianMonth = new List<string>()
{
"فروردین",
"اردیبهشت",
"خرداد",
"تیر",
"مرداد",
"شهریور",
"مهر",
"آبان",
"آذر",
"دی",
"بهمن",
"اسفند"
};
public static string CurrentMonth
{
get
{
return PersianMonth[persianDate.GetMonth(DateTime.Now) - 1];
}
}
public static string CurrntWeekDay
{
get
{
try
{
var d = (int)persianDate.GetDayOfWeek(DateTime.Now);
if (d == 6)
d = -1;
return PersianWeekDay[d + 1];
}
catch { return persianDate.GetDayOfWeek(DateTime.Now).ToString() + "," + (int)persianDate.GetDayOfWeek(DateTime.Now); }
}
}
public static int CurrentDaysInMonth
{
get
{
return persianDate.GetDaysInMonth(CurrentPersianYear, CurrentPersianMonth);
}
}
public static int StartDayInWeek(int Year, int Month)
{
DateTime dt = ConvertToMiladi(Year + "/" + Month.ToString().PadLeft(2, '0') + "/01");
var d = (int)dt.DayOfWeek;
if (d == 6)
d = -1;
return d + 1;
}
public static int CurrentDayInWeek
{
get
{
try
{
var d = (int)persianDate.GetDayOfWeek(DateTime.Now);
if (d == 6)
d = -1;
return d + 1;
}
catch { return 0; }
}
}
public static string GetToday()
{
return GetDate(DateTime.Now);
//return Year + "/" + ((Month < 10) ? "0" + Month : Month.ToString()) + ((Day < 10) ? "0" + Day : Day.ToString());
}
public static string GetDateStringFormat(string date, bool showIntervalDate = false)
{
if (date.IsNullOrEmpty())
return "--";
date = date.Trim();
string today = GetToday();
if (date == today)
return "امروز";
string yesterday = GetDate(DateTime.Now.AddDays(-1));
if (yesterday == today)
return "دیروز";
string twoYesterday = GetDate(DateTime.Now.AddDays(-2));
if (twoYesterday == today)
return "دو روز پیش";
string treeYesterday = GetDate(DateTime.Now.AddDays(-3));
if (treeYesterday == today)
return "سه روز پیش";
if (showIntervalDate)
{
var m1 = ConvertToMiladi(date);
var diff = DateTime.Now - m1;
return (int)diff.TotalDays + " روز پیش";
}
else
return date.Substring(8).ToInt() + " " + PersianMonth[date.Substring(5, 2).ToInt().Value - 1] + " ماه " + date.Substring(0, 4);
}
public static int? GetDateDiff(string date1, string date2)
{
if (date1.IsNullOrEmpty() || date2.IsNullOrEmpty())
return null;
string today = GetToday();
var m1 = ConvertToMiladi(date1);
var m2 = ConvertToMiladi(date2);
var diff = m2 - m1;
return (int)diff.TotalDays;
}
public static string GetDate(DateTime day)
{
int Year = persianDate.GetYear(day);
int Month = persianDate.GetMonth(day);
int Day = persianDate.GetDayOfMonth(day);
return string.Format("{0:D2}/{1:D2}/{2:D2}", Year, Month, Day);
//return Year + "/" + ((Month < 10) ? "0" + Month : Month.ToString()) + ((Day < 10) ? "0" + Day : Day.ToString());
}
public static PDate GetPDate(DateTime day)
{
PDate pdate = new PDate();
pdate.Year = persianDate.GetYear(day);
pdate.Month = persianDate.GetMonth(day);
pdate.Day = persianDate.GetDayOfMonth(day);
return pdate;
}
public static string ToStandard(string _date)
{
if (_date.IsNullOrEmpty())
return _date;
try
{
var a = _date.Split('/').Select(i => i.ToInt().Value).ToArray();
if (a.Count() < 2)
return _date;
return string.Format("{0:D2}/{1:D2}/{2:D2}", a[0], a[1], a[2]);
}
catch
{
return "";
}
//return Year + "/" + ((Month < 10) ? "0" + Month : Month.ToString()) + ((Day < 10) ? "0" + Day : Day.ToString());
}
public static string GetNowTime(bool BySecond = false, bool ByMiliSecond = false)
{
DateTime dnow = DateTime.Now;
return GetTime(dnow, BySecond, ByMiliSecond);
}
public static string GetTime(DateTime DT, bool BySecond = false, bool ByMiliSecond = false)
{
int minutes = DT.Minute;
int Hour = DT.Hour;
int Second = DT.Second;
bool AN = DT.ToLongTimeString().ToLower().Contains("pm") || DT.ToLongTimeString().Contains("ب");
if (AN && Hour < 12)
Hour += 12;
string time = string.Format("{0:D2}:{1:D2}", Hour, minutes); //((Hour < 10) ? "0" + Hour : Hour.ToString()) + ":" + ((minutes < 10) ? "0" + minutes : minutes.ToString());
if (BySecond)
time += ":" + (Second < 10 ? "0" + Second : Second.ToString());
if (ByMiliSecond)
time += ":" + DT.Millisecond;
return time;
}
public static string GetNowDateTime(bool BySecond = false, bool ByMiliSecond = false)
{
return GetToday() + " - " + GetNowTime(BySecond, ByMiliSecond);
}
public static string GetDateTime(DateTime DT, bool BySecond = false)
{
return GetDate(DT) + " - " + GetTime(DT, BySecond);
}
/// <summary>
/// محاسبه اختلاف دو زمان به ساعت و دقیقه
/// </summary>
/// <param name="beginTime">زمان شروع</param>
/// <param name="endTime">زمان پایان</param>
/// <returns></returns>
public static string GetTimeDiff(string beginTime, string endTime)
{
var begin = beginTime.Split(':').Select(int.Parse).ToArray();
var end = endTime.Split(':').Select(int.Parse).ToArray();
int beginMinutes = begin[0] * 60 + begin[1];
int endMinutes = end[0] * 60 + end[1];
int diffMinutes = endMinutes - beginMinutes;
int hour = diffMinutes / 60;
int minute = diffMinutes % 60;
return string.Format("{0:D2}:{1:D2}", hour, minute);
}
/// <summary>
/// بررسی صحت یک رشته از نظر فرمت تاریخ
/// </summary>
/// <param name="date">تاریخ</param>
/// <returns></returns>
public static bool HasDateFormat(string date)
{
Regex regex = new Regex(@"^([12]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01]))$");
return regex.IsMatch(date);
}
/// <summary>
/// بررسی صحت یک رشته از نظر فرمت زمان
/// </summary>
/// <param name="time">زمان</param>
/// <returns></returns>
public static bool HasTimeFormat(string time)
{
Regex regex = new Regex(@"^([01]?[0-9]|2[0-3]):[0-5][0-9]$");
return regex.IsMatch(time);
}
}
}

View File

@@ -0,0 +1,484 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Complex.Application.Utility
{
public static class ExtendFunction
{
public static string ObjectToJson(this object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
});
//return System.Text.Json.JsonSerializer.Serialize(obj);
}
public static byte[] ToByteArray(this Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
//public static void Log(this Exception ex)
//{
// if (ex is ThreadAbortException)
// {
// return;
// }
// var a = new List<string>() { "[" + ex.Message + "]<br />" };
// a.Add(ex.StackTrace);
// while (ex.InnerException != null)
// {
// ex = ex.InnerException;
// //a.Add("<br />-----------<br />[" + ex.Message + "]<br />---------<br />" + ex.StackTrace);
// }
// long personId = 0;
// if (HttpContext.Current.Session != null && HttpContext.Current.Session["PersonID"] != null)
// personId = HttpContext.Current.Session["PersonID"].ToString().ToLong().Value;
// LogClass.SetLog(personId, -1, ex.Message, false, a, -1, 2);
//}
public static string CodeID(this short ID)
{
return Code_ID(ID);
}
public static string CodeID(this int ID)
{
return Code_ID(ID);
}
public static string CodeID(this long ID)
{
return Code_ID(ID);
}
static string Code_ID(long ID)
{
long id1 = ID ^ 0;//GetResourceLongValue("KeyCode1");
id1 = id1 * 7 + 5;
long id2 = id1.ToString().Length + ID % 10 ^ 0;//GetResourceLongValue("KeyCode2");
return id1 + "_" + id2;
}
public static long DeCodeID(this string ID)
{
string[] ids = ID.Split('_');
long id1 = ids[0].ToLong().Value;
id1 = (id1 - 5) / 7;
id1 = id1 ^ 0;//GetResourceLongValue("KeyCode1");
long id2 = ids[0].Length + id1 % 10 ^ 0;//GetResourceLongValue("KeyCode2");
if (ids[1] == id2.ToString())
return id1;
return -1;
}
public static long? ToLong(this object ID, long? defaultValue = null)
{
long LID;
bool IsLong = long.TryParse(ID + "", out LID);
if (IsLong)
return LID;
else
return defaultValue;
}
public static int Value(this int? number, int defaultInt = 0)
{
if (number.HasValue)
return number.Value;
return defaultInt;
}
public static double Value(this double? number, int defaultInt = 0)
{
if (number.HasValue)
return number.Value;
return defaultInt;
}
public static string NumberToDate(this int? Date)
{
if (Date == null)
return "";
return Date.Value.NumberToDate();
}
public static string NumberToDate(this int Date)
{
try
{
var st = Date.ToString();
return st.Substring(0, 4) + "/" + st.Substring(4, 2) + "/" + st.Substring(6, 2);
}
catch { return ""; }
}
public static int? ToInt(this object ID, int? defaultInt = null)
{
int LID;
bool IsLong = int.TryParse(ID + "", out LID);
if (IsLong)
return LID;
else
return defaultInt;
}
//public static string GetSql(this IQueryable<object> query)
//{
// return ((System.Data.Objects.ObjectQuery)query).ToTraceString();
//}
public static double? ToDouble(this object ID, double? defaultValue = null)
{
double LID;
bool IsDouble = double.TryParse(ID + "", out LID);
if (IsDouble)
return LID;
else
return defaultValue;
}
public static short? ToShort(this object ID)
{
short LID;
bool IsLong = short.TryParse(ID + "", out LID);
if (IsLong)
return LID;
else
return null;
}
public static byte? ToByte(this object ID, byte defaultValue = 0)
{
byte LID;
bool IsLong = byte.TryParse(ID + "", out LID);
if (IsLong)
return LID;
else
return defaultValue;
}
public static bool? ToBool(this object obj)
{
if (obj == null)
return null;
var ID = obj.ToString();
bool b;
if (ID.ToLower() == "false" || ID == "0")
return false;
if (ID.ToLower() == "true" || ID == "1" || ID.ToLower() == "on")
return true;
bool isConvert = bool.TryParse(ID, out b);
if (!isConvert)
return null;
return b;
}
public static string ConvertToBase64(this string str)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
}
public static string ConvertToBase64(this byte[] bytes)
{
return Convert.ToBase64String(bytes);
}
public static string ConvertBase64ToString(this string str)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(str));
}
public static byte[] Base64ToByte(this string str)
{
return Convert.FromBase64String(str);
}
public static string[] Split(this string str, string spliter, StringSplitOptions spo = StringSplitOptions.RemoveEmptyEntries)
{
string[] sp = new string[] { spliter };
return str.Split(sp, spo);
}
public static bool IsNullOrEmpty(this string? str)
{
return string.IsNullOrEmpty(str);
}
public static bool IsNotNullOrEmpty(this string? str)
{
return !string.IsNullOrEmpty(str);
}
public static string CalculateMD5Hash(this string input)
{
// step 1, calculate MD5 hash from input
MD5 md5 = MD5.Create();
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
public static byte[] ToByte(this Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
public static string SimpleCodeString(this string st)
{
if (st == null)
return "";
return string.Join("", st.ConvertToBase64().Reverse()).Replace("=", "*@!").Replace("1", "___").Replace("2", "_1_1_");
}
public static string SimpleDeCodeString(this string st)
{
if (st.IsNullOrEmpty())
return "";
return string.Join("", st.Replace("_1_1_", "2").Replace("___", "1").Replace("*@!", "=").Reverse()).ConvertBase64ToString();
}
public static string SetValisQueryString(this string st)
{
return st;
}
public static byte[] EnCodeString(this string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] += 14;
}
return bytes;
}
public static byte[] EnCodeStringForSearchLike(this string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] += 14;
}
var b = Encoding.UTF8.GetBytes("%");
var finalBytes = new byte[bytes.Length + 2];
finalBytes[0] = b[0];
finalBytes[finalBytes.Length - 1] = b[0];
for (int i = 0; i < bytes.Length; i++)
finalBytes[i + 1] = bytes[i];
return finalBytes;
}
public static string DeCodeString(this byte[] byteArray)
{
if (byteArray == null)
return "";
for (int i = 0; i < byteArray.Length; i++)
{
byteArray[i] -= 14;
}
var bytes = Encoding.UTF8.GetString(byteArray);
return bytes;
}
public static string StripHTML(this string input)
{
return Regex.Replace(input, "<.*?>", string.Empty);
}
public static string SubStrFromStartEnd(this string str, int startindex = 0, int minesLenght = 0)
{
return str.Substring(startindex, str.Length - minesLenght);
}
public static string SubStrWithMax(this string str, int maxLength = 50, string continueStr = "")
{
if (str.Length < maxLength)
return str;
return str.Substring(0, maxLength) + continueStr;
}
public static IList<T> CastToList<T>(this IEnumerable source)
{
return new List<T>(source.Cast<T>());
}
//public static T Cast2<T>(this object obj)
//{
// return (T)obj;
//}
public static T CastTo<T>(this object value, T targetType)
{
// targetType above is just for compiler magic
// to infer the type to cast x to
return (T)value;
}
public static string RemoveFirstLines(this string text, int linesCount)
{
var lines = Regex.Split(text, "\r\n|\r|\n").Skip(linesCount);
return string.Join(Environment.NewLine, lines.ToArray());
}
public static string RemoveEndLines(this string text, int linesCount)
{
var lines = Regex.Split(text, "\r\n|\r|\n").Reverse().Skip(linesCount).Reverse();
return string.Join(Environment.NewLine, lines.ToArray());
}
public static string GetPropertiesValues(this object obj)
{
if (obj == null) return "null";
StringBuilder sb = new StringBuilder();
List<PropertyInfo> props = obj.GetType().GetProperties().ToList();
foreach (var p in props)
{
sb.Append(p.Name).Append(": ").Append(p.GetValue(obj, null));
sb.AppendLine();
}
return sb.ToString();
}
//public static IEnumerable<T> Filter<T>(this IEnumerable<T> source, string searchStr)
//{
// var propsToCheck = typeof(T).GetProperties().Where(a => a.PropertyType == typeof(string));
// var filter = propsToCheck.Aggregate(string.Empty, (s, p) => (s == string.Empty ? string.Empty : string.Format("{0} OR ", s)) + string.Format("{0} == @0", p.Name));
// var filtered = source.AsQueryable().Where(filter, searchStr);
// return filtered;
//}
/// <summary>
/// فرمت تاریخ صحیح است؟
/// </summary>
/// <param name="date">تاریخ</param>
/// <returns></returns>
public static bool HasDateFormat(this string date)
{
return PersianDate.HasDateFormat(date);
}
/// <summary>
/// فرمت زمان معتبر است؟
/// </summary>
/// <param name="time">زمان</param>
/// <returns></returns>
public static bool HasTimeFormat(this string time)
{
return PersianDate.HasTimeFormat(time);
}
/// <summary>
/// تبدیل رشته زمان به دقیقه
/// </summary>
/// <param name="time">زمان</param>
/// <returns></returns>
public static int ConvertTimeToMinutes(this string time)
{
//if (!time.HasTimeFormat())
// return 0;
try
{
var hm = time.Split(':').Select(i => i.ToInt(0).Value).ToArray();
return hm[0] * 60 + hm[1];
}
catch
{
return 0;
}
}
/// <summary>
/// تبدیل دقیقه به رشته زمان
/// </summary>
/// <param name="minutes">دقیقه</param>
/// <returns></returns>
public static string ConvertMinutesToTime(this int minutes)
{
if (minutes < 0)
return "";
return string.Format("{0:D2}:{1:D2}", minutes / 60, minutes % 60);
}
public static object Copy(this object entity, object distEntity, List<string> excludeCopyField = null, int level = 0/*, ILogger logger*/)
{
if (level > 5)
return null;
if (excludeCopyField == null)
excludeCopyField = new List<string>();
var obj1Properties = entity.GetType().GetProperties();
var obj2Properties = distEntity.GetType().GetProperties();
try
{
foreach (var obj1prop in obj1Properties)
{
if (excludeCopyField.Contains(obj1prop.Name))
continue;
var destProp = obj2Properties.FirstOrDefault(x => x.Name == obj1prop.Name);// && x.PropertyType == obj1prop.PropertyType);
//logger.LogInformation("---> " + obj1prop.Name);
if (destProp != null)
{
object srcEnt = obj1prop.GetValue(entity, null);
//logger.LogInformation("------> srcEnt is null: " + (srcEnt == null));
if (srcEnt != null)
{
bool isNullable = destProp.PropertyType.IsGenericType;// && destProp.PropertyType.GetGenericTypeDefinition() == typeof(Nullable);
if (isNullable || destProp.PropertyType.IsPrimitive || destProp.PropertyType == typeof(String))
{
destProp.SetValue(distEntity, srcEnt);
}
else
{
object destEnt = Activator.CreateInstance(destProp.PropertyType);
//logger.LogCritical("=====> destEnt is null: " + (destEnt == null));
if (destEnt != null)
{
var a = srcEnt.Copy(destEnt, excludeCopyField, level + 1);
destProp.SetValue(distEntity, a);
}
}
}
}
}
}
catch
{
return null;
}
return distEntity;
}
public static string CorrectPersianString(this string str)
{
return str.Replace("ك", "ک").Replace("ي", "ی").Replace("ﯼ", "ی").Replace("ى", "ی");
}
}
public class SearchTokenVM
{
public string KeySearch { set; get; }
}
public class RoleParam
{
public int RoleId { set; get; }
}
}