初始化提交

This commit is contained in:
2025-09-19 17:42:11 +08:00
commit fde5919d99
84 changed files with 55570 additions and 0 deletions

View File

@@ -0,0 +1,394 @@
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace .Utility.Core
{
public static class Checker
{
#region IP
/// <summary>
/// 验证IP
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsIP(this string source)
{
return Regex.IsMatch(source, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase);
}
public static bool HasIP(this string source)
{
return Regex.IsMatch(source, @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])", RegexOptions.IgnoreCase);
}
#endregion
#region EMail是否合法
/// <summary>
/// 验证EMail是否合法
/// </summary>
/// <param name="email">要验证的Email</param>
public static bool IsEmail(this string source)
{
return Regex.IsMatch(source, @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", RegexOptions.IgnoreCase);
}
public static bool HasEmail(this string source)
{
return Regex.IsMatch(source, @"[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})", RegexOptions.IgnoreCase);
}
#endregion
#region
/// <summary>
/// 验证网址
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsUrl(this string source)
{
return Regex.IsMatch(source, @"^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?$", RegexOptions.IgnoreCase);
}
public static bool HasUrl(this string source)
{
return Regex.IsMatch(source, @"(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?", RegexOptions.IgnoreCase);
}
#endregion
#region
/// <summary>
/// 验证日期
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsDateTime(this string source)
{
try
{
DateTime time = Convert.ToDateTime(source);
return true;
}
catch
{
return false;
}
}
#endregion
#region
/// <summary>
/// 验证手机号
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsMobile(this string source)
{
return Regex.IsMatch(source, @"^1[35678]\d{9}$", RegexOptions.IgnoreCase);
}
public static bool HasMobile(this string source)
{
return Regex.IsMatch(source, @"1[35678]\d{9}", RegexOptions.IgnoreCase);
}
#endregion
#region
/// <summary>
/// 验证身份证是否有效
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public static bool IsIDCard(this string Id)
{
if (Id.Length == 18)
{
bool check = IsIDCard18(Id);
return check;
}
else if (Id.Length == 15)
{
bool check = IsIDCard15(Id);
return check;
}
else
{
return false;
}
}
public static bool IsIDCard18(this string Id)
{
long n = 0;
if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(Id.Remove(2)) == -1)
{
return false;//省份验证
}
string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
char[] Ai = Id.Remove(17).ToCharArray();
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
}
int y = -1;
Math.DivRem(sum, 11, out y);
if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
{
return false;//校验码验证
}
return true;//符合GB11643-1999标准
}
public static bool IsIDCard15(this string Id)
{
long n = 0;
if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(Id.Remove(2)) == -1)
{
return false;//省份验证
}
string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
return true;//符合15位身份证标准
}
#endregion
#region Int型的
/// <summary>
/// 是不是Int型的
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsInt(this string source)
{
Regex regex = new Regex(@"^(-){0,1}\d+$");
if (regex.Match(source).Success)
{
if ((long.Parse(source) > 0x7fffffffL) || (long.Parse(source) < -2147483648L))
{
return false;
}
return true;
}
return false;
}
#endregion
#region
/// <summary>
/// 看字符串的长度是不是在限定数之间 一个中文为两个字符
/// </summary>
/// <param name="source">字符串</param>
/// <param name="begin">大于等于</param>
/// <param name="end">小于等于</param>
/// <returns></returns>
public static bool IsLengthStr(this string source, int begin, int end)
{
int length = Regex.Replace(source, @"[^\x00-\xff]", "OK").Length;
if ((length <= begin) && (length >= end))
{
return false;
}
return true;
}
#endregion
#region 010-85849685
/// <summary>
/// 是不是中国电话格式010-85849685
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsTel(this string source)
{
return Regex.IsMatch(source, @"^\d{3,4}-?\d{6,8}$", RegexOptions.IgnoreCase);
}
#endregion
#region 6
/// <summary>
/// 邮政编码 6个数字
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsPostCode(this string source)
{
return Regex.IsMatch(source, @"^\d{6}$", RegexOptions.IgnoreCase);
}
#endregion
#region
/// <summary>
/// 中文
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsChinese(this string source)
{
return Regex.IsMatch(source, @"^[\u4e00-\u9fa5]+$", RegexOptions.IgnoreCase);
}
public static bool hasChinese(this string source)
{
return Regex.IsMatch(source, @"[\u4e00-\u9fa5]+", RegexOptions.IgnoreCase);
}
#endregion
#region 线
/// <summary>
/// 验证是不是正常字符 字母,数字,下划线的组合
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsNormalChar(this string source)
{
return Regex.IsMatch(source, @"[\w\d_]+", RegexOptions.IgnoreCase);
}
#endregion
#region _.5
/// <summary>
/// 验证用户名必须以字母开头可以包含字母、数字、“_”、“.”至少5个字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool checkUserId(this string str)
{
Regex regex = new Regex("[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}");
if (regex.Match(str).Success)
if (regex.Matches(str)[0].Value.Length == str.Length)
return true;
return false;
}
#endregion
/// <summary>
/// 是否是Base64字符串
/// </summary>
/// <param name="eStr"></param>
/// <returns></returns>
public static bool IsBase64(string eStr)
{
if ((eStr.Length % 4) != 0)
{
return false;
}
if (!Regex.IsMatch(eStr, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
{
return false;
}
return true;
}
#region
public static bool IsValidDecimal(this string strIn)
{
return Regex.IsMatch(strIn, @"[0].d{1,2}|[1]");
}
#endregion
#region
public static bool IsValidDate(this string strIn)
{
return Regex.IsMatch(strIn, @"^2d{3}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[1-2]d|3[0-1])(?:0?[1-9]|1d|2[0-3]):(?:0?[1-9]|[1-5]d):(?:0?[1-9]|[1-5]d)$");
}
#endregion
#region
//检察是否正确的日期格式
public static bool IsDate(this string str)
{
//考虑到了4年一度的366天还有特殊的2月的日期
Regex reg = new Regex(@"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$");
return reg.IsMatch(str);
}
#endregion
#region
public static bool IsValidPostfix(this string strIn)
{
return Regex.IsMatch(strIn, @".(?i:gif|jpg)$");
}
#endregion
#region 412
public static bool IsValidByte(this string strIn)
{
return Regex.IsMatch(strIn, @"^[a-z]{4,12}$");
}
#endregion
#region
/// <summary>
/// 判断字符串是否为数字
/// </summary>
/// <param name="str">待验证的字符窜</param>
/// <returns>bool</returns>
public static bool IsNumber(this string str)
{
bool result = true;
foreach (char ar in str)
{
if (!char.IsNumber(ar))
{
result = false;
break;
}
}
return result;
}
#endregion
#region
/// <summary>
/// 是否为数字型
/// </summary>
/// <param name="strNumber"></param>
/// <returns></returns>
public static bool IsDecimal(this string strNumber)
{
return new System.Text.RegularExpressions.Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strNumber);
}
#endregion
#region /
/// <summary>
/// 验证是否包含汉语
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsHanyu(this string str)
{
Regex regex = new Regex("[\u4e00-\u9fa5]");
if (regex.Match(str).Success)
return true;
else
return false;
}
/// <summary>
/// 验证是否全部汉语
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsHanyuAll(this string str)
{
Regex regex = new Regex("[\u4e00-\u9fa5]");
//匹配的内容长度和被验证的内容长度相同时,验证通过
if (regex.Match(str).Success)
if (regex.Matches(str).Count == str.Length)
return true;
//其它,未通过
return false;
}
#endregion
}
}

View File

@@ -0,0 +1,464 @@
using System;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace .Utility.Core
{
/// <summary>
/// ChineseDateTime
/// 一日有十二时辰,一时辰有四刻,一刻有三盏茶,一盏茶有两柱香
/// 一柱香有五分,一分有六弹指,一弹指有十刹那,一刹那为一念
/// </summary>
public class ChineseDateTime
{
#region ====== ======
private readonly ChineseLunisolarCalendar _chineseDateTime;
private readonly DateTime _dateTime;
private readonly int _serialMonth;
private static readonly string[] _chineseNumber = { "", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
private static readonly string[] _chineseMonth =
{
"正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "冬", "腊"
};
private static readonly string[] _chineseDay =
{
"初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
"十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
"廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
};
private static readonly string[] _chineseWeek =
{
"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"
};
private static readonly string[] _celestialStem = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
private static readonly string[] _terrestrialBranch = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
private static readonly string[] _chineseZodiac = { "鼠", "牛", "虎", "免", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
private static readonly string[] _solarTerm =
{
"小寒", "大寒", "立春", "雨水", "惊蛰", "春分",
"清明", "谷雨", "立夏", "小满", "芒种", "夏至",
"小暑", "大暑", "立秋", "处暑", "白露", "秋分",
"寒露", "霜降", "立冬", "小雪", "大雪", "冬至"
};
private static readonly int[] _solarTermInfo = {
0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072, 240693, 263343, 285989,
308563, 331033, 353350, 375494, 397447, 419210, 440795, 462224, 483532, 504758
};
#endregion
#region ======= ======
public ChineseDateTime(DateTime dateTime)
{
_chineseDateTime = new ChineseLunisolarCalendar();
if (dateTime < _chineseDateTime.MinSupportedDateTime || dateTime > _chineseDateTime.MaxSupportedDateTime)
{
throw new ArgumentOutOfRangeException(
$"参数日期不在有效的范围内:只支持{_chineseDateTime.MinSupportedDateTime.ToShortTimeString()}到{_chineseDateTime.MaxSupportedDateTime}");
}
Year = _chineseDateTime.GetYear(dateTime);
Month = _chineseDateTime.GetMonth(dateTime);
Day = _chineseDateTime.GetDayOfMonth(dateTime);
IsLeep = _chineseDateTime.IsLeapMonth(Year, Month);
_dateTime = dateTime;
_serialMonth = Month;
var leepMonth = _chineseDateTime.GetLeapMonth(Year);
if (leepMonth > 0 && leepMonth <= Month) Month--;
}
/// <summary>
/// 参数为农历的年月日及是否润月
/// </summary>
/// <param name="year"></param>
/// <param name="month"></param>
/// <param name="day"></param>
/// <param name="isLeap"></param>
public ChineseDateTime(int year, int month, int day, bool isLeap = false)
: this(year, month, day, 0, 0, 0, isLeap)
{
}
public ChineseDateTime(int year, int month, int day, int hour, int minute, int second, bool isLeap = false)
: this(year, month, day, hour, minute, second, 0, isLeap)
{
}
public ChineseDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, bool isLeap = false)
{
_chineseDateTime = new ChineseLunisolarCalendar();
if (year < _chineseDateTime.MinSupportedDateTime.Year || year >= _chineseDateTime.MaxSupportedDateTime.Year)
{
throw new ArgumentOutOfRangeException(
$"参数年份不在有效的范围内,只支持{_chineseDateTime.MinSupportedDateTime.Year}到{_chineseDateTime.MaxSupportedDateTime.Year - 1}");
}
if (month < 1 || month > 12) throw new ArgumentOutOfRangeException($"月份只支持1-12");
IsLeep = isLeap;
var leepMonth = _chineseDateTime.GetLeapMonth(year);
if (leepMonth - 1 != month)
IsLeep = false;
_serialMonth = month;
if (leepMonth > 0 && (month == leepMonth - 1 && isLeap || month > leepMonth - 1))
_serialMonth = month + 1;
if (_chineseDateTime.GetDaysInMonth(year, _serialMonth) < day || day < 1)
throw new ArgumentOutOfRangeException($"指定的月份天数,不在有效的范围内");
Year = year;
Month = month;
Day = day;
_dateTime = _chineseDateTime.ToDateTime(Year, _serialMonth, Day, hour, minute, second, millisecond);
}
public static ChineseDateTime Now => new ChineseDateTime(DateTime.Now);
#endregion
#region ====== ======
public int Year { get; }
public int Month { get; }
public int Day { get; }
/// <summary>
/// 是否为润月
/// </summary>
public bool IsLeep { get; }
#endregion
#region ====== ======
/// <summary>
/// 转换为公历
/// </summary>
/// <returns></returns>
public DateTime ToDateTime()
{
return _chineseDateTime.ToDateTime(Year, _serialMonth, Day, _dateTime.Hour,
_dateTime.Minute,
_dateTime.Second, _dateTime.Millisecond);
}
/// <summary>
/// 短日期(农历)
/// </summary>
/// <returns></returns>
public string ToShortDateString()
{
return $"{Year}-{GetLeap(false)}{Month}-{Day}";
}
/// <summary>
/// 长日期(农历)
/// </summary>
/// <returns></returns>
public string ToLongDateString()
{
return $"{Year}年{GetLeap()}{Month}月-{Day}日";
}
public new string ToString()
{
return $"{Year}-{GetLeap(false)}{Month}-{Day} {_dateTime.Hour}:{_dateTime.Minute}:{_dateTime.Second}";
}
#endregion
#region ====== ======
public string ToChineseString()
{
return ToChineseString("yMd");
}
public string GetChineseDate()
{
var date = new StringBuilder();
date.Append(GetMonth() + "月");
date.Append(GetDay() + "");
date.AppendLine();
date.Append(GetEraYear() + ChineseZodiac + "年");
date.AppendLine();
return date.ToString();
}
public string ToChineseString(string format)
{
var year = GetYear();
var month = GetMonth();
var day = GetDay();
var date = new StringBuilder();
foreach (var item in format.ToCharArray())
{
switch (item)
{
case 'y':
date.Append($"{year}年");
break;
case 'M':
date.Append($"{month}月");
break;
case 'd':
date.Append($"{day}");
break;
default:
date.Append(item);
break;
}
}
var def = $"{year}年{month}月{day}";
var result = date.ToString();
return string.IsNullOrEmpty(result) ? def : result;
}
public string ChineseWeek => _chineseWeek[(int)_dateTime.DayOfWeek];
#endregion
#region ====== ======
public string ToChineseEraString()
{
return ToChineseEraString("yMdHm");
}
public string ToChineseEraString(string format)
{
var year = GetEraYear();
var month = GetEraMonth();
var day = GetEraDay();
var hour = GetEraHour();
var minute = GetEraMinute();
var date = new StringBuilder();
foreach (var item in format.ToCharArray())
{
switch (item)
{
case 'y':
date.Append($"{year}年");
break;
case 'M':
date.Append($"{month}月");
break;
case 'd':
date.Append($"{day}日");
break;
case 'H':
date.Append($"{hour}时");
break;
case 'm':
date.Append($"{minute}刻");
break;
default:
date.Append(item);
break;
}
}
var def = $"{year}年{month}月{day}日{hour}时";
var result = date.ToString();
return result.IsNullOrEmpty() ? def : result;
}
public string ChineseZodiac => _chineseZodiac[(Year - 4) % 12];
#endregion
#region ====== (Chinese) ======
private string GetYear()
{
var yearArray = Array.ConvertAll(Year.ToString().ToCharArray(), x => int.Parse(x.ToString()));
var year = new StringBuilder();
foreach (var item in yearArray)
year.Append(_chineseNumber[item]);
return year.ToString();
}
private string GetMonth()
{
return $"{GetLeap()}{_chineseMonth[Month - 1]}";
}
private string GetDay()
{
return _chineseDay[Day - 1];
}
private string GetLeap(bool isChinese = true)
{
return IsLeep ? isChinese ? "润" : "L" : "";
}
#endregion
#region ====== ======
//年采用的头尾法,月采用的是节令法,主流日历基本上都这种结合,如百度的日历
private string GetEraYear()
{
var sexagenaryYear = _chineseDateTime.GetSexagenaryYear(_dateTime);
var stemIndex = _chineseDateTime.GetCelestialStem(sexagenaryYear) - 1;
var branchIndex = _chineseDateTime.GetTerrestrialBranch(sexagenaryYear) - 1;
return $"{_celestialStem[stemIndex]}{_terrestrialBranch[branchIndex]}";
}
private string GetEraMonth()
{
#region ====== ======
var solarIndex = SolarTermFunc((x, y) => x <= y, out var dt);
solarIndex = solarIndex == -1 ? 23 : solarIndex;
var currentIndex = (int)Math.Floor(solarIndex / (decimal)2);
//天干
var solarMonth = currentIndex == 0 ? 11 : currentIndex - 1; //计算天干序(月份)
var sexagenaryYear = _chineseDateTime.GetSexagenaryYear(_dateTime);
var stemYear = _chineseDateTime.GetCelestialStem(sexagenaryYear) - 1;
if (solarMonth == 0) //立春时,春节前后的不同处理
{
var year = _chineseDateTime.GetYear(dt);
var month = _chineseDateTime.GetMonth(dt);
stemYear = year == Year && month != 1 ? stemYear + 1 : stemYear;
}
if (solarMonth == 11) //立春在春节后,对前一节气春节前后不同处理
{
var year = _chineseDateTime.GetYear(dt);
stemYear = year != Year ? stemYear - 1 : stemYear;
}
int stemIndex;
switch (stemYear)
{
case 0:
case 5:
stemIndex = 3;
break;
case 1:
case 6:
stemIndex = 5;
break;
case 2:
case 7:
stemIndex = 7;
break;
case 3:
case 8:
stemIndex = 9;
break;
default:
stemIndex = 1;
break;
}
//天干序
stemIndex = (stemIndex - 1 + solarMonth) % 10;
//地支序
var branchIndex = currentIndex >= 11 ? currentIndex - 11 : currentIndex + 1;
return $"{_celestialStem[stemIndex]}{_terrestrialBranch[branchIndex]}";
#endregion
#region ====== ======
//这里算法要容易些,原理和节令法一样,只需取农历整年整月即可。未贴上来
#endregion
}
private string GetEraDay()
{
var ts = _dateTime - new DateTime(1901, 2, 15);
var offset = ts.Days;
var sexagenaryDay = offset % 60;
return $"{_celestialStem[sexagenaryDay % 10]}{_terrestrialBranch[sexagenaryDay % 12]}";
}
private string GetEraHour()
{
var hourIndex = (int)Math.Floor((_dateTime.Hour + 1) / (decimal)2);
hourIndex = hourIndex == 12 ? 0 : hourIndex;
return _terrestrialBranch[hourIndex];
}
private string GetEraMinute()
{
var realMinute = (_dateTime.Hour % 2 == 0 ? 60 : 0) + _dateTime.Minute;
return $"{_chineseNumber[(int)Math.Floor(realMinute / (decimal)30) + 1]}";
}
#endregion
#region ====== 24 ======
/// <summary>
/// 当前节气,没有则返回空
/// </summary>
public string SolarTerm
{
get
{
var i = SolarTermFunc((x, y) => x == y, out var dt);
return i == -1 ? "" : _solarTerm[i];
}
}
/// <summary>
/// 上一个节气
/// </summary>
public string SolarTermPrev
{
get
{
var i = SolarTermFunc((x, y) => x < y, out var dt);
return i == -1 ? "" : _solarTerm[i];
}
}
/// <summary>
/// 下一个节气
/// </summary>
public string SolarTermNext
{
get
{
var i = SolarTermFunc((x, y) => x > y, out var dt);
return i == -1 ? "" : $"{_solarTerm[i]}";
}
}
/// <summary>
/// 节气计算(当前年),返回指定条件的节气序及日期(公历)
/// </summary>
/// <param name="func"></param>
/// <param name="dateTime"></param>
/// <returns>-1时即没找到</returns>
private int SolarTermFunc(Expression<Func<int, int, bool>> func, out DateTime dateTime)
{
var baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
var year = _dateTime.Year;
int[] solar = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
var expressionType = func.Body.NodeType;
if (expressionType != ExpressionType.LessThan && expressionType != ExpressionType.LessThanOrEqual &&
expressionType != ExpressionType.GreaterThan && expressionType != ExpressionType.GreaterThanOrEqual &&
expressionType != ExpressionType.Equal)
{
throw new NotSupportedException("不受支持的操作符");
}
if (expressionType == ExpressionType.LessThan || expressionType == ExpressionType.LessThanOrEqual)
{
solar = solar.OrderByDescending(x => x).ToArray();
}
foreach (var item in solar)
{
var num = 525948.76 * (year - 1900) + _solarTermInfo[item - 1];
var newDate = baseDateAndTime.AddMinutes(num); //按分钟计算
if (func.Compile()(newDate.DayOfYear, _dateTime.DayOfYear))
{
dateTime = newDate;
return item - 1;
}
}
dateTime = _chineseDateTime.MinSupportedDateTime;
return -1;
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
namespace .Utility.Core
{
/// <summary>
/// 枚举类型操作公共类。
/// </summary>
public static class EnumHelper
{
/// <summary>
/// 获取枚举所有成员名称。
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
public static string[] GetNames<T>()
{
return Enum.GetNames(typeof(T));
}
/// <summary>
/// 检测枚举是否包含指定成员。
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="member">成员名或成员值</param>
public static bool IsDefined(this Enum value)
{
Type type = value.GetType();
return Enum.IsDefined(type, value);
}
/// <summary>
/// 返回指定枚举类型的指定值的描述。
/// </summary>
/// <param name="t">枚举类型</param>
/// <param name="v">枚举值</param>
/// <returns></returns>
public static string GetDescription(this Enum value)
{
try
{
Type type = value.GetType();
FieldInfo field = type.GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : string.Empty;
}
catch
{
return string.Empty;
}
}
}
}

View File

@@ -0,0 +1,247 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Utility.Core
{
public static class ExtDateTime
{
/// <summary>
/// 获取格式化字符串,不带时分秒。格式:"yyyy-MM-dd"
/// </summary>
/// <param name="dateTime">日期</param>
public static string ToDateString(this DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd");
}
/// <summary>
/// 获取格式化字符串,不带时分秒。格式:"yyyy-MM-dd"
/// </summary>
/// <param name="dateTime">日期</param>
public static string ToDateString(this DateTime? dateTime)
{
if (dateTime == null)
{
return string.Empty;
}
return ToDateString(dateTime.Value);
}
/// <summary>
/// 获取格式化字符串,不带年月日,格式:"HH:mm:ss"
/// </summary>
/// <param name="dateTime">日期</param>
public static string ToTimeString(this DateTime dateTime)
{
return dateTime.ToString("HH:mm:ss");
}
/// <summary>
/// 获取格式化字符串,不带年月日,格式:"HH:mm:ss"
/// </summary>
/// <param name="dateTime">日期</param>
public static string ToTimeString(this DateTime? dateTime)
{
if (dateTime == null)
{
return string.Empty;
}
return ToTimeString(dateTime.Value);
}
/// <summary>
/// 获取格式化字符串,带毫秒,格式:"yyyy-MM-dd HH:mm:ss.fff"
/// </summary>
/// <param name="dateTime">日期</param>
public static string ToMillisecondString(this DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
}
/// <summary>
/// 获取格式化字符串,带毫秒,格式:"yyyy-MM-dd HH:mm:ss.fff"
/// </summary>
/// <param name="dateTime">日期</param>
public static string ToMillisecondString(this DateTime? dateTime)
{
if (dateTime == null)
{
return string.Empty;
}
return ToMillisecondString(dateTime.Value);
}
/// <summary>
/// 获取格式化字符串,不带时分秒,格式:"yyyy年MM月dd日"
/// </summary>
/// <param name="dateTime">日期</param>
public static string ToChineseDateString(this DateTime dateTime)
{
return string.Format("{0}年{1}月{2}日", dateTime.Year, dateTime.Month, dateTime.Day);
}
/// <summary>
/// 获取格式化字符串,带时分秒,格式:"yyyy年MM月dd日 HH时mm分"
/// </summary>
/// <param name="dateTime">日期</param>
/// <param name="isRemoveSecond">是否移除秒</param>
public static string ToChineseDateTimeString(this DateTime dateTime, bool isRemoveSecond = false)
{
StringBuilder result = new StringBuilder();
result.AppendFormat("{0}年{1}月{2}日", dateTime.Year, dateTime.Month, dateTime.Day);
result.AppendFormat(" {0}时{1}分", dateTime.Hour, dateTime.Minute);
if (isRemoveSecond == false)
{
result.AppendFormat("{0}秒", dateTime.Second);
}
return result.ToString();
}
/// <summary>
/// 获取格式化字符串,带时分秒,格式:"yyyy年MM月dd日 HH时mm分"
/// </summary>
/// <param name="dateTime">日期</param>
/// <param name="isRemoveSecond">是否移除秒</param>
public static string ToChineseDateTimeString(this DateTime? dateTime, bool isRemoveSecond = false)
{
if (dateTime == null)
{
return string.Empty;
}
return ToChineseDateTimeString(dateTime.Value);
}
/// <summary>
/// 返回指定日期起始时间。
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime StartDateTime(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
}
/// <summary>
/// 返回指定日期结束时间。
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime EndDateTime(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59);
}
#region
/// <summary>
/// 获取时间戳
/// </summary>
public static string GetTimeStamp(DateTime dateTime)
{
DateTime dtStart = new DateTime(1970, 1, 1, 8, 0, 0);
return Convert.ToInt64(dateTime.Subtract(dtStart).TotalMilliseconds).ToString();
}
#endregion
#region
/// <summary>
/// 根据时间戳获取时间
/// </summary>
public static DateTime TimeStampToDateTime(string timeStamp)
{
DateTime dtStart = new DateTime(1970, 1, 1, 8, 0, 0);
return dtStart.AddMilliseconds(Convert.ToInt64(timeStamp));
}
#endregion
#region
/// <summary>
/// 本周开始时间
/// </summary>
public static DateTime GetCurrentWeekStart()
{
DateTime now = DateTime.Now;
int day = Convert.ToInt32(now.DayOfWeek.ToString("d"));
return now.AddDays(1 - day).Date;
}
#endregion
#region
/// <summary>
/// 本周结束时间
/// </summary>
public static DateTime GetCurrentWeekEnd()
{
return GetCurrentWeekStart().AddDays(7).AddSeconds(-1);
}
#endregion
#region
/// <summary>
/// 本月开始时间
/// </summary>
public static DateTime GetCurrentMonthStart()
{
DateTime now = DateTime.Now;
return now.AddDays(1 - now.Day).Date;
}
#endregion
#region
/// <summary>
/// 本月结束时间
/// </summary>
public static DateTime GetCurrentMonthEnd()
{
return GetCurrentWeekStart().AddMonths(1).AddSeconds(-1);
}
#endregion
#region
/// <summary>
/// 本季度开始时间
/// </summary>
public static DateTime GetCurrentQuarterStart()
{
DateTime now = DateTime.Now;
return now.AddMonths(0 - (now.Month - 1) % 3).AddDays(1 - now.Day).Date;
}
#endregion
#region
/// <summary>
/// 本季度结束时间
/// </summary>
public static DateTime GetCurrentQuarterthEnd()
{
return GetCurrentWeekStart().AddMonths(3).AddSeconds(-1);
}
#endregion
#region
/// <summary>
/// 本年开始时间
/// </summary>
public static DateTime GetCurrentYearStart()
{
return new DateTime(DateTime.Now.Year, 1, 1);
}
#endregion
#region
/// <summary>
/// 本年结束时间
/// </summary>
public static DateTime GetCurrentYearEnd()
{
return new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59);
}
#endregion
}
}

View File

@@ -0,0 +1,59 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
namespace .Utility.Core
{
public static class JsonHelper
{
/// <summary>
/// 对象序列化成JSON字符串。
/// </summary>
/// <param name="obj">序列化对象</param>
/// <param name="ignoreProperties">设置需要忽略的属性</param>
/// <returns></returns>
public static string ToJson(this object obj)
{
if (obj == null)
return string.Empty;
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
return JsonConvert.SerializeObject(obj, timeConverter);
}
/// <summary>
/// JSON字符串序列化成对象。
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">JSON字符串</param>
/// <returns></returns>
public static T ToObject<T>(this string json)
{
return json.IsNullOrEmpty() ? default(T) : JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
/// JSON字符串序列化成集合。
/// </summary>
/// <typeparam name="T">集合类型</typeparam>
/// <param name="json">JSON字符串</param>
/// <returns></returns>
public static List<T> ToList<T>(this string json)
{
return json.IsNullOrEmpty() ? null : JsonConvert.DeserializeObject<List<T>>(json);
}
/// <summary>
/// JSON字符串序列化成DataTable。
/// </summary>
/// <param name="json">JSON字符串</param>
/// <returns></returns>
public static DataTable ToTable(this string json)
{
return json.IsNullOrEmpty() ? null : JsonConvert.DeserializeObject<DataTable>(json);
}
}
}

View File

@@ -0,0 +1,255 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace .Utility.Core
{
/// <summary>
/// LINQ扩展方法
/// </summary>
public static class LinqExtension
{
/// <summary>
/// 与连接
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="left">左条件</param>
/// <param name="right">右条件</param>
/// <returns>新表达式</returns>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
{
return CombineLambdas(left, right, ExpressionType.AndAlso);
}
/// <summary>
/// 或连接
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="left">左条件</param>
/// <param name="right">右条件</param>
/// <returns>新表达式</returns>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
{
return CombineLambdas(left, right, ExpressionType.OrElse);
}
private static Expression<Func<T, bool>> CombineLambdas<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right, ExpressionType expressionType)
{
var visitor = new SubstituteParameterVisitor
{
Sub =
{
[right.Parameters[0]] = left.Parameters[0]
}
};
Expression body = Expression.MakeBinary(expressionType, left.Body, visitor.Visit(right.Body));
return Expression.Lambda<Func<T, bool>>(body, left.Parameters[0]);
}
/// <summary>
/// 取最大值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static TResult MaxOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector) => source.Select(selector).OrderByDescending(_ => _).FirstOrDefault();
/// <summary>
/// 取最大值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static TResult MaxOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, TResult defaultValue)
{
TResult result = source.Select(selector).OrderByDescending(_ => _).FirstOrDefault();
if (result != null)
return result;
return defaultValue;
}
/// <summary>
/// 取最大值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static TSource MaxOrDefault<TSource>(this IQueryable<TSource> source)
{
return source.OrderByDescending(_ => _).FirstOrDefault();
}
/// <summary>
/// 取最大值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static TSource MaxOrDefault<TSource>(this IQueryable<TSource> source, TSource defaultValue)
{
TSource result = source.OrderByDescending(_ => _).FirstOrDefault();
if (result != null)
return result;
return defaultValue;
}
/// <summary>
/// 取最大值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static TResult MaxOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, TResult defaultValue)
{
TResult result = source.Select(selector).OrderByDescending(_ => _).FirstOrDefault();
if (result != null)
return result;
return defaultValue;
}
/// <summary>
/// 取最大值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static TSource MaxOrDefault<TSource>(this IEnumerable<TSource> source) => source.OrderByDescending(_ => _).FirstOrDefault();
/// <summary>
/// 取最大值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static TSource MaxOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
TSource result = source.OrderByDescending(_ => _).FirstOrDefault();
if (result != null)
return result;
return defaultValue;
}
/// <summary>
/// 取最小值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static TResult MinOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector) => source.Select(selector).OrderBy(_ => _).FirstOrDefault();
/// <summary>
/// 取最小值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static TResult MinOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, TResult defaultValue)
{
TResult result = source.Select(selector).OrderBy(_ => _).FirstOrDefault();
if (result != null)
return result;
return defaultValue;
}
/// <summary>
/// 取最小值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static TSource MinOrDefault<TSource>(this IQueryable<TSource> source) => source.OrderBy(_ => _).FirstOrDefault();
/// <summary>
/// 取最小值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static TSource MinOrDefault<TSource>(this IQueryable<TSource> source, TSource defaultValue)
{
TSource result = source.OrderBy(_ => _).FirstOrDefault();
if (result != null)
return result;
return defaultValue;
}
/// <summary>
/// 取最小值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <returns></returns>
public static TResult MinOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) => source.Select(selector).OrderBy(_ => _).FirstOrDefault();
/// <summary>
/// 取最小值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static TResult MinOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, TResult defaultValue)
{
TResult result = source.Select(selector).OrderBy(_ => _).FirstOrDefault();
if (result != null)
return result;
return defaultValue;
}
/// <summary>
/// 取最小值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static TSource MinOrDefault<TSource>(this IEnumerable<TSource> source) => source.OrderBy(_ => _).FirstOrDefault();
/// <summary>
/// 取最小值
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static TSource MinOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
TSource result = source.OrderBy(_ => _).FirstOrDefault();
if (result != null)
return result;
return defaultValue;
}
}
internal class SubstituteParameterVisitor : ExpressionVisitor
{
public Dictionary<Expression, Expression> Sub = new Dictionary<Expression, Expression>();
protected override Expression VisitParameter(ParameterExpression node)
{
return Sub.TryGetValue(node, out var newValue) ? newValue : node;
}
}
}

View File

@@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace .Utility.Core
{
public static class RMB
{/// <summary>
/// 转换人民币大小金额
/// </summary>
/// <param name="num">金额</param>
/// <returns>返回大写形式</returns>
public static string ToRMB(this decimal num)
{
string str1 = "零壹贰叁肆伍陆柒捌玖"; //0-9所对应的汉字
string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字
string str3 = ""; //从原num值中取出的值
string str4 = ""; //数字的字符串形式
string str5 = ""; //人民币大写金额形式
int i; //循环变量
int j; //num的值乘以100的字符串长度
string ch1 = ""; //数字的汉语读法
string ch2 = ""; //数字位的汉字读法
int nzero = 0; //用来计算连续的零值是几个
int temp; //从原num值中取出的值
num = Math.Round(Math.Abs(num), 2); //将num取绝对值并四舍五入取2位小数
str4 = ((long)(num * 100)).ToString(); //将num乘100并转换成字符串形式
j = str4.Length; //找出最高位
if (j > 15) { return "溢出"; }
str2 = str2.Substring(15 - j); //取出对应位数的str2的值。如200.55,j为5所以str2=佰拾元角分
//循环取出每一位需要转换的值
for (i = 0; i < j; i++)
{
str3 = str4.Substring(i, 1); //取出需转换的某一位的值
temp = Convert.ToInt32(str3); //转换为数字
if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
{
//当所取位数不为元、万、亿、万亿上的数字时
if (str3 == "0")
{
ch1 = "";
ch2 = "";
nzero = nzero + 1;
}
else
{
if (str3 != "0" && nzero != 0)
{
ch1 = "零" + str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
ch1 = str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
}
}
else
{
//该位是万亿,亿,万,元位等关键位
if (str3 != "0" && nzero != 0)
{
ch1 = "零" + str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
if (str3 != "0" && nzero == 0)
{
ch1 = str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
if (str3 == "0" && nzero >= 3)
{
ch1 = "";
ch2 = "";
nzero = nzero + 1;
}
else
{
if (j >= 11)
{
ch1 = "";
nzero = nzero + 1;
}
else
{
ch1 = "";
ch2 = str2.Substring(i, 1);
nzero = nzero + 1;
}
}
}
}
}
if (i == (j - 11) || i == (j - 3))
{
//如果该位是亿位或元位,则必须写上
ch2 = str2.Substring(i, 1);
}
str5 = str5 + ch1 + ch2;
if (i == j - 1 && str3 == "0")
{
//最后一位为0时加上“整”
str5 = str5 + '整';
}
}
if (num == 0)
{
str5 = "零元整";
}
return str5;
}
public static string ToRMB(this int num)
{
return ToRMB(Convert.ToString(num));
}
public static string ToRMB(this float num)
{
return ToRMB(Convert.ToString(num));
}
public static string ToRMB(this double num)
{
return ToRMB(Convert.ToString(num));
}
public static string ToRMB(this long num)
{
return ToRMB(Convert.ToString(num));
}
/// <summary>
/// 一个重载将字符串先转换成数字在调用CmycurD(decimal num)
/// </summary>
/// <param name="num">用户输入的金额字符串形式未转成decimal</param>
/// <returns></returns>
public static string ToRMB(this string numstr)
{
try
{
decimal num = Convert.ToDecimal(numstr);
return ToRMB(num);
}
catch
{
return "非数字形式!";
}
}
}
}

View File

@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace .Utility.Core
{
/// <summary>
/// 使用Random类生成伪随机数
/// </summary>
public static class RandomHelper
{
/// <summary>
/// 生成一个指定范围的随机整数,该随机数范围包括最小值,但不包括最大值
/// </summary>
/// <param name="minNum">最小值</param>
/// <param name="maxNum">最大值</param>
public static int GetRandomInt(int minNum, int maxNum)
{
return new Random().Next(minNum, maxNum);
}
/// <summary>
/// 生成一个0.0到1.0的随机小数
/// </summary>
public static double GetRandomDouble()
{
return new Random().NextDouble();
}
/// <summary>
/// 对一个数组进行随机排序
/// </summary>
/// <typeparam name="T">数组的类型</typeparam>
/// <param name="arr">需要随机排序的数组</param>
public static void GetRandomArray<T>(T[] arr)
{
//对数组进行随机排序的算法:随机选择两个位置,将两个位置上的值交换
//交换的次数,这里使用数组的长度作为交换次数
int count = arr.Length;
//开始交换
for (int i = 0; i < count; i++)
{
//生成两个随机数位置
int targetIndex1 = GetRandomInt(0, arr.Length);
int targetIndex2 = GetRandomInt(0, arr.Length);
//定义临时变量
T temp;
//交换两个随机数位置的值
temp = arr[targetIndex1];
arr[targetIndex1] = arr[targetIndex2];
arr[targetIndex2] = temp;
}
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace .Utility.Core
{
/// <summary>
/// 操作正则表达式的公共类
/// </summary>
public class RegexHelper
{
/// <summary>
/// 验证输入字符串是否与模式字符串匹配匹配返回true
/// </summary>
/// <param name="input">输入字符串</param>
/// <param name="pattern">模式字符串</param>
public static bool IsMatch(string input, string pattern)
{
return IsMatch(input, pattern, RegexOptions.IgnoreCase);
}
/// <summary>
/// 验证输入字符串是否与模式字符串匹配匹配返回true
/// </summary>
/// <param name="input">输入的字符串</param>
/// <param name="pattern">模式字符串</param>
/// <param name="options">筛选条件</param>
public static bool IsMatch(string input, string pattern, RegexOptions options)
{
return Regex.IsMatch(input, pattern, options);
}
}
}

View File

@@ -0,0 +1,279 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Reflection;
namespace .Utility.Core
{
#if NETFRAMEWORK
/// <summary>
/// 注册表辅助类
/// </summary>
public class RegisterHelper
{
/// <summary>
/// 默认注册表基项
/// </summary>
private string baseKey = "Software";
#region
/// <summary>
/// 构造函数
/// </summary>
/// <param name="baseKey">基项的名称</param>
public RegisterHelper()
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="baseKey">基项的名称</param>
public RegisterHelper(string baseKey)
{
this.baseKey = baseKey;
}
#endregion
#region
/// <summary>
/// 写入注册表,如果指定项已经存在,则修改指定项的值
/// </summary>
/// <param name="keytype">注册表基项枚举</param>
/// <param name="key">注册表项,不包括基项</param>
/// <param name="name">值名称</param>
/// <param name="values">值</param>
public void SetValue(KeyType keytype, string key, string name, string values)
{
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
RegistryKey software = rk.OpenSubKey(baseKey, true);
RegistryKey rkt = software.CreateSubKey(key);
if (rkt != null)
{
rkt.SetValue(name, values);
}
}
/// <summary>
/// 读取注册表
/// </summary>
/// <param name="keytype">注册表基项枚举</param>
/// <param name="key">注册表项,不包括基项</param>
/// <param name="name">值名称</param>
/// <returns>返回字符串</returns>
public string GetValue(KeyType keytype, string key, string name)
{
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
RegistryKey software = rk.OpenSubKey(baseKey, true);
RegistryKey rkt = software.OpenSubKey(key);
if (rkt != null)
{
return rkt.GetValue(name).ToString();
}
else
{
return string.Empty;
}
}
/// <summary>
/// 删除注册表中的值
/// </summary>
/// <param name="keytype">注册表基项枚举</param>
/// <param name="key">注册表项名称,不包括基项</param>
/// <param name="name">值名称</param>
public void DeleteValue(KeyType keytype, string key, string name)
{
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
RegistryKey software = rk.OpenSubKey(baseKey, true);
RegistryKey rkt = software.OpenSubKey(key, true);
if (rkt != null)
{
object value = rkt.GetValue(name);
if (value != null)
{
rkt.DeleteValue(name, true);
}
}
}
/// <summary>
/// 删除注册表中的指定项
/// </summary>
/// <param name="keytype">注册表基项枚举</param>
/// <param name="key">注册表中的项,不包括基项</param>
/// <returns>返回布尔值,指定操作是否成功</returns>
public void DeleteSubKey(KeyType keytype, string key)
{
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
RegistryKey software = rk.OpenSubKey(baseKey, true);
if (software != null)
{
software.DeleteSubKeyTree(key);
}
}
/// <summary>
/// 判断指定项是否存在
/// </summary>
/// <param name="keytype">基项枚举</param>
/// <param name="key">指定项字符串</param>
/// <returns>返回布尔值,说明指定项是否存在</returns>
public bool IsExist(KeyType keytype, string key)
{
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
RegistryKey software = rk.OpenSubKey(baseKey);
RegistryKey rkt = software.OpenSubKey(key);
if (rkt != null)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 检索指定项关联的所有值
/// </summary>
/// <param name="keytype">基项枚举</param>
/// <param name="key">指定项字符串</param>
/// <returns>返回指定项关联的所有值的字符串数组</returns>
public string[] GetValues(KeyType keytype, string key)
{
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
RegistryKey software = rk.OpenSubKey(baseKey, true);
RegistryKey rkt = software.OpenSubKey(key);
string[] names = rkt.GetValueNames();
if (names.Length == 0)
{
return names;
}
else
{
string[] values = new string[names.Length];
int i = 0;
foreach (string name in names)
{
values[i] = rkt.GetValue(name).ToString();
i++;
}
return values;
}
}
/// <summary>
/// 将对象所有属性写入指定注册表中
/// </summary>
/// <param name="keytype">注册表基项枚举</param>
/// <param name="key">注册表项,不包括基项</param>
/// <param name="obj">传入的对象</param>
public void SetObjectValue(KeyType keyType, string key, Object obj)
{
if (obj != null)
{
Type t = obj.GetType();
string name;
object value;
foreach (var p in t.GetProperties())
{
if (p != null)
{
name = p.Name;
value = p.GetValue(obj, null);
this.SetValue(keyType, key, name, value.ToString());
}
}
}
}
#endregion
#region
/// <summary>
/// 返回RegistryKey对象
/// </summary>
/// <param name="keyType">注册表基项枚举</param>
/// <returns></returns>
private object GetRegistryKey(KeyType keyType)
{
RegistryKey rk = null;
switch (keyType)
{
case KeyType.HKEY_CLASS_ROOT:
rk = Registry.ClassesRoot;
break;
case KeyType.HKEY_CURRENT_USER:
rk = Registry.CurrentUser;
break;
case KeyType.HKEY_LOCAL_MACHINE:
rk = Registry.LocalMachine;
break;
case KeyType.HKEY_USERS:
rk = Registry.Users;
break;
case KeyType.HKEY_CURRENT_CONFIG:
rk = Registry.CurrentConfig;
break;
}
return rk;
}
#endregion
#region
/// <summary>
/// 注册表基项枚举
/// </summary>
public enum KeyType : int
{
/// <summary>
/// 注册表基项 HKEY_CLASSES_ROOT
/// </summary>
HKEY_CLASS_ROOT,
/// <summary>
/// 注册表基项 HKEY_CURRENT_USER
/// </summary>
HKEY_CURRENT_USER,
/// <summary>
/// 注册表基项 HKEY_LOCAL_MACHINE
/// </summary>
HKEY_LOCAL_MACHINE,
/// <summary>
/// 注册表基项 HKEY_USERS
/// </summary>
HKEY_USERS,
/// <summary>
/// 注册表基项 HKEY_CURRENT_CONFIG
/// </summary>
HKEY_CURRENT_CONFIG
}
#endregion
}
#endif
}

View File

@@ -0,0 +1,316 @@

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace .Utility.Core
{
/// <summary>
/// 字符串操作类
/// </summary>
public static class StringHelper
{
/// <summary>
/// 把字符串按照分隔符转换成 List
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="speater">分隔符</param>
/// <param name="toLower">是否转换为小写</param>
/// <returns></returns>
public static List<string> SplitToList(this string str, char speater = ',', bool toLower = false)
{
List<string> list = new List<string>();
string[] ss = str.Split(speater);
foreach (string s in ss)
{
if (!string.IsNullOrEmpty(s) && s != speater.ToString())
{
string strVal = s;
if (toLower)
{
strVal = s.ToLower();
}
list.Add(strVal);
}
}
return list;
}
/// <summary>
/// 把 List<string> 按照分隔符组装成 string
/// </summary>
/// <param name="list"></param>
/// <param name="speater"></param>
/// <returns></returns>
public static string GetStrArray(this List<string> list, string speater = ",")
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.Count; i++)
{
if (i == list.Count - 1)
{
sb.Append(list[i]);
}
else
{
sb.Append(list[i]);
sb.Append(speater);
}
}
return sb.ToString();
}
/// <summary>
/// 删除最后结尾的指定字符后的字符
/// </summary>
public static string DelLastChar(this string str, string strChar = ",")
{
return str.Substring(0, str.LastIndexOf(strChar));
}
/// <summary>
/// 转全角的函数(SBC case)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string ToSBC(string input)
{
//半角转全角:
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 32)
{
c[i] = (char)12288;
continue;
}
if (c[i] < 127)
c[i] = (char)(c[i] + 65248);
}
return new string(c);
}
/// <summary>
/// 转半角的函数(SBC case)
/// </summary>
/// <param name="input">输入</param>
/// <returns></returns>
public static string ToDBC(string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
return new string(c);
}
/// <summary>
/// 获取正确的Id如果不是正整数返回0
/// </summary>
/// <param name="value"></param>
/// <returns>返回正确的整数ID失败返回0</returns>
public static int ToInt32(this string value)
{
if (IsNumberId(value))
return int.Parse(value);
else
return 0;
}
/// <summary>
/// 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。(0除外)
/// </summary>
/// <param name="_value">需验证的字符串。。</param>
/// <returns>是否合法的bool值。</returns>
public static bool IsNumberId(string _value)
{
return QuickValidate("^[1-9]*[0-9]*$", _value);
}
/// <summary>
/// 快速验证一个字符串是否符合指定的正则表达式。
/// </summary>
/// <param name="_express">正则表达式的内容。</param>
/// <param name="_value">需验证的字符串。</param>
/// <returns>是否合法的bool值。</returns>
public static bool QuickValidate(string _express, string _value)
{
if (_value == null) return false;
Regex myRegex = new Regex(_express);
if (_value.Length == 0)
{
return false;
}
return myRegex.IsMatch(_value);
}
/// <summary>
/// 得到字符串长度一个汉字长度为2
/// </summary>
/// <param name="inputString">参数字符串</param>
/// <returns></returns>
public static int StrLength(this string inputString)
{
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
int tempLen = 0;
byte[] s = ascii.GetBytes(inputString);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
tempLen += 2;
else
tempLen += 1;
}
return tempLen;
}
/// <summary>
/// 截取指定长度字符串
/// </summary>
/// <param name="inputString">要处理的字符串</param>
/// <param name="len">指定长度</param>
/// <returns>返回处理后的字符串</returns>
public static string splitString(this string inputString, int len)
{
bool isShowFix = false;
if (len % 2 == 1)
{
isShowFix = true;
len--;
}
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
int tempLen = 0;
string tempString = "";
byte[] s = ascii.GetBytes(inputString);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
tempLen += 2;
else
tempLen += 1;
try
{
tempString += inputString.Substring(i, 1);
}
catch
{
break;
}
if (tempLen > len)
break;
}
byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
if (isShowFix && mybyte.Length > len)
tempString += "…";
return tempString;
}
/// <summary>
/// HTML转行成TEXT
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string HtmlToTxt(this string strHtml)
{
string[] aryReg ={
@"<script[^>]*?>.*?</script>",
@"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
@"([\r\n])[\s]+",
@"&(quot|#34);",
@"&(amp|#38);",
@"&(lt|#60);",
@"&(gt|#62);",
@"&(nbsp|#160);",
@"&(iexcl|#161);",
@"&(cent|#162);",
@"&(pound|#163);",
@"&(copy|#169);",
@"&#(\d+);",
@"-->",
@"<!--.*\n"
};
string newReg = aryReg[0];
string strOutput = strHtml;
for (int i = 0; i < aryReg.Length; i++)
{
Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
strOutput = regex.Replace(strOutput, string.Empty);
}
strOutput.Replace("<", "");
strOutput.Replace(">", "");
strOutput.Replace("\r\n", "");
return strOutput;
}
/// <summary>
/// 判断对象是否为空为空返回true
/// </summary>
/// <typeparam name="T">要验证的对象的类型</typeparam>
/// <param name="data">要验证的对象</param>
public static bool IsNullOrEmpty(this string data)
{
//如果为null
if (data == null)
{
return true;
}
if (string.IsNullOrEmpty(data.ToString().Trim()))
return true;
return false;
}
/// <summary>
/// 判断对象是否为空为空返回true
/// </summary>
/// <typeparam name="T">要验证的对象的类型</typeparam>
/// <param name="data">要验证的对象</param>
public static bool IsNullOrEmpty<T>(this List<T> collection)
{
if (collection == null)
return true;
if (collection.Count() == 0)
return true;
return false;
}
public static bool IsNullOrEmpty(this DataSet ds)
{
if (ds == null)
return true;
if (ds.Tables.Count == 0)
return true;
return ds.Tables[0].IsNullOrEmpty();
}
public static bool IsNullOrEmpty(this DataTable dt)
{
if (dt == null)
return true;
if (dt.Rows.Count == 0)
return true;
return false;
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Utility.Extension
{
public class MyEnvironment
{
public static string WebRootPath(string path)
{
if (!path.StartsWith("/"))
{
path += "/";
}
return Root("/wwwroot" + path);
}
public static string Root(string vPath)
{
string path = Environment.CurrentDirectory.Replace("/", "\\");
if (!path.EndsWith("\\")) path += "\\";
vPath = vPath.Replace("/", "\\");
if (vPath.StartsWith("\\"))
{
vPath = vPath.Substring(1);
}
return path + vPath;
}
/// <summary>
/// 插件所在路径
/// </summary>
/// <param name="plugType"></param>
/// <param name="vPath"></param>
/// <returns></returns>
public static string PlugRoot(Type plugType, string vPath)
{
string path = plugType.Assembly.Location;
path = path.Substring(0, path.LastIndexOf("\\"));
if (!path.EndsWith("\\")) path += "\\";
vPath = vPath.Replace("/", "\\");
if (vPath.StartsWith("\\"))
{
vPath = vPath.Substring(1);
}
return path + vPath;
}
}
}

View File

@@ -0,0 +1,94 @@
using NLog;
using NLog.Config;
using System;
using .Utility.Extension;
namespace .Utility.Logs
{
public class LogHelper
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private static LogHelper _obj;
private LogHelper()
{
LogManager.Configuration = new XmlLoggingConfiguration(MyEnvironment.Root("/Configs/NLog.config"));
}
public static LogHelper Instance => _obj ?? (new LogHelper());
#region Debug
public void Debug(string msg)
{
_logger.Debug(msg);
}
public void Debug(string msg, Exception err)
{
_logger.Debug(err, msg);
}
#endregion
#region Info
public void Info(string msg)
{
_logger.Info(msg);
}
public void Info(string msg, Exception err)
{
_logger.Info(err, msg);
}
#endregion
#region Warn
public void Warn(string msg)
{
_logger.Warn(msg);
}
public void Warn(string msg, Exception err)
{
_logger.Warn(err, msg);
}
#endregion
#region Trace
public void Trace(string msg)
{
_logger.Trace(msg);
}
public void Trace(string msg, Exception err)
{
_logger.Trace(err, msg);
}
#endregion
#region Error
public void Error(string msg)
{
_logger.Error(msg);
}
public void Error(string msg, Exception err)
{
_logger.Error(err, msg);
}
#endregion
#region Fatal,
public void Fatal(string msg)
{
_logger.Fatal(msg);
}
public void Fatal(string msg, Exception err)
{
_logger.Fatal(err, msg);
}
#endregion
}
}

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace .Utility.ResponseModels
{
/// <summary>
/// 通用AJAX请求响应数据格式模型。
/// </summary>
public class AjaxResult
{
public AjaxResult(ResultType state, string message, object data = null)
{
this.state = state;
this.message = message;
this.data = data;
}
/// <summary>
/// 结果类型。
/// </summary>
public ResultType state { get; set; }
/// <summary>
/// 消息内容。
/// </summary>
public string message { get; set; }
/// <summary>
/// 返回数据。
/// </summary>
public object data { get; set; }
}
/// <summary>
/// 结果类型枚举。
/// </summary>
public enum ResultType
{
/// <summary>
/// 警告。
/// </summary>
Warning = 0,
/// <summary>
/// 成功。
/// </summary>
Success = 1,
/// <summary>
/// 异常。
/// </summary>
Error = 2,
/// <summary>
/// 消息。
/// </summary>
Info = 6
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Utility.ResponseModels
{
/// <summary>
/// 菜单视图模型。
/// </summary>
public class LayNavbar
{
/// <summary>
/// 标题
/// </summary>
public string title { get; set; }
/// <summary>
/// 图标
/// </summary>
public string icon { get; set; }
/// <summary>
/// 是否展开
/// </summary>
public bool spread { get; set; }
/// <summary>
/// 子级菜单集合
/// </summary>
public List<LayChildNavbar> children { get; set; }
}
/// <summary>
/// 子级菜单模型。
/// </summary>
public class LayChildNavbar
{
/// <summary>
/// 标题
/// </summary>
public string title { get; set; }
/// <summary>
/// 图标
/// </summary>
public string icon { get; set; }
/// <summary>
/// 链接
/// </summary>
public string href { get; set; }
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace .Utility.ResponseModels
{
/// <summary>
/// Laytpl + Laypage 分页模型。
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class LayPadding<TEntity> where TEntity : class
{
public int code { get; set; }
/// <summary>
/// 获取结果。
/// </summary>
public bool result { get; set; }
/// <summary>
/// 备注信息。
/// </summary>
public string msg { get; set; }
/// <summary>
/// 数据列表。
/// </summary>
public List<TEntity> list { get; set; }
public string backgroundImage { get; set; }
/// <summary>
/// 记录条数。
/// </summary>
public long count { get; set; }
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Utility.ResponseModels
{
public class LayPaddingDataTable
{
public int code { get; set; }
/// <summary>
/// 获取结果。
/// </summary>
public bool result { get; set; }
/// <summary>
/// 备注信息。
/// </summary>
public string msg { get; set; }
/// <summary>
/// 数据列表。
/// </summary>
public DataTable list { get; set; }
public string backgroundImage { get; set; }
/// <summary>
/// 记录条数。
/// </summary>
public long count { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace .Utility.ResponseModels
{
public class RetStr
{
public string Data { get; set; }
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
namespace .Utility.ResponseModels
{
/// <summary>
/// Select2树形下拉列表模型。
/// </summary>
public class TreeSelect
{
public string id { get; set; }
public string text { get; set; }
public string parentId { get; set; }
public object data { get; set; }
}
public static class TreeSelectHelper
{
public static string ToTreeSelectJson(this List<TreeSelect> data)
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
sb.Append(ToTreeSelectJson(data, "0", ""));
sb.Append("]");
return sb.ToString();
}
private static string ToTreeSelectJson(List<TreeSelect> data, string parentId, string blank)
{
StringBuilder sb = new StringBuilder();
var childList = data.FindAll(t => t.parentId == parentId);
var tabline = "";
if (parentId != "0")
{
tabline = "  ";
}
if (childList.Count > 0)
{
tabline = tabline + blank;
}
foreach (TreeSelect entity in childList)
{
entity.text = tabline + entity.text;
string strJson = JsonConvert.SerializeObject(entity);
sb.Append(strJson);
sb.Append(ToTreeSelectJson(data, entity.id, tabline));
}
return sb.ToString().Replace("}{", "},{");
}
}
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace .Utility.ResponseModels
{
/// <summary>
/// zTree单层节点数据模型。
/// </summary>
public class ZTreeNode
{
/// <summary>
/// 节点ID。
/// </summary>
public string id { get; set; }
/// <summary>
/// 父节点ID。
/// </summary>
public string pId { get; set; }
/// <summary>
/// 节点名称。
/// </summary>
public string name { get; set; }
/// <summary>
/// 是否展开。
/// </summary>
public bool open { get; set; }
/// <summary>
/// 是否选中。
/// </summary>
public bool @checked { get; set; }
}
}