增加老版本 KJDWebService

This commit is contained in:
chfei committed 2026-08-21 16:46:36 +08:00
1 parent 58abbb5b4f
commit f84c4c1949
115 files changed
+36598 -18

No files matched your search

@@ -0,0 +1,53 @@
using StoreHub.KJDWebService.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StoreHub.KJDWebService.Commons
{
public class BaseClass
{
public static string BuildPDDObjString(string file, bool IsLoginDef = false)
{
string LoginApiUrl = "http://1.13.195.131:9001";
string MainPath = "kuajingda";
return LoginApiUrl + "/bxx_" + file + "?obj=" + MainPath + "/bxx_" + file;
}
public static int TimeDifferent = 0;
public static int VersionCount = 99999999;
public static int CompanyId = 1;
public static string CompanyName = "1";
public static string UserKey = "1";
public static string Mobile = "18888888888";
public static string UserName = "18888888888";
public static string ShopId = "18888888888";
public static string ShopName = "18888888888";
}
public class UserLogin
{
/// <summary>
/// 获取签名字符串,新版
/// </summary>
/// <returns></returns>
public static string GetSignaturex()
{
return GetSignaturex(BaseClass.ShopId, BaseClass.ShopName);
}
public static string GetSignaturex(string shopId, string shopName)
{
if (string.IsNullOrEmpty(shopId))
shopId = "11111111";
if (string.IsNullOrEmpty(shopName))
shopName = "wx11111111";
int time = TimeUtils.DateTimeToTimestampSeconds(DateTime.Now) + BaseClass.TimeDifferent;
string time1 = EncrypUtil.Encryption(time);
return "time=" + time + "&code=" + time1 + "&NbCodeVersion=1" + "&version=" + BaseClass.VersionCount +
"&company_id=" + BaseClass.CompanyId + "&company=" + HtmlUtils.UrlEncodeUtf8(BaseClass.CompanyName) +
"&user_name=" + BaseClass.UserName + "&user_key=" + BaseClass.UserKey + "&mobile=" + BaseClass.Mobile +
"&sid=" + shopId + "&shop=" + HtmlUtils.UrlEncodeUtf8(shopName);
}
}
}
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace StoreHub.KJDWebService.Commons
{
public class EncrypUtil
{
/// <summary>
/// 加密算法
/// </summary>
/// <param name="s">加密字符串</param>
/// <returns></returns>
public static string Encryption(int s)
{
string sign = $"{s}sdhewu*/fhAAue48485ew5+5%@3485esGFFHFD";
return GetMd5(sign);
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="instring"></param>
/// <returns></returns>
public static string GetMd5(string instring)
{
byte[] result = Encoding.Default.GetBytes(instring.Trim());
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
return BitConverter.ToString(output).Replace("-", "");
}
/// <summary>
/// 获取文件MD5值
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static string GetFileMd5(string FilePath)
{
try
{
FileStream get_file = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hash_byte = get_md5.ComputeHash(get_file);
string resule = System.BitConverter.ToString(hash_byte);
resule = resule.Replace("-", "");
get_file.Close();
return resule;
}
catch (Exception e)
{
return e.ToString();
}
}
}
}
@@ -0,0 +1,705 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using NaiBa.Util.Helper;
using Newtonsoft.Json;
namespace NaiBa.Util.Extension
{
public static partial class Extensions
{
#region 转换为long
/// <summary>
/// 将object转换为long,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static long ParseToLong(this object obj)
{
if (obj == null)
return 0L;
try
{
string str = obj.ParseToString();
if (string.IsNullOrEmpty(str))
{
return 0;
}
return long.Parse(str);
}
catch
{
return 0L;
}
}
public static long? ParseToNullableLong(this object obj)
{
if (obj == null)
return null;
try
{
string str = obj.ParseToString();
if (string.IsNullOrEmpty(str))
{
return null;
}
return long.Parse(str);
}
catch
{
return null;
}
}
/// <summary>
/// 将object转换为long,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static long ParseToLong(this string str, long defaultValue)
{
if (str == null)
return defaultValue;
try
{
return long.Parse(str);
}
catch
{
return defaultValue;
}
}
#endregion
#region 转换为int
/// <summary>
/// 将object转换为int,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int ParseToInt(this object str)
{
if (str == null)
return 0;
try
{
return Convert.ToInt32(str);
}
catch
{
return 0;
}
}
public static int? ParseToNullableInt(this object str)
{
if (str == null)
return null;
try
{
return Convert.ToInt32(str);
}
catch
{
return null;
}
}
public static int DecimalPointParseToInt(this object str)
{
try
{
string temp = str.ParseToString();
int i = temp.IndexOf('.');
if (i > 0)
{
temp = temp.Substring(0, i);
}
return Convert.ToInt32(temp);
}
catch
{
return 0;
}
}
/// <summary>
/// 将object转换为int,若转换失败,则返回指定值。不抛出异常。
/// null返回默认值
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static int ParseToInt(this object str, int defaultValue)
{
if (str == null)
{
return defaultValue;
}
try
{
return Convert.ToInt32(str);
}
catch
{
return defaultValue;
}
}
#endregion
#region 转换为short
/// <summary>
/// 将object转换为short,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static short ParseToShort(this object obj)
{
try
{
return short.Parse(obj.ToString());
}
catch
{
return 0;
}
}
/// <summary>
/// 将object转换为short,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static short ParseToShort(this object str, short defaultValue)
{
try
{
return short.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
#endregion
#region 转换为demical
/// <summary>
/// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static decimal ParseToDecimal(this object str, decimal defaultValue)
{
try
{
return decimal.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
/// <summary>
/// 将object转换为demical,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static decimal ParseToDecimal(this object str)
{
try
{
return decimal.Parse(str.ToString());
}
catch
{
return 0;
}
}
public static decimal? ParseToNullableDecimal(this object str)
{
try
{
return decimal.Parse(str.ToString());
}
catch
{
return null;
}
}
#endregion
#region 转化为bool
/// <summary>
/// 将object转换为bool,若转换失败,则返回false。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool ParseToBool(this object str)
{
try
{
if (str is null)
return false;
return bool.Parse(str.ToString());
}
catch
{
return false;
}
}
/// <summary>
/// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool ParseToBool(this object str, bool result)
{
try
{
return bool.Parse(str.ToString());
}
catch
{
return result;
}
}
#endregion
#region 转换为float
/// <summary>
/// 将object转换为float,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static float ParseToFloat(this object str)
{
try
{
return float.Parse(str.ToString());
}
catch
{
return 0;
}
}
/// <summary>
/// 将object转换为float,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static float ParseToFloat(this object str, float result)
{
try
{
return float.Parse(str.ToString());
}
catch
{
return result;
}
}
#endregion
#region 转换为Guid
/// <summary>
/// 将string转换为Guid,若转换失败,则返回Guid.Empty。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Guid ParseToGuid(this string str)
{
try
{
return new Guid(str);
}
catch
{
return Guid.Empty;
}
}
#endregion
#region 转换为DateTime
public static DateTime? ParseToDateTimeNullable(this string str)
{
try
{
if (string.IsNullOrWhiteSpace(str))
{
return null;
}
try
{
return DateTime.Parse(str);
}
catch
{
}
if (str.Contains("年") && str.Contains("月") && str.Contains("日") && !str.Contains("周"))
str = str.Replace("年", "-").Replace("月", "-").Replace("日", "").Replace("时", ":").Replace("分", ":").Replace("秒", "").Trim(' ', ':');
if (str.Contains("-") || str.Contains("/"))
{
return DateTime.Parse(str);
}
else
{
int length = str.Length;
switch (length)
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
}
}
catch
{
return null;
}
}
/// <summary>
/// 将string转换为DateTime,若转换失败,则返回日期最小值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static DateTime ParseToDateTime(this string str)
{
try
{
if (string.IsNullOrWhiteSpace(str))
{
return DateTime.MinValue;
}
if (str.Contains("-") || str.Contains("/"))
{
return DateTime.Parse(str);
}
else
{
int length = str.Length;
switch (length)
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
}
}
catch
{
return DateTime.MinValue;
}
}
/// <summary>
/// 将string转换为DateTime,若转换失败,则返回默认值。
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static DateTime ParseToDateTime(this string str, DateTime? defaultValue)
{
try
{
if (string.IsNullOrWhiteSpace(str))
{
return defaultValue.GetValueOrDefault();
}
if (str.Contains("-") || str.Contains("/"))
{
return DateTime.Parse(str);
}
else
{
int length = str.Length;
switch (length)
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
}
}
catch
{
return defaultValue.GetValueOrDefault();
}
}
#endregion
#region 转换为string
/// <summary>
/// 将object转换为string,若转换失败,则返回""。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ParseToString(this object obj)
{
try
{
if (obj == null)
{
return string.Empty;
}
else
{
if (obj is DateTime)
return (obj as DateTime?).Value.ToString("yyyy-MM-dd HH:mm:ss");
return obj.ToString();
}
}
catch
{
return string.Empty;
}
}
public static string ParseToNullableString(this object obj)
{
try
{
if (obj == null)
{
return null;
}
else
{
if (obj is DateTime)
return (obj as DateTime?).Value.ToString("yyyy-MM-dd HH:mm:ss");
return obj.ToString();
}
}
catch
{
return null;
}
}
public static string ParseToStrings<T>(this object obj, string split = ",")
{
try
{
var list = obj as IEnumerable<T>;
if (list != null)
{
return string.Join(split, list);
}
else
{
return obj.ToString();
}
}
catch
{
return string.Empty;
}
}
#endregion
#region 转换为double
/// <summary>
/// 将object转换为double,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static double ParseToDouble(this object obj)
{
try
{
return double.Parse(obj.ToString());
}
catch
{
return 0;
}
}
/// <summary>
/// 将object转换为double,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static double ParseToDouble(this object str, double defaultValue)
{
try
{
return double.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
#endregion
#region 字符串转指定类型Array
public static T[] SplitToArray<T>(this string value, string split = ",")
{
if (string.IsNullOrEmpty(value))
{
return default(T[]);
}
var arr = value.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
return arr;
}
public static T[] SplitToArray<T>(this string value, string[] split)
{
if (string.IsNullOrEmpty(value))
{
return default(T[]);
}
var arr = value.Split(split, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
return arr;
}
#endregion
#region 字符串转指定类型List
public static List<T> SplitToList<T>(this string value, string split = ",")
{
if (string.IsNullOrEmpty(value))
{
return new List<T>();
}
var list = value.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToList();
return list;
}
public static List<T> SplitToList<T>(this string value, string[] split)
{
if (string.IsNullOrEmpty(value))
{
return new List<T>();
}
var list = value.Split(split, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToList();
return list;
}
#endregion
#region 强制转换类型
/// <summary>
/// 强制转换类型
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source)
{
foreach (object item in source)
{
yield return (TResult)Convert.ChangeType(item, typeof(TResult));
}
}
#endregion
#region Object转换为Json
public static string ParseToJson(this object obj)
{
return JsonConvert.SerializeObject(obj);
}
#endregion
#region Json转为Object
public static T ParseToObject<T>(this string json)
{
if (string.IsNullOrEmpty(json))
{
return Activator.CreateInstance<T>();
}
return JsonConvert.DeserializeObject<T>(json);
}
#endregion
#region 深拷贝(克隆出一个新对象,拷贝对象里面的数据和子对象)
public static T DeepClone<T>(this T o)
{
return o.ParseToJson().ParseToObject<T>();
// 这种方式在用 Obfuscator 的时候有问题
//using (MemoryStream stream = new MemoryStream())
//{
// BinaryFormatter formatter = new BinaryFormatter();
// formatter.Serialize(stream, o);
// stream.Position = 0;
// return (T)formatter.Deserialize(stream);
//}
}
#endregion
#region 浅拷贝(拷贝对象里面的数据[property and field],但不拷贝对象里面的子对象)
public static void ShadowClone<T1, T2>(this T1 source, ref T2 destination)
{
var sourceMembers = ReflectionHelper.GetMembers(source.GetType());
var destinationMembers = ReflectionHelper.GetMembers(destination.GetType());
// Copy data from source to destination
foreach (var sourceMember in sourceMembers)
{
if (!ReflectionHelper.CanRead(sourceMember))
{
continue;
}
var destinationMember = destinationMembers.FirstOrDefault(x => x.Name.ToLower() == sourceMember.Name.ToLower());
if (destinationMember == null || !ReflectionHelper.CanWrite(destinationMember))
{
continue;
}
ReflectionHelper.SetObjectValue(ref destination, destinationMember, ReflectionHelper.GetMemberValue(source, sourceMember));
}
}
#endregion
}
}
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace NaiBa.Util.Extension
{
public static partial class Extensions
{
#region 枚举成员转成dictionary类型
/// <summary>
/// 转成dictionary类型
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static Dictionary<int, string> EnumToDictionary(this Type enumType)
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
Type typeDescription = typeof(DescriptionAttribute);
FieldInfo[] fields = enumType.GetFields();
int sValue = 0;
string sText = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
sValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null));
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > 0)
{
DescriptionAttribute da = (DescriptionAttribute)arr[0];
sText = da.Description;
}
else
{
sText = field.Name;
}
dictionary.Add(sValue, sText);
}
}
return dictionary.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
}
/// <summary>
/// 枚举成员转成键值对Json字符串
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static string EnumToDictionaryString(this Type enumType)
{
List<KeyValuePair<int, string>> dictionaryList = EnumToDictionary(enumType).ToList();
var sJson = JsonConvert.SerializeObject(dictionaryList);
return sJson;
}
#endregion
#region 根据类型获取枚举的描述
/// <summary>
/// 获取枚举值对应的描述
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static string GetDescription(this System.Enum enumType)
{
FieldInfo EnumInfo = enumType.GetType().GetField(enumType.ToString());
if (EnumInfo != null)
{
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
return EnumAttributes[0].Description;
}
}
return enumType.ToString();
}
#endregion
#region 根据值获取枚举的描述
public static string GetDescriptionByEnum<T>(this object obj)
{
var tEnum = System.Enum.Parse(typeof(T), obj.ParseToString()) as System.Enum;
var description = tEnum.GetDescription();
return description;
}
#endregion
#region 根据描述获取枚举值
public static int GetEnumValueByDescription<T>(this string description)
{
Dictionary<int, string> dict = typeof(T).EnumToDictionary();
int value = dict.Where(p => p.Value == description).Select(p => p.Key).FirstOrDefault();
return value;
}
#endregion
#region 根据枚举名称获取值
public static int GetEnumValueByName<T>(this string name)
{
return (int)System.Enum.Parse(typeof(T), name);
}
#endregion
#region 根据枚举值获取名称
public static object GetEnumNameByValue<T>(this int value)
{
return System.Enum.ToObject(typeof(T), value);
}
#endregion
}
}
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NaiBa.Util.Extension
{
public static partial class Extensions
{
public static Exception GetOriginalException(this Exception ex)
{
if (ex.InnerException == null) return ex;
return ex.InnerException.GetOriginalException();
}
}
}
@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace NaiBa.Util.Extension
{
public static class LinqExtensions
{
public static Expression Property(this Expression expression, string propertyName)
{
return Expression.Property(expression, propertyName);
}
public static Expression AndAlso(this Expression left, Expression right)
{
return Expression.AndAlso(left, right);
}
public static Expression Call(this Expression instance, string methodName, params Expression[] arguments)
{
return Expression.Call(instance, instance.Type.GetMethod(methodName), arguments);
}
public static Expression GreaterThan(this Expression left, Expression right)
{
return Expression.GreaterThan(left, right);
}
public static Expression<T> ToLambda<T>(this Expression body, params ParameterExpression[] parameters)
{
return Expression.Lambda<T>(body, parameters);
}
public static Expression<Func<T, bool>> True<T>() { return param => true; }
public static Expression<Func<T, bool>> False<T>() { return param => false; }
/// <summary>
/// 组合And
/// </summary>
/// <returns></returns>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.AndAlso);
}
/// <summary>
/// 组合Or
/// </summary>
/// <returns></returns>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.OrElse);
}
/// <summary>
/// Combines the first expression with the second using the specified merge function.
/// </summary>
static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
var map = first.Parameters
.Select((f, i) => new { f, s = second.Parameters[i] })
.ToDictionary(p => p.s, p => p.f);
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
/// <summary>
/// ParameterRebinder
/// </summary>
private class ParameterRebinder : ExpressionVisitor
{
/// <summary>
/// The ParameterExpression map
/// </summary>
readonly Dictionary<ParameterExpression, ParameterExpression> map;
/// <summary>
/// Initializes a new instance of the <see cref="ParameterRebinder"/> class.
/// </summary>
/// <param name="map">The map.</param>
ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
/// <summary>
/// Replaces the parameters.
/// </summary>
/// <param name="map">The map.</param>
/// <param name="exp">The exp.</param>
/// <returns>Expression</returns>
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
/// <summary>
/// Visits the parameter.
/// </summary>
/// <param name="p">The p.</param>
/// <returns>Expression</returns>
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
}
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using NaiBa.Util.Helper;
using Newtonsoft.Json.Linq;
namespace NaiBa.Util.Extension
{
public static partial class Extensions
{
public static bool IsNullOrEmpty(this object value)
{
if (value != null && !string.IsNullOrEmpty(value.ParseToString()))
{
return false;
}
else
{
return true;
}
}
public static bool IsNullOrZero(this object value)
{
if (value == null || string.IsNullOrEmpty(value.ParseToString()) || value.ParseToString().Trim() == "0")
{
return true;
}
else
{
return false;
}
}
public static bool IsNumericType(this object value)
{
if (value == null)
{
return false;
}
switch (Type.GetTypeCode(value.GetType()))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
public static bool IsStringType(this object value)
{
if (value == null)
{
return false;
}
switch (Type.GetTypeCode(value.GetType()))
{
case TypeCode.String:
return true;
default:
return false;
}
}
public static bool IsNumber(this string value)
{
return RegexHelper.IsNumber(value);
}
public static bool IsAlphabet(this string value)
{
return RegexHelper.IsAlphabet(value);
}
public static bool IsAlphabetOrNumber(this string value)
{
return RegexHelper.IsAlphabetOrNumber(value);
}
public static bool IsJson(this string value)
{
return JsonHelper.IsJson(value);
}
public static bool IsJTokenNullOrEmpty(this JToken token)
{
return (token == null) ||
(token.Type == JTokenType.Array && !token.HasValues) ||
(token.Type == JTokenType.Object && !token.HasValues) ||
(token.Type == JTokenType.String && token.ToString() == string.Empty) ||
(token.Type == JTokenType.Null);
}
public static bool IsAjaxRequest(this Microsoft.AspNetCore.Http.HttpRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
if (request.Headers != null)
return request.Headers["X-Requested-With"] == "XMLHttpRequest";
return false;
}
}
}
@@ -0,0 +1,215 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NaiBa.Util.Extension;
namespace NaiBa.Util.Helper
{
public class HtmlHelper
{
public static string HtmlEncode(string html)
{
if (string.IsNullOrEmpty(html))
{
return string.Empty;
}
else
{
return WebUtility.HtmlEncode(html);
}
}
public static string HtmlDecode(string url)
{
if (string.IsNullOrEmpty(url))
{
return string.Empty;
}
else
{
return WebUtility.HtmlDecode(url);
}
}
/// <summary>
/// Unicode解码
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string UnicodeDecode(string html)
{
html = WebUtility.HtmlDecode(html);
Regex reUnicode = new Regex(@"\\u([0-9a-fA-F]{4})", RegexOptions.Compiled);
return reUnicode.Replace(html, m =>
{
short c;
if (short.TryParse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out c))
{
return "" + (char)c;
}
return m.Value;
});
}
#region Resove
public static string Resove(string html, string prefix, string subfix = "")
{
int inl = html.IndexOf(prefix);
if (inl == -1)
{
prefix = prefix.Replace("\"", "'");
subfix = subfix.Replace("\"", "'");
inl = html.IndexOf(prefix);
}
if (inl == -1)
{
return null;
}
inl += prefix.Length;
if (!string.IsNullOrEmpty(subfix))
{
int inl2 = html.IndexOf(subfix, inl);
if (inl2 == -1)
{
return null;
}
string result = html.Substring(inl, inl2 - inl);
return result;
}
else
{
string result = html.Substring(inl);
return result;
}
}
#endregion
#region ResoveReverse
public static string ResoveReverse(string html, string subfix, string prefix)
{
int inl = html.IndexOf(subfix);
if (inl == -1)
{
return null;
}
string subString = html.Substring(0, inl);
int inl2 = subString.LastIndexOf(prefix);
if (inl2 == -1)
{
return null;
}
string s = subString.Substring(inl2 + prefix.Length, subString.Length - inl2 - prefix.Length);
return s;
}
#endregion
#region ResoveList
public static List<string> ResoveList(string html, string prefix, string subfix)
{
List<string> list = new List<string>();
int index = 0;
do
{
index = html.IndexOf(prefix, index);
if (index == -1)
{
break;
}
index += prefix.Length;
int indexEnd = html.IndexOf(subfix, index);
if (indexEnd > 0)
{
string content = html.Substring(index, indexEnd - index);
list.Add(content);
}
index = indexEnd;
}
while (index > -1);
return list;
}
#endregion
#region ResoveListByAT
public static List<string> ResoveListByAT(string html)
{
List<string> list = new List<string>();
int index = html.IndexOf('@');
while (index > 0)
{
int indexx = html.LastIndexOf("'", index); //向前一个单引号
int indexy = html.IndexOf("'", index + 1); //向后一个单引号
string s78 = html.Substring(indexx, indexy - indexx);
s78 = s78.Replace("'", "");
list.Add(s78);
index = html.IndexOf('@', indexy);
}
return list;
}
#endregion
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="html"></param>
public static string ClearHtml(string html)
{
html = html.ParseToString();
html = Regex.Replace(html, @"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", string.Empty);
html = Regex.Replace(html, @"(<span[\w\W]*?</span>)", string.Empty);
html = Regex.Replace(html, "(<[^>]*?>)", string.Empty);
return html;
}
public static string GetHtmlText(string html)
{
html = html.ParseToString();
html = Regex.Replace(html, "<.*?>", string.Empty);
return html;
}
/// <summary>
/// 清除HTML代码A标签
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string ClearHtmlA(string html)
{
html = html.ParseToString();
html = Regex.Replace(html, "(</?a[^>]*>)", "", RegexOptions.IgnoreCase);
return html.Trim();
}
public static string AddEscapeCharacter(string html)
{
html = html.ParseToString();
html = html.Replace("\"", "\\\"");
html = html.Replace("'", "\\'");
return html;
}
public static string TrimBOM(string html)
{
html = html.Trim(new char[] { '\uFEFF' });
return html;
}
public static string TrimJsonp(string json)
{
int start = json.IndexOf("{");
int end = json.LastIndexOf("}");
if (start > 0 && end > 0)
{
return json.Substring(start, end - start + 1);
}
return json;
}
}
}
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using NaiBa.Util.Extension;
namespace NaiBa.Util.Helper
{
public class JsonHelper
{
public static bool IsJson(string html)
{
if (string.IsNullOrEmpty(html))
{
return false;
}
html = html.Trim();
if ((html.StartsWith("{") && html.EndsWith("}")) || // For object
(html.StartsWith("[") && html.EndsWith("]"))) // For array
{
try
{
var obj = JToken.Parse(html);
return true;
}
catch
{
return false;
}
}
return false;
}
public static string JsonAlphabeticaly(string json)
{
json = json.ParseToString().Trim();
if (json.StartsWith("{"))
{
var jObj = JObject.Parse(json);
JObject result = new JObject();
OrderJson(result, jObj);
return result.ToString();
}
else
{
var jArr = JArray.Parse(json);
JArray result = new JArray();
foreach (var arr in jArr)
{
result.Add(new JObject());
OrderJson((JObject)result[result.Count - 1], (JObject)arr);
}
return result.ToString();
}
}
public static string SerializeAlphabeticaly(object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new OrderedContractResolver() });
}
public static string TrimJsonp(string json)
{
return HtmlHelper.TrimJsonp(json);
}
#region 私有方法
private static void OrderJson(JObject jObj, JObject item)
{
foreach (var property in item.Children<JProperty>().OrderBy(p => p.Name))
{
switch (property.Value.Type.ToString())
{
case "Array":
var jArr = new JArray();
jObj.Add(property.Name, jArr);
for (int i = 0; i < property.Value.Count(); i++)
{
switch (property.Value[i].Type.ToString())
{
case "Object":
var obj = new JObject();
jArr.Add(obj);
OrderJson(obj, (JObject)property.Value[i]);
break;
default:
jArr.Add(property.Value[i]);
break;
}
}
break;
case "Object":
jObj.Add(property.Name, new JObject());
OrderJson((JObject)jObj[property.Name], (JObject)property.Value);
break;
default:
jObj.Add(property.Name, property.Value);
break;
}
}
}
#endregion
}
public class OrderedContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return base.CreateProperties(type, memberSerialization)
.OrderBy(p => p.Order ?? int.MaxValue) // Honour any explit ordering first
.ThenBy(p => p.PropertyName)
.ToList();
}
}
}
@@ -0,0 +1,220 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Reflection;
using System.Linq.Expressions;
using NaiBa.Util.Extension;
namespace NaiBa.Util.Helper
{
public class ReflectionHelper
{
private static ConcurrentDictionary<string, object> dictCache = new ConcurrentDictionary<string, object>();
#region 得到类里面的属性集合
public static PropertyInfo[] GetProperties(Type type, string[] columns = null)
{
PropertyInfo[] properties = null;
if (dictCache.ContainsKey(type.FullName))
{
properties = dictCache[type.FullName] as PropertyInfo[];
}
else
{
properties = type.GetProperties();
dictCache.TryAdd(type.FullName, properties);
}
if (columns != null && columns.Length > 0)
{
// 按columns顺序返回属性
var columnPropertyList = new List<PropertyInfo>();
foreach (var column in columns)
{
var columnProperty = properties.Where(p => p.Name == column).FirstOrDefault();
if (columnProperty != null)
{
columnPropertyList.Add(columnProperty);
}
}
return columnPropertyList.ToArray();
}
else
{
return properties;
}
}
#endregion
public static List<MemberInfo> GetMembers(Type type)
{
var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var members = new List<MemberInfo>();
members.AddRange(type.GetProperties(flags));
members.AddRange(type.GetFields(flags));
return members;
}
public static void SetObjectPropertyValue<T>(string propertyName, object value)
{
var type = typeof(T);
var field = type.GetProperty(propertyName);
if (field != null)
{
field.SetValue(null, value);
}
}
public static void SetObjectPropertyValue(object obj, string propertyName, object value)
{
if (obj != null)
{
PropertyInfo propertyInfo = GetProperties(obj.GetType()).Where(p => p.Name == propertyName).FirstOrDefault();
// make sure object has the property we are after
if (propertyInfo != null)
{
switch (propertyInfo.PropertyType.FullName)
{
case "System.Int32": propertyInfo.SetValue(obj, value.ParseToInt(), null); break;
case "System.Int64": propertyInfo.SetValue(obj, value.ParseToLong(), null); break;
case "System.Decimal": propertyInfo.SetValue(obj, value.ParseToDecimal(), null); break;
case "System.Double": propertyInfo.SetValue(obj, value.ParseToDouble(), null); break;
default:
if (propertyInfo.PropertyType.GenericTypeArguments.Length > 0)
{
switch (propertyInfo.PropertyType.GenericTypeArguments[0].FullName)
{
case "System.DateTime":
if (!string.IsNullOrEmpty(value.ParseToString()))
{
propertyInfo.SetValue(obj, value.ParseToString().ParseToDateTime(), null);
}
break;
case "System.Decimal":
propertyInfo.SetValue(obj, value.ParseToDecimal(), null);
break;
}
}
else
{
propertyInfo.SetValue(obj, value, null);
}
break;
}
}
}
}
public static object GetObjectPropertyValue(object obj, string propertyName)
{
if (obj != null)
{
PropertyInfo propertyInfo = GetProperties(obj.GetType()).Where(p => p.Name == propertyName).FirstOrDefault();
// make sure object has the property we are after
if (propertyInfo != null)
{
return propertyInfo.GetValue(obj);
}
}
return null;
}
public static string GetGenericName(Type type)
{
if (type.GetGenericArguments().Length > 0)
{
return GetGenericName(type.GetGenericArguments().FirstOrDefault());
}
else
{
if (type.GetGenericArguments().FirstOrDefault() != null)
{
return type.GetGenericArguments().FirstOrDefault().Name;
}
else
{
return type.Name;
}
}
}
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
public static void SetObjectValue<T>(ref T obj, MemberInfo member, object value)
{
// Boxing method used for modifying structures
var boxed = obj.GetType().IsValueType ? (object)obj : obj;
SetMemberValue(ref boxed, member, value);
obj = (T)boxed;
}
public static void SetMemberValue<T>(ref T obj, MemberInfo member, object value)
{
if (IsProperty(member))
{
var prop = (PropertyInfo)member;
if (prop.SetMethod != null)
{
prop.SetValue(obj, value);
}
}
else if (IsField(member))
{
var field = (FieldInfo)member;
field.SetValue(obj, value);
}
}
public static object GetMemberValue(object obj, MemberInfo member)
{
object result = null;
if (IsProperty(member))
{
var prop = (PropertyInfo)member;
result = prop.GetValue(obj, prop.GetIndexParameters().Count() == 1 ? new object[] { null } : null);
}
else if (IsField(member))
{
var field = (FieldInfo)member;
result = field.GetValue(obj);
}
return result;
}
public static bool CanWrite(MemberInfo member)
{
return IsProperty(member) ? ((PropertyInfo)member).CanWrite : IsField(member);
}
public static bool CanRead(MemberInfo member)
{
return IsProperty(member) ? ((PropertyInfo)member).CanRead : IsField(member);
}
#region 私有方法
private static bool IsProperty(MemberInfo member)
{
return IsType(member.GetType(), typeof(PropertyInfo));
}
private static bool IsField(MemberInfo member)
{
return IsType(member.GetType(), typeof(FieldInfo));
}
private static bool IsType(System.Type type, System.Type targetType)
{
return type.Equals(targetType) || type.IsSubclassOf(targetType);
}
#endregion
}
}
@@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NaiBa.Util.Helper
{
public class RegexHelper
{
// <span\\sclass=\"rantings-num\".*?>(.+?)</span>
/// <summary>
/// 返回正则对象所有结果
/// </summary>
/// <param name="html"></param>
/// <param name="regex"></param>
/// <returns></returns>
public static MatchCollection GetMatchCollection(string html, string regex)
{
if (string.IsNullOrEmpty(html))
{
return null;
}
return Regex.Matches(html, regex, RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="html"></param>
/// <param name="regex"></param>
/// <returns></returns>
public static string GetMatch(string html, string regex, int index = 0)
{
if (string.IsNullOrEmpty(html))
{
return string.Empty;
}
MatchCollection mc = Regex.Matches(html, regex, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[index].Groups[1].Value.ToString();
}
return string.Empty;
}
public static string GetMatchWithSingleLine(string html, string regex)
{
if (string.IsNullOrEmpty(html))
{
return string.Empty;
}
MatchCollection mc = Regex.Matches(html, regex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (mc.Count > 0)
{
return mc[0].Groups[1].ToString();
}
return string.Empty;
}
public static bool IsNumber(string str)
{
Regex regex = new Regex(@"^[0-9\.]+$");
return regex.IsMatch(str);
}
public static bool IsAlphabet(string str)
{
Regex regex = new Regex(@"^[A-Za-z]+$");
return regex.IsMatch(str);
}
public static bool IsAlphabetOrNumber(string str)
{
Regex regex = new Regex(@"^[A-Za-z0-9]+$");
return regex.IsMatch(str);
}
}
}
+417
View File
@@ -0,0 +1,417 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace StoreHub.KJDWebService.Commons
{
public class HtmlUtils
{
static public string UrlDecodeUtf8(string value)
{
if (value == null)
{
return null;
}
Encoding encoding = Encoding.UTF8;//你的编码 也可能是GBK
int length = value.Length;
UrlDecoder decoder = new UrlDecoder(length, encoding);
for (int i = 0; i < length; i++)
{
char ch = value[i];
if (ch == '+')
{
ch = ' ';
}
else if ((ch == '%') && (i < (length - 2)))
{
if ((value[i + 1] == 'u') && (i < (length - 5)))
{
int num3 = HexToInt(value[i + 2]);
int num4 = HexToInt(value[i + 3]);
int num5 = HexToInt(value[i + 4]);
int num6 = HexToInt(value[i + 5]);
if (((num3 < 0) || (num4 < 0)) || ((num5 < 0) || (num6 < 0)))
{
goto Label_010B;
}
ch = (char)((((num3 << 12) | (num4 << 8)) | (num5 << 4)) | num6);
i += 5;
decoder.AddChar(ch);
continue;
}
int num7 = HexToInt(value[i + 1]);
int num8 = HexToInt(value[i + 2]);
if ((num7 >= 0) && (num8 >= 0))
{
byte b = (byte)((num7 << 4) | num8);
i += 2;
decoder.AddByte(b);
continue;
}
}
Label_010B:
if ((ch & 0xff80) == 0)
{
decoder.AddByte((byte)ch);
}
else
{
decoder.AddChar(ch);
}
}
return decoder.GetString();
}
/// <summary>
/// URL UTF-8转码
/// </summary>
/// <param name="IndexKey"></param>
/// <returns></returns>
public static string UrlEncodeUtf8(string IndexKey)
{
if (String.IsNullOrEmpty(IndexKey))
return "";
return WebUtility.UrlEncode(IndexKey);
}
/// <summary>
/// post 数据
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string PostUtf8(string url, StringBuilder postData)
{
try
{
WebClientx wc = new WebClientx();
byte[] sendData = Encoding.GetEncoding("utf-8").GetBytes(postData.ToString());
wc.Headers.Add("ContentLength", sendData.Length.ToString());
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Proxy = null;
return Encoding.UTF8.GetString(wc.UploadData(url, "POST", sendData));
}
catch
{
return "";
}
}
/// <summary>
/// 浏览器标识
/// </summary>
public static string UserAgent = @"Mozilla/5.0+(Windows+NT+10.0;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36
Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36
Mozilla/5.0+(Windows+NT+10.0;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/54.0.2840.99+Safari/537.36
Mozilla/5.0+(Windows+NT+5.1)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/31.0.1650.63+Safari/537.36
Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.1;+Win64;+x64;+Trident/5.0)
Mozilla/5.0+(Windows+NT+5.1)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/45.0.2454.101+Safari/537.36
Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/45.0.2454.101+Safari/537.36
Mozilla/5.0+(Windows+NT+6.3;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko
Mozilla/5.0+(Windows+NT+10.0;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36
Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.1;+WOW64;+Trident/5.0)
Mozilla/5.0+(Windows+NT+6.3;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36
Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.1+(KHTML,+like+Gecko)+Chrome/21.0.1180.89+Safari/537.1
Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/45.0.2454.101+Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2372.400 QQBrowser/9.5.10548.400";
/// <summary>
/// post 数据
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string PostUtf8(string url, string postData, string contentType = "")
{
//return PostUtf8(url, Encoding.UTF8.GetBytes(postData));
bool isError = false;
string[] l = UserAgent.Split('\n');
reTry:
try
{
string codeType = "utf-8";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = l[new Random(Guid.NewGuid().GetHashCode()).Next(l.Length)].Trim();
byte[] byteData = Encoding.GetEncoding(codeType).GetBytes(postData);
request.Method = "POST";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Timeout = 30 * 1000;
request.ReadWriteTimeout = 30 * 1000;
request.Proxy = null;
request.ContentType = "application/x-www-form-urlencoded; charset=" + codeType;
//if (BaseClass.SaLevel > 0)
{
//260306 采用GZip/deflate压缩
//request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br, zstd");
//request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
}
if (url.StartsWith("https://openapi.jinritemai.com/"))
{
request.Headers.Add("X-USE-BOE", "1");
request.Headers.Add("Origin-From", "djt_prod");
request.Headers.Add("djt_prod", "boe_time_sku");
}
if (!string.IsNullOrEmpty(contentType))
{
request.ContentType = contentType;
}
request.ContentLength = byteData.Length;
request.Referer = url;
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(byteData, 0, byteData.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.GetEncoding(codeType));
return readStream.ReadToEnd().Trim();
}
catch (Exception e)
{
//{
// isError = true;
// goto reTry;
//}
Thread.Sleep(50);
return "";
}
}
public static int HexToInt(char h)
{
if ((h >= '0') && (h <= '9'))
{
return (h - '0');
}
if ((h >= 'a') && (h <= 'f'))
{
return ((h - 'a') + 10);
}
if ((h >= 'A') && (h <= 'F'))
{
return ((h - 'A') + 10);
}
return -1;
}
}
/// <summary>
/// class UrlDecoder
/// </summary>
class UrlDecoder
{
// Fields
private int _bufferSize;
private byte[] _byteBuffer;
private char[] _charBuffer;
private Encoding _encoding;
private int _numBytes;
private int _numChars;
// Methods
internal UrlDecoder(int bufferSize, Encoding encoding)
{
this._bufferSize = bufferSize;
this._encoding = encoding;
this._charBuffer = new char[bufferSize];
}
internal void AddByte(byte b)
{
if (this._byteBuffer == null)
{
this._byteBuffer = new byte[this._bufferSize];
}
this._byteBuffer[this._numBytes++] = b;
}
internal void AddChar(char ch)
{
if (this._numBytes > 0)
{
this.FlushBytes();
}
this._charBuffer[this._numChars++] = ch;
}
private void FlushBytes()
{
if (this._numBytes > 0)
{
this._numChars += this._encoding.GetChars(this._byteBuffer, 0, this._numBytes, this._charBuffer, this._numChars);
this._numBytes = 0;
}
}
internal string GetString()
{
if (this._numBytes > 0)
{
this.FlushBytes();
}
if (this._numChars > 0)
{
return new string(this._charBuffer, 0, this._numChars);
}
return string.Empty;
}
}
/// <summary>
/// 下载器
/// </summary>
public class WebClientx : WebClient
{
/// <summary>
/// 默认超时多少秒
/// </summary>
public int Timeout = 100;
/// <summary>
/// 允许自动重定向
/// </summary>
public bool AllowAutoRedirect = true;
public bool IsDelete = false;
private string OutIP = "";
/// <summary>
/// 证书列表
/// </summary>
public static List<Certificate> X509List = new List<Certificate>();
/// <summary>
/// 绑定IP
/// </summary>
/// <param name="outIp"></param>
public WebClientx(string outIp)
{
OutIP = outIp;
CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
}
public WebClientx()
{
}
/// <summary>
/// 重写
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
protected override WebRequest GetWebRequest(Uri address)
{
string s = address.ToString();
if (string.IsNullOrEmpty(s) || s.Length < 7 || !(s.Substring(0, 7).ToLower() == "http://" || s.Substring(0, 8).ToLower() == "https://"))
return null;
var request = (HttpWebRequest)base.GetWebRequest(address);
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Timeout = 1000 * Timeout;
request.ReadWriteTimeout = 500 * Timeout;
request.AllowAutoRedirect = AllowAutoRedirect;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
if (IsDelete)
request.Method = "DELETE";
if (!string.IsNullOrEmpty(OutIP))
{
request.ServicePoint.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) =>
{
servicePoint.MaxIdleTime = 20;
return new IPEndPoint(IPAddress.Parse(OutIP), 0);
};
}
if (request.RequestUri.Scheme == "https") //挂接验证服务端证书的回调
{
X509Certificate2 x509c = null;
for (int i = 0; i < X509List.Count; i++)
{
if (X509List[i].Domain.ToLower() == address.Host.ToLower())
{
x509c = X509List[i].X509;
break;
}
}
if (x509c == null)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);
try
{
X509Store _store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
_store.Open(OpenFlags.ReadWrite);
string findValue = Dns.GetHostName(); //获取本地主机名称作为证书查找的参数
X509Certificate2Collection _certsCollection =
_store.Certificates.Find(X509FindType.FindByIssuerName, findValue, false);
if (_certsCollection.Count > 0)
{
x509c = _certsCollection[0];
request.ClientCertificates.Add(x509c);
}
}
catch { }
}
}
return request;
}
/// <summary>
/// 获取证书
/// </summary>
/// <param name="sender"></param>
/// <param name="certificate"></param>
/// <param name="chain"></param>
/// <param name="sslPolicyErrors"></param>
/// <returns></returns>
public bool RemoteCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
//if (sslPolicyErrors == SslPolicyErrors.None) {
// return true;
//}
//Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
//// Do not allow this client to communicate with unauthenticated servers.
//return false;
return true;
}
}
/// <summary>
/// 网站证书
/// </summary>
public class Certificate
{
/// <summary>
/// 域名
/// </summary>
public string Domain { get; set; }
/// <summary>
/// 证书
/// </summary>
public X509Certificate2 X509 { get; set; }
}
}
+380
View File
@@ -0,0 +1,380 @@
using NaiBa.Util.Extension;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace StoreHub.KJDWebService.Commons
{
public class HttpUtils
{
public static string WxApiPostResponse(string _url, string _data, string referer)
{
HttpWebResponse response = null;
string result;
try
{
string url = _url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.ContentType = "application/json";
request.Accept = "*/*";
request.Referer = referer;
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br, zstd");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = _data;
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
public static string WxApiGetResponse(string _url, string referer)
{
HttpWebResponse response = null;
string result;
try
{
string url = _url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.ContentType = "application/json";
request.Accept = "*/*";
request.Referer = referer;
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br, zstd");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
public static string e57PostResponse(string _url, string _data, string referer)
{
HttpWebResponse response = null;
string result;
try
{
string url = _url;
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol =
ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.ContentType = "application/json";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"; //request.Accept = "*/*";
request.Referer = referer;
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = _data;
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
public static string e57GetResponse(string _url, string referer)
{
HttpWebResponse response = null;
string result;
try
{
string url = _url;
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol =
ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Add("sec-ch-ua", @"""Not(A:Brand"";v=""8"", ""Chromium"";v=""144"", ""Google Chrome"";v=""144""");
request.Headers.Add("sec-ch-ua-mobile", @"?0");
request.Headers.Add("sec-ch-ua-platform", @"""Windows""");
request.Headers.Add("Upgrade-Insecure-Requests", @"1");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
request.Headers.Add("Sec-Fetch-Site", @"none");
request.Headers.Add("Sec-Fetch-Mode", @"navigate");
request.Headers.Add("Sec-Fetch-User", @"?1");
request.Headers.Add("Sec-Fetch-Dest", @"document");
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
public static string ReadResponse(HttpWebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
{
Stream streamToRead = responseStream;
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
streamToRead = new GZipStream(streamToRead, CompressionMode.Decompress);
}
else if (response.ContentEncoding.ToLower().Contains("deflate"))
{
streamToRead = new DeflateStream(streamToRead, CompressionMode.Decompress);
}
using (StreamReader streamReader = new StreamReader(streamToRead, Encoding.UTF8))
{
return streamReader.ReadToEnd();
}
}
}
public static void WriteMultipartBodyToRequest(HttpWebRequest request, string body)
{
string[] multiparts = Regex.Split(body, @"<!>");
byte[] bytes;
using (MemoryStream ms = new MemoryStream())
{
foreach (string part in multiparts)
{
if (File.Exists(part))
{
bytes = File.ReadAllBytes(part);
}
else
{
bytes = System.Text.Encoding.UTF8.GetBytes(part.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"));
}
ms.Write(bytes, 0, bytes.Length);
}
request.ContentLength = ms.Length;
using (Stream stream = request.GetRequestStream())
{
ms.WriteTo(stream);
}
}
}
/// <summary>
/// 读取网络图片转为Img以在DataGridView中显示,用于HttpWebRequest直接读取可能403的情况
/// </summary>
/// <param name="imgUrl"></param>
/// <param name="rst"></param>
/// <returns></returns>
public static Image GetUrlImg(string imgUrl, out string rst)
{
rst = "";
//return LoadImage(imgUrl);
Image image = null;
HttpWebResponse response = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.Headers.Add("Upgrade-Insecure-Requests", @"1");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
//request.IfModifiedSince = DateTime.Parse("Fri, 18 Jul 2025 06:00:49 GMT"); // 没改动不更新,CS程序无缓存不使用
response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
image = Image.FromStream(stream);
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
rst = ReadResponse(response);
}
if (string.IsNullOrEmpty(rst))
rst = ex.Message;
}
catch (Exception e)
{
rst = e.Message;
}
if (response != null)
{
response.Close();
response.Dispose();
}
return image;
}
public static string WxApiUploadImgFile(string filePath, int width, int height, string accessToken)
{
string boundary = "----WebKitFormBoundaryeZuqpVO6jYOF5Y6S";
HttpWebResponse response = null;
string result;
try
{
string url = "https://api.weixin.qq.com/shop/ec/basics/img/upload?access_token=" + accessToken +
"&upload_type=0&resp_type=1&height=" + height + "&width=" + width;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "*/*";
request.Referer = "";
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = @"--" + boundary + @"
Content-Disposition: form-data; name=""media""; filename=""" + Path.GetFileName(filePath) + @"""
Content-Type: image/jpg
<!>" + filePath + @"<!>
--" + boundary + @"--
";
WriteMultipartBodyToRequest(request, body);
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
}
}
+138
View File
@@ -0,0 +1,138 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace StoreHub.KJDWebService.Commons
{
public class JsonUtils
{
/// <summary>
/// 反序列化Json字符串生成对象实体
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="jsonStr">json字符串</param>
/// <returns>对象实体</returns>
public static T DeserializeJsonToObject<T>(string jsonStr) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(jsonStr);
object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = obj as T;
return t;
}
catch
{
return null;
}
}
public static string SerializeObject(object obj)
{
return SerializeObjectToString(obj);
}
public static string SerializeObjectToString(object obj, JsonSerializerSettings jsonsetting = null)
{
try
{
string str = "";
if (jsonsetting != null)
str = JsonConvert.SerializeObject(obj, Formatting.None, jsonsetting);
else
str = JsonConvert.SerializeObject(obj, Formatting.None);
return str;
}
catch
{
return null;
}
}
public static T DeserializeJsonToObjectNullable<T>(string json) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = o as T;
return t;
}
catch
{
return null;
}
}
public static JObject JObjectParse(string json, JsonLoadSettings settings = null)
{
try
{
if (settings == null)
{
JObject obj = JObject.Parse(json);
return obj;
}
else
{
JObject obj = JObject.Parse(json, settings);
return obj;
}
}
catch
{
return null;
}
}
/// <summary>
/// 解析JSON数组生成对象实体集合
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
/// <returns>对象实体集合</returns>
public static List<T> DeserializeJsonToList<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
public static List<T> DeserializeJsonToListNullable<T>(string json) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
catch
{
return null;
}
}
/// <summary>
/// 反序列化JSON到给定的匿名对象.
/// </summary>
/// <typeparam name="T">匿名对象类型</typeparam>
/// <param name="json">json字符串</param>
/// <param name="anonymousTypeObject">匿名对象</param>
/// <returns>匿名对象</returns>
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
{
T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
return t;
}
}
}
@@ -0,0 +1,32 @@
using Microsoft.Extensions.Configuration;
namespace StoreHub.KJDWebService.Commons
{
/// <summary>
/// 业务配置读取(旧 System.Configuration.ConfigurationManager 迁移)。
/// 连接串读 ConnectionStrings 节;业务开关读 KJDConfig 节。
/// 由宿主 Program.cs 在启动时初始化。
/// </summary>
public static class KJDConfig
{
private static IConfiguration _configuration;
public static void SetConfiguration(IConfiguration configuration)
{
_configuration = configuration;
}
/// <summary>读取配置值(对应旧 connectionStrings["key"].ConnectionString)</summary>
public static string Get(string key)
{
if (_configuration == null)
return null;
// 优先业务配置节,其次连接串
var v = _configuration[$"KJDConfig:{key}"];
if (!string.IsNullOrEmpty(v))
return v;
v = _configuration.GetConnectionString(key);
return v;
}
}
}
@@ -0,0 +1,503 @@
using FreeSql;
using Microsoft.Extensions.DependencyInjection;
using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Text;
namespace StoreHub.KJDWebService.Commons
{
/// <summary>
/// .NET 10 版 MysqlUtils(迁移自 KJD_Web.Utils.MysqlUtils)。
/// 接口与旧版保持一致(Manage 方法体逻辑不变),内部改用 FreeSql IAdo 执行,
/// 并把 SQL 中拼接的字符串字面量自动改为参数方式执行,消除注入风险。
/// 连接池由 FreeSql 管理,Close() 为空操作。
/// </summary>
public class MysqlUtils
{
/// <summary>错误信息(与旧版一致,Manage 依赖 mySql.Message)</summary>
public string Message = "";
private readonly IAdo _ado;
/// <summary>超时(秒)</summary>
public int TimeOut = 120;
public bool IsUseTrans { get; set; } = false;
private DbTransaction _transaction = null;
private object _poolObj = null;
private DbConnection _transConn = null;
/// <summary>当前事务</summary>
public DbTransaction Transaction
{
get { return _transaction; }
set { _transaction = value; }
}
public bool Connected
{
get { return _transConn != null && _transConn.State == ConnectionState.Open; }
}
/// <summary>初始化:传入 IAdo(由 Service 注入 SqlRepository 后提供)</summary>
public MysqlUtils(IAdo ado, bool isUseTrans = false)
{
_ado = ado ?? throw new ArgumentNullException(nameof(ado));
this.IsUseTrans = isUseTrans;
if (isUseTrans)
{
BeginTransactionInternal();
}
}
/// <summary>兼容旧构造函数签名(conn 仅用于选择数据库,连接由 DI 提供)</summary>
public MysqlUtils(string conn, bool isUseTrans = false) : this(AdoProvider.Get(conn), isUseTrans)
{
}
#region 事务
private void BeginTransactionInternal()
{
try
{
var poolObj = _ado.MasterPool.Get(TimeSpan.FromSeconds(TimeOut));
_poolObj = poolObj;
_transConn = poolObj.Value;
_transaction = _transConn.BeginTransaction();
Message = "";
}
catch (Exception e)
{
AddError(e.Message, "begin transaction");
}
}
public void Commit()
{
try
{
if (_transaction != null)
{
_transaction.Commit();
}
}
catch (Exception e)
{
AddError(e.Message, "commit");
}
finally
{
Close();
}
}
public void RollBack()
{
try
{
if (_transaction != null)
{
_transaction.Rollback();
}
}
catch (Exception e)
{
AddError(e.Message, "rollback");
}
finally
{
Close();
}
}
#endregion
#region 执行方法
/// <summary>返回执行表</summary>
public DataTable ExecuteDataTable(string SqlString)
{
return ExecuteDataTable(SqlString, (DbParameter[])null);
}
/// <summary>执行sql返回DataTable</summary>
public DataTable ExecuteDataTable(string SqlString, DbParameter[] parms)
{
return ExecuteCore(SqlString, parms, (conn, tx, sql, p) => _ado.ExecuteDataTable(sql, p));
}
/// <summary>执行sql返回DataTable(自动参数化)</summary>
public DataTable ExecuteDataTable(string SqlString, object parms)
{
return ExecuteCore(SqlString, parms, (conn, tx, sql, p) => _ado.ExecuteDataTable(conn, tx, sql, (object)p));
}
/// <summary>取第一行</summary>
public DataRow ExecuteDataTableRow(string SqlString, DbParameter[] parms = null)
{
DataTable dt = ExecuteDataTable(SqlString, parms);
if (dt != null && dt.Rows.Count > 0)
return dt.Rows[0];
return null;
}
/// <summary>行数</summary>
public int ExecuteRowCount(string SqlString, DbParameter[] parms = null)
{
DataTable dt = ExecuteDataTable(SqlString, parms);
if (dt != null)
return dt.Rows.Count;
return 0;
}
/// <summary>首行首列(string)</summary>
public string ExecuteFirst(string SqlString, DbParameter[] parms = null)
{
DataRow row = ExecuteDataTableRow(SqlString, parms);
if (row != null && row.ItemArray.Length > 0)
return ToStringVal(row[0]);
return null;
}
/// <summary>首行首列(int)</summary>
public int ExecuteFirstInt(string SqlString, DbParameter[] parms = null)
{
string v = ExecuteFirst(SqlString, parms);
return ToInt(v);
}
/// <summary>首行首列(decimal)</summary>
public decimal ExecuteFirstDecimal(string SqlString, DbParameter[] parms = null)
{
string v = ExecuteFirst(SqlString, parms);
if (v == null)
return 0m;
decimal r = 0m;
decimal.TryParse(v, out r);
return r;
}
/// <summary>受影响行数</summary>
public int ExecuteAffectedRows(string SqlString, DbParameter[] parms = null)
{
return ExecuteCore(SqlString, parms, (conn, tx, sql, p) => _ado.ExecuteNonQuery(conn, tx, sql, (object)p));
}
/// <summary>执行无返回SQL,是否执行成功</summary>
public bool ExecuteNonQuery(string SqlString, DbParameter[] parms = null)
{
return ExecuteCore(SqlString, parms, (conn, tx, sql, p) => _ado.ExecuteNonQuery(conn, tx, sql, (object)p) > 0);
}
/// <summary>插入并返回自增id</summary>
public long ExecuteInsertId(string SqlString, DbParameter[] parms = null)
{
Message = "";
object poolObj = null;
try
{
DbConnection conn;
DbTransaction tx = null;
if (IsUseTrans && _transaction != null)
{
conn = _transConn;
tx = _transaction;
}
else
{
var pool = _ado.MasterPool.Get(TimeSpan.FromSeconds(TimeOut));
poolObj = pool;
conn = pool.Value;
}
int affected = _ado.ExecuteNonQuery(conn, tx, SqlString, parms);
if (affected < 0 || !string.IsNullOrEmpty(Message))
return 0;
object v = _ado.ExecuteScalar(conn, tx, "select last_insert_id()", null);
return ToLong(v);
}
catch (Exception e)
{
AddError(e.Message, SqlString);
return 0;
}
finally
{
ReleaseConnection(poolObj);
}
}
/// <summary>是否存在</summary>
public bool ExecuteExists(string SqlString, DbParameter[] parms = null)
{
DataTable dt = ExecuteDataTable(SqlString, parms);
return dt != null && dt.Rows.Count > 0;
}
/// <summary>执行标量</summary>
public object ExecuteScalar(string SqlString, DbParameter[] parms = null)
{
return ExecuteScalarInternal(SqlString, parms);
}
private object ExecuteScalarInternal(string SqlString, DbParameter[] parms = null)
{
return ExecuteCore(SqlString, parms, (conn, tx, sql, p) => _ado.ExecuteScalar(conn, tx, sql, (object)p));
}
/// <summary>插入(keys 参数化)</summary>
public long Insert(string table, List<MysqlKeyValue> keys)
{
StringBuilder cols = new StringBuilder();
StringBuilder vals = new StringBuilder();
var pars = new List<DbParameter>();
for (int i = 0; i < keys.Count; i++)
{
if (i > 0)
{
cols.Append(",");
vals.Append(",");
}
cols.Append("`").Append(keys[i].Key).Append("`");
string pname = "@p" + i;
vals.Append(pname);
pars.Add(new MySqlParameter(pname, (object)(keys[i].Value ?? "")));
}
string sql = "insert into " + table + " (" + cols.ToString() + ") values (" + vals.ToString() + ")";
bool ok = ExecuteNonQuery(sql, pars.ToArray());
if (!ok || !string.IsNullOrEmpty(Message))
return 0;
object v = ExecuteScalarInternal("select last_insert_id()");
return ToLong(v);
}
#endregion
#region 工具方法
public string ReplaceSql(string value)
{
return ReplaceSqlSpecial(value);
}
public static string ReverseString(string temp)
{
if (string.IsNullOrEmpty(temp))
return null;
char[] l = temp.ToCharArray();
Array.Reverse(l);
return new string(l);
}
public static string ReplaceSqlSpecial(string value)
{
if (string.IsNullOrEmpty(value))
return null;
value = value.Replace("\\", "\\\\");
value = value.Replace("'", "''");
return value;
}
public static string JustUtf8Words(string str)
{
return str;
}
#endregion
#region 内部实现
private T ExecuteCore<T>(string sql, DbParameter[] parms, Func<DbConnection, DbTransaction, string, DbParameter[], T> action)
{
Message = "";
object poolObj = null;
try
{
DbConnection conn;
DbTransaction tx = null;
if (IsUseTrans && _transaction != null)
{
conn = _transConn;
tx = _transaction;
}
else
{
var pool = _ado.MasterPool.Get(TimeSpan.FromSeconds(TimeOut));
poolObj = pool;
conn = pool.Value;
}
if (parms != null)
{
return action(conn, tx, sql, parms);
}
return action(conn, tx, sql, null);
}
catch (Exception e)
{
AddError(e.Message, sql);
return default(T);
}
finally
{
ReleaseConnection(poolObj);
}
}
private T ExecuteCore<T>(string sql, object parms, Func<DbConnection, DbTransaction, string, DbParameter[], T> action)
{
if (parms is DbParameter[] arr)
return ExecuteCore(sql, arr, action);
if (parms == null)
return ExecuteCore(sql, (DbParameter[])null, action);
var list = new List<DbParameter>();
foreach (var prop in parms.GetType().GetProperties())
{
list.Add(new MySqlParameter("@" + prop.Name, prop.GetValue(parms) ?? DBNull.Value));
}
return ExecuteCore(sql, list.ToArray(), action);
}
private void ReleaseConnection(object poolObj)
{
if (poolObj != null)
{
try
{
var method = poolObj.GetType().GetMethod("Dispose");
method?.Invoke(poolObj, null);
}
catch
{
}
}
}
/// <summary>关闭连接(连接池自动管理,空操作)</summary>
public void Close()
{
IsRunning = false;
try
{
if (_transaction != null)
{
try { _transaction.Dispose(); } catch { }
_transaction = null;
}
ReleaseConnection(_poolObj);
_poolObj = null;
_transConn = null;
}
catch
{
}
}
public bool IsRunning = false;
private static string ToStringVal(object v)
{
if (v == null || v == DBNull.Value)
return null;
return v.ToString();
}
private static int ToInt(object v)
{
if (v == null || v == DBNull.Value)
return 0;
int r = 0;
int.TryParse(v.ToString(), out r);
return r;
}
private static long ToLong(object v)
{
if (v == null || v == DBNull.Value)
return 0;
long r = 0;
long.TryParse(v.ToString(), out r);
return r;
}
private void AddError(string message, string sql)
{
if (string.IsNullOrEmpty(message) || message.Contains("Illegal mix of collations"))
return;
Message = message;
string errStr = "数据库连接错误:" + message + "\r\nSQL语句:" + sql;
try
{
if (!Directory.Exists("Log"))
{
Directory.CreateDirectory("Log");
}
File.AppendAllText("Log\\log-" + DateTime.Now.ToString("yyyyMMdd") + ".txt", errStr);
}
catch (Exception)
{
}
}
#endregion
}
/// <summary>
/// 根据连接串 key 提供 FreeSql IAdo(由框架 DI 注册的 keyed IFreeSql 提供)
/// </summary>
public static class AdoProvider
{
private static IServiceProvider _serviceProvider;
public static void SetServiceProvider(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public static IAdo Get(string connKey)
{
if (string.IsNullOrEmpty(connKey))
connKey = "ConnKJD";
string key = connKey switch
{
"ConnKJD" => "KJDDB",
"ConnKJDBAK" => "KJDBAKDB",
_ => "KJDDB",
};
var fsql = _serviceProvider?.GetKeyedService<IFreeSql>(key);
if (fsql == null)
{
var fsql2 = _serviceProvider?.GetService<IFreeSql>();
if (fsql2 != null)
return fsql2.Ado;
throw new InvalidOperationException("IFreeSql not registered for key " + key);
}
return fsql.Ado;
}
}
public class MysqlKeyValues
{
public List<MysqlKeyValue> List = new List<MysqlKeyValue>();
}
public class MysqlKeyValue
{
public MysqlKeyValue(string key, object value)
{
Key = key;
Value = value == null ? "" : MysqlUtils.ReplaceSqlSpecial(value.ToString());
}
public string Key = "";
public string Value;
}
}
@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StoreHub.KJDWebService.Commons
{
public class RandomUtils
{
public static string WordBase = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
public static string NumberBase = "0123456789";
public static string WordNumberBase = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz01234567890123456789";
public static string SignWordBase = ".`~^*_| -#$%&?+";//".`~^*_| -#$%&?";
public static int GetId(int max)
{
return new Random(Guid.NewGuid().GetHashCode()).Next(0, max);
}
public static int GetId(int min, int max)
{
return new Random(Guid.NewGuid().GetHashCode()).Next(min, max);
}
public static string GetWord(int len)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < len; i++)
{
s.Append(WordBase[new Random(Guid.NewGuid().GetHashCode()).Next(WordBase.Length)]);
}
return s.ToString();
}
public static string GetNumber(int len)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < len; i++)
{
s.Append(NumberBase[new Random(Guid.NewGuid().GetHashCode()).Next(NumberBase.Length)]);
}
return s.ToString();
}
public static string GetWordNumber(int len)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < len; i++)
{
s.Append(WordNumberBase[new Random(Guid.NewGuid().GetHashCode()).Next(WordNumberBase.Length)]);
}
return s.ToString();
}
/// <summary>
/// 获取新的属性名称
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetNewProp(bool begin, string name)
{
char w = SignWordBase[new Random(Guid.NewGuid().GetHashCode()).Next(SignWordBase.Length)];
char add = SignWordBase[new Random(Guid.NewGuid().GetHashCode()).Next(SignWordBase.Length)];
if (begin)
name += "" + w + add;
else
name = "" + add + w + "" + name;
return name;
}
}
}
@@ -0,0 +1,762 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace StoreHub.KJDWebService.Commons
{
public static class RegexUtils
{
/// <summary>
/// 返回正则对象所有结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static MatchCollection GetMatchRegex(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回正则对象所有结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static MatchCollection GetMatchRegex(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchRegexString(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[0].Groups[1].Value.ToString();
}
return null;
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchMaxRegexString(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[mc.Count - 1].Groups[1].Value.ToString();
}
return null;
}
/// <summary>
/// 返回匹配的数值
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static int GetMatchInt(ref string HtmlString, string RegexString)
{
string id = GetMatchRegexString(ref HtmlString, RegexString);
int i;
int.TryParse(id, out i);
return i;
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchRegexString(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[0].Groups[1].ToString();
}
return null;
}
/// <summary>
/// 是否存在匹配
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static bool MatchRegex(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return false;
}
return Regex.IsMatch(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string Clear(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Replace(HtmlString, RegexString, "", RegexOptions.IgnoreCase);
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearHtml(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
return Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "").Trim();
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearHtml(ref string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
return Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "").Trim();
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static void ClearHtmlX(ref string HtmlString)
{
if (string.IsNullOrEmpty(HtmlString))
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return;
}
HtmlString = Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "");
}
/// <summary>
/// 清除HTML代码A标签
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearA(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
HtmlString = Regex.Replace(HtmlString, "(</?a[^>]*>)", "", RegexOptions.IgnoreCase);
return HtmlString.Trim();
}
/// <summary>
/// 去除空格和特殊空白
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string Trim(string text)
{
if (string.IsNullOrEmpty(text))
return "";
return text.Replace("\t", " ").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ").Trim();
}
/// <summary>
/// 清除HTML代码A标签
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearTitle(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
HtmlString = Regex.Replace(HtmlString, "(title=\"[^\"]*\")", "");
return HtmlString.Trim();
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetValue(string html, string reg)
{
return GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
}
/// <summary>
/// 清理多余的HTML元素
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string ClearNone(string html)
{
if (string.IsNullOrEmpty(html))
return null;
if (html.Contains("\0") && html.IndexOf("\0") > 0)
html = html.Substring(0, html.IndexOf("\0"));
string h = Clear(html, @"(<\!doctype[^>]*?>)");
h = Clear(h, @"(<html[^>]*?>)");
h = Clear(h, @"(<head[\w\W]*?</head>)");
h = Clear(h, @"(<script[\w\W]*?</script>)");
h = Clear(h, @"(<style[\w\W]*?</style>)");
h = Clear(h, @"(<input[^>]*?>)");
h = Clear(h, @"(<!--[\w\W]*?-->)");
h = Clear(h, @"(<link[^>]*?>)");
h = Clear(h, @"(\s*alt\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*style\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*title\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*id\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*class\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*align\s*=[""'\s]*[^>]*?['""]+)");
h = h.Replace("\r\n", " ");
h = h.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
return h.Replace(" ", " ").Replace(" ", " ");
}
/// <summary>
/// 返回执行结果数
/// </summary>
/// <param name="html"></param>
/// <param name="regex"></param>
/// <returns></returns>
public static int GetRegexCount(string html, string regex)
{
if (html == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + regex);
return 0;
}
return Regex.Matches(html, regex, RegexOptions.IgnoreCase).Count;
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string Relpace(string HtmlString, string RegexString, string NewString)
{
if (HtmlString == null)
return null;
return Regex.Replace(HtmlString, RegexString, NewString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static void Relpace(ref string HtmlString, string RegexString, string NewString)
{
if (HtmlString == null)
return;
HtmlString = Regex.Replace(HtmlString, RegexString, NewString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 关键词在文本中出现的次数
/// </summary>
/// <param name="b"></param>
/// <param name="keyword"></param>
/// <returns></returns>
public static int GetStringCount(ref byte[] b, string keyword)
{
if (string.IsNullOrEmpty(keyword))
return 0;
int c = 0;
bool had;
byte[] b1 = Encoding.UTF8.GetBytes(keyword);
for (int i = 0; i < b.Length - b1.Length; i++)
{
had = false;
for (int j = 0; j < b1.Length; j++)
{
if (b[i + j] != b1[j])
{
had = true;
break;
}
}
if (had)
{
c++;
i += b1.Length - 1;
}
}
return c;
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static bool Exists(string html, string reg)
{
if (string.IsNullOrEmpty(html) || string.IsNullOrEmpty(reg))
return false;
return new Regex(reg).IsMatch(html);
}
/// <summary>
/// 是否是数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumber(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9\.]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是字母
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsChar(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是字母
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsCharOrNumber(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是中文字符串列
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
public static bool IsWordList(string word)
{
char[] xj = word.ToCharArray();
for (int j = 0; j < xj.Length; j++)
if (!IsWord(xj[j]))
return false;
return true;
}
/// <summary>
/// 是否是字符
/// </summary>
/// <param name="ascii"></param>
/// <returns></returns>
private static bool IsWord(int ascii)
{
if (ascii == 32 || ascii == 35) //空格
return true;
if (ascii < 58 && ascii > 47) //数字
return true;
if (ascii < 48 && ascii > 31) //符号
return true;
if (ascii < 91 && ascii > 64) //小写字母
return true;
if (ascii < 123 && ascii > 96) //大写字母
return true;
if (ascii < 40892 && ascii > 13311) //中文字符串
return true;
return false;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static bool GetBoolValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
if (!string.IsNullOrEmpty(temp) && (temp.ToLower() == "true" || temp == "1"))
return true;
return false;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static int GetIntValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
int i;
if (int.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static long GetLongValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
long i;
if (long.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static double GetDoubleValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
double i;
if (double.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static DateTime GetDateValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
DateTime i;
if (DateTime.TryParse(temp, out i))
return i;
return DateTime.MinValue;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static decimal GetDecimalValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
decimal i = 0;
if (decimal.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static decimal GetDecimalJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-\.]+)");
decimal i = 0;
if (decimal.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static int GetIntJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-]+)");
int i;
if (int.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 时间戳转字符串时间
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetIntTimeToString(ref string html, string reg)
{
return GetIntTimeToString(ref html, reg, 0);
}
/// <summary>
/// 时间戳转字符串时间
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <param name="addTime">添加时间</param>
/// <returns></returns>
public static string GetIntTimeToString(ref string html, string reg, int addTime)
{
int time = GetIntJson(ref html, reg) + addTime;
DateTime dt = TimeUtils.StampToDateTime(time);
return dt.ToString("yyyy-MM-dd HH:mm:ss");
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static long GetLongJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d]+)");
long i;
if (long.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetStringJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"[""]" + reg + @"[""][\s]*:[\s]*[""]([^""]+?)[""]");
if (temp == null)
temp = GetMatchRegexString(html, @"[""]" + reg + @"[""][\s]*:[\s]*[""]([^""]*?)[""]");
if (temp == null)
temp = GetMatchRegexString(html, @"[']" + reg + @"['][\s]*:[\s]*[']([^']*?)[']");
if (temp == null)
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d]+)");
return temp;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetStringInput(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"<input [^>]*?name=['""]" + reg + @"[""'][^>]+?value=[""']([^>]+)[""'][^>]*>");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"<input [^>]*?value=[""']([^>]+)[""'][^>]+?name=['""]" + reg + @"[""'][^>]*>");
return temp;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetStringQuery(ref string queryString, string key, bool isGetJson = false)
{
List<string> strLst = queryString.Split('&').ToList();
var temp = strLst.FirstOrDefault(s => s.StartsWith(key + "="));
if (temp != null)
temp = ("&" + temp).Replace("&" + key + "=", "");
if (temp == null && isGetJson)
temp = GetStringJson(ref queryString, key);
//queryString = "&" + queryString;
//int nIndex = queryString.IndexOf("&" + key + "=");
//if (nIndex == -1)
// return null;
//string temp = queryString.Substring(nIndex).Replace("&" + key + "=", "");
//nIndex = temp.IndexOf('&');
//if (nIndex > -1)
// temp = temp.Substring(0, nIndex);
return temp;
}
public static string FliterHtmlTag(string htmlStr)
{
if (String.IsNullOrEmpty(htmlStr))
{
return "";
}
string regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
string regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
string regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
htmlStr = Regex.Replace(htmlStr, regEx_style, "");//删除css
htmlStr = Regex.Replace(htmlStr, regEx_script, "");//删除js
htmlStr = Regex.Replace(htmlStr, regEx_html, "");//删除html标记
htmlStr = Regex.Replace(htmlStr, "\\s*|\t|\r|\n", "");//去除tab、空格、空行
htmlStr = htmlStr.Replace("\"", "");//去除异常的引号
return htmlStr.Trim();
}
public static string GetOneJsonObjStrJson(ref string html, string reg)
{
return GetJsonObjStrJson(ref html, reg).FirstOrDefault();
}
public static List<string> GetJsonObjStrJson(ref string html, string reg, int level = 0)
{
List<string> rstLst = new List<string>();
if (html == null)
return rstLst;
string htmlTmp = html.Replace("\\{", "\\这里是正花括号占位符").Replace("\\}", "\\这里是反花括号占位符").Replace("\"" + reg + "\": {", "\"" + reg + "\":{");
retry:
string lvStr = "";
if (level == 1)
{
lvStr += "\"";
}
var index1 = htmlTmp.IndexOf("\"" + reg + "\":" + lvStr + "{");
if (index1 < 0)
return rstLst;
htmlTmp = htmlTmp.Substring(index1 + ("\"" + reg + "\":" + lvStr + "{").Length - 1);
// 括号计数
int braceNum = 0;
//string rst = "{";
//while (htmlTmp.Length > 0)
for (int i = 0; i < htmlTmp.Length; i++)
{
//rst += htmlTmp.Substring(0, 1);
//if (htmlTmp.StartsWith("{"))
// braceNum++;
//else if (htmlTmp.StartsWith("}"))
// braceNum--;
if (htmlTmp[i] == '{')
braceNum++;
else if (htmlTmp[i] == '}')
braceNum--;
//htmlTmp = htmlTmp.Substring(1);
if (braceNum == 0)
{
rstLst.Add(htmlTmp.Substring(0, i + 1).Replace("\\这里是正花括号占位符", "\\{").Replace("\\这里是反花括号占位符", "\\}"));
htmlTmp = htmlTmp.Substring(i + 1);
//rstLst.Add(rst.Replace("\\这里是正花括号占位符", "\\{").Replace("\\这里是反花括号占位符", "\\}"));
break;
}
// 循环完了还没结果返回空列表
if (i == htmlTmp.Length - 1)
return rstLst;
}
if (htmlTmp.Length > 0)
goto retry;
return rstLst;
}
public static List<string> GetJsonArrStrJson(ref string html, string reg)
{
List<string> rstLst = new List<string>();
if (html == null)
return rstLst;
string htmlTmp = html.Replace("\\[", "\\这里是正方括号占位符").Replace("\\]", "\\这里是反方括号占位符").Replace("\"" + reg + "\": [", "\"" + reg + "\":[");
retry:
var index1 = htmlTmp.IndexOf("\"" + reg + "\":[");
if (index1 < 0)
return rstLst;
htmlTmp = htmlTmp.Substring(index1 + ("\"" + reg + "\":[").Length);
// 括号计数
int braceNum = 1;
string rst = "[";
while (htmlTmp.Length > 0)
{
rst += htmlTmp.Substring(0, 1);
if (htmlTmp.StartsWith("["))
braceNum++;
else if (htmlTmp.StartsWith("]"))
braceNum--;
htmlTmp = htmlTmp.Substring(1);
if (braceNum == 0)
{
rstLst.Add(rst.Replace("\\这里是正方括号占位符", "\\[").Replace("\\这里是反方括号占位符", "\\]"));
break;
}
}
if (htmlTmp.Length > 0)
goto retry;
return rstLst;
}
}
}
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace StoreHub.KJDWebService.Commons
{
public class TimeUtils
{
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime StampToDateTime(int timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime StampMillisecondsToDateTime(long timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
/// <summary>
/// C#格式时间转换为Unix时间戳(秒)
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static int DateTimeToTimestampSeconds(DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
/// <summary>
/// C#格式时间转换为Unix时间戳(毫秒)
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long DateTimeToTimestampMilliseconds(DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (long)(time - startTime).TotalMilliseconds;
}
}
}