using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Transactions;
using System.Web;
namespace MES.Common
{
/// <summary>
/// 扩展方法
/// </summary>
public static class ExtraFun
{
#region Json处理函数
/// <summary>
/// 对象转字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJson(this object obj)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
return JsonConvert.SerializeObject(obj, timeConverter);
}
/// <summary>
/// 字符串转对象
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static T JosnToObject<T>(this string json)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
return JsonConvert.DeserializeObject<T>(json, timeConverter);
}
#endregion
#region 字符串处理函数
/// <summary>
/// 去除字符串的空格换行符等
/// </summary>
/// <param name="str">需要处理的字符串</param>
/// <returns>处理后的字符串</returns>
public static string Purify(this string str)
{
if (!string.IsNullOrEmpty(str)) str = str.Replace("
", "").Replace(" ", "").Replace(" ", "").Replace("
", "");
return str;
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="str">加密字符</param>
/// <param name="code">加密位数16/32</param>
/// <returns></returns>
public static string ToMd5(this string str, EnumMd5Length length = EnumMd5Length.x2)
{
StringBuilder strMd5 = new StringBuilder();
try
{
byte[] sor = Encoding.UTF8.GetBytes(str);
using (MD5 md5 = MD5.Create())
{
byte[] result = md5.ComputeHash(sor);
for (int i = 0; i < result.Length; i++)
{
strMd5.Append(result[i].ToString(length == EnumMd5Length.x1 ? EnumMd5Length.x2.ToString() : length.ToString()));
}
}
return length == EnumMd5Length.x1 ? strMd5.ToString().ToUpper().Substring(8, 16) : strMd5.ToString().ToUpper();
}
catch
{
return "";
}
}
/// <summary>
/// 去除HTML标记
/// </summary>
/// <param name="NoHTML">包括HTML的源码 </param>
/// <returns>已经去除后的文字</returns>
public static string RemoveHtml(this string Htmlstring)
{
if (!string.IsNullOrWhiteSpace(Htmlstring))
{
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//删除HTML
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"([
])[s]+", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", """, RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "xa1", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "xa2", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "xa3", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "xa9", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&#(d+);", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"…", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"—", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"“", "", RegexOptions.IgnoreCase);
Htmlstring.Replace("<", "");
Htmlstring = Regex.Replace(Htmlstring, @"”", "", RegexOptions.IgnoreCase);
Htmlstring.Replace(">", "");
Htmlstring.Replace("
", "");
Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
}
return Htmlstring;
}
/// <summary>
/// 格式化文本(防止SQL注入)
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string RemoveSql(this string html)
{
if (!string.IsNullOrWhiteSpace(html))
{
Regex regex1 = new Regex(@"<script[sS]+</script *>", RegexOptions.IgnoreCase);
Regex regex2 = new Regex(@" href *= *[sS]*script *:", RegexOptions.IgnoreCase);
Regex regex3 = new Regex(@" on[sS]*=", RegexOptions.IgnoreCase);
Regex regex4 = new Regex(@"<iframe[sS]+</iframe *>", RegexOptions.IgnoreCase);
Regex regex5 = new Regex(@"<frameset[sS]+</frameset *>", RegexOptions.IgnoreCase);
Regex regex10 = new Regex(@"select", RegexOptions.IgnoreCase);
Regex regex11 = new Regex(@"update", RegexOptions.IgnoreCase);
Regex regex12 = new Regex(@"delete", RegexOptions.IgnoreCase);
html = regex1.Replace(html, ""); //过滤<script></script>标记
html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
html = regex4.Replace(html, ""); //过滤iframe
html = regex5.Replace(html, ""); //过滤iframe
html = regex10.Replace(html, "s_elect");
html = regex11.Replace(html, "u_pudate");
html = regex12.Replace(html, "d_elete");
html = html.Replace("'", "’");
html = html.Replace(" ", " ");
}
return html;
}
/// <summary>
/// 判断是否为手机号
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsMobilePhone(this string input)
{
Regex regex = new Regex("^1[3456789]\d{9}$");
return regex.IsMatch(input);
}
/// <summary>
/// 将字符串转为int数组
/// </summary>
/// <param name="str"></param>
/// <param name="separator"></param>
/// <returns></returns>
public static int[] ToIntArray(this string str, char separator)
{
if (string.IsNullOrWhiteSpace(str)) return null;
string[] ar = str.Split(separator);
List<int> ints = new List<int>();
foreach (var item in ar)
{
int v;
if (int.TryParse(item, out v))
ints.Add(v);
}
return ints.ToArray();
}
/// <summary>
/// 将字符串转为DateTime数组
/// </summary>
/// <param name="str"></param>
/// <param name="separator"></param>
/// <returns></returns>
public static DateTime[] ToDateTimeArray(this string str, char separator)
{
if (string.IsNullOrWhiteSpace(str)) return null;
string[] ar = str.Split(separator);
List<DateTime> ints = new List<DateTime>();
foreach (var item in ar)
{
DateTime v;
if (DateTime.TryParse(item, out v))
ints.Add(v);
}
return ints.ToArray();
}
/// <summary>
/// 将字符串加单引号
/// </summary>
/// <param name="paramStr"></param>
/// <returns></returns>
public static string AddSingleQuotes(this string str, char separator = ',')
{
return $"'{str.Trim(separator).Replace(separator.ToString(), $"'{separator}'")}'";
}
#endregion
#region 实体类转换相关
/// <summary>
/// 将DataRow转为实体类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="row"></param>
/// <returns></returns>
public static TEntity ToEntity<TEntity>(this DataRow row) where TEntity : class
{
TEntity entity = null;
if(row != null)
{
entity = Activator.CreateInstance<TEntity>();
foreach (var property in entity.GetType().GetProperties())
{
Type t = property.PropertyType;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
t = t.GetGenericArguments()[0];
try
{
if (row.Table.Columns.Contains(property.Name))
property.SetValue(entity, Convert.ChangeType(row[property.Name], t), null);
}
catch
{
property.SetValue(entity, null, null);
continue;
}
}
}
return entity;
}
/// <summary>
/// 将DataTable转为List<T>
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static List<TEntity> ToList<TEntity>(this DataTable dt) where TEntity : class
{
//if (dt == null || dt.Rows.Count <= 0) return null;
List<TEntity> list = new List<TEntity>();
foreach (DataRow row in dt.Rows)
{
list.Add(row.ToEntity<TEntity>());
}
return list;
}
/// <summary>
/// DataTable中添加实体类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="dt"></param>
/// <param name="entity"></param>
public static void Add<TEntity>(this DataTable dt, TEntity entity) where TEntity : class
{
if (entity == null) return;
DataRow dataRow = dt.NewRow();
object proValue;
foreach (var property in entity.GetType().GetProperties())
{
if (!dt.Columns.Contains(property.Name))
{
Type t = property.PropertyType;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
t = t.GetGenericArguments()[0];
dt.Columns.Add(new DataColumn(property.Name, t));
}
proValue = property.GetValue(entity, null);
if (proValue == null) proValue = DBNull.Value;
dataRow[property.Name] = proValue;
}
dt.Rows.Add(dataRow);
}
/// <summary>
/// 实体类之间数据复制
/// </summary>
/// <typeparam name="T">需要复制的实体类类型</typeparam>
/// <param name="source">数据源</param>
/// <param name="target">需要复制的实体类实例</param>
public static void CopyTo<T>(this object source, T target, string endString = null) where T : class, new()
{
if (source == null) return;
if (target == null) target = new T();
try
{
PropertyInfo proInfo;
FieldInfo fieldInfo;
object proValue;
using (TransactionScope scope = new TransactionScope())
{
//复制主体
foreach (var property in target.GetType().GetProperties())
{
proInfo = source.GetType().GetProperty(property.Name);
if (proInfo == null) continue;
proValue = proInfo.GetValue(source, null);
if (proValue == null) continue;
target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { proValue });
if (property.Name == endString) break;
}
//复制子类
foreach (var field in target.GetType().GetFields())
{
fieldInfo = source.GetType().GetField(field.Name);
if (fieldInfo == null) continue;
proValue = fieldInfo.GetValue(source);
if (proValue == null) continue;
target.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, target, new object[] { proValue });
}
scope.Complete();
}
}
catch
{
return;
}
}
/// <summary>
/// 判断是否为Nullable<>泛型
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
/// <summary>
/// 过滤只读字段
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="entity"></param>
/// <param name="strName"></param>
/// <returns></returns>
public static TEntity ReadonlyToNull<TEntity>(this TEntity entity, string strName) where TEntity : class
{
object proValue;
foreach (var property in entity.GetType().GetProperties())
{
proValue = property.GetValue(entity, null);
if (proValue == null || (property.Name == "Id" && property.PropertyType == typeof(int) && (int)proValue == 0)) continue;
if ($"0,{strName},".Contains(property.Name)) property.SetValue(entity, null, null);
}
return entity;
}
/// <summary>
/// 从表单中转换实体
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="request"></param>
/// <returns></returns>
public static TEntity ToEntity<TEntity>(this HttpRequest request) where TEntity : class
{
TEntity entity = Activator.CreateInstance<TEntity>();
foreach (var property in entity.GetType().GetProperties())
{
Type t = property.PropertyType;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
t = t.GetGenericArguments()[0];
try
{
if (!string.IsNullOrWhiteSpace(request[property.Name]))
property.SetValue(entity, Convert.ChangeType(request[property.Name], t), null);
}
catch
{
property.SetValue(entity, null, null);
continue;
}
}
return entity;
}
#endregion
#region SQL语句操作函数
/// <summary>
/// 处理Sql语句的Where条件
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string SqlWhere(this string str)
{
if (string.IsNullOrWhiteSpace(str)) return "1=1";
if (str.Trim().StartsWith("and", StringComparison.OrdinalIgnoreCase)) return "1=1 " + str;
return str;
}
#endregion
#region DataTable操作相关
/// <summary>
/// 根据实体生成DataTable结构
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public static DataTable ToTable<TEntity>()
{
DataTable dt = new DataTable(typeof(TEntity).Name);
foreach (var property in typeof(TEntity).GetProperties())
{
Type t = property.PropertyType;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
t = t.GetGenericArguments()[0];
dt.Columns.Add(new DataColumn(property.Name, t));
}
return dt;
}
/// <summary>
/// 将List转为DataTable
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable<TEntity>(this List<TEntity> list) where TEntity : class
{
DataTable dt = ToTable<TEntity>();
if (list == null || list.Count <= 0) return dt;
foreach (var item in list)
{
dt.Add(item);
}
return dt;
}
/// <summary>
/// 将Datatable保存为Excel文件
/// </summary>
/// <param name="dt"></param>
/// <param name="fileFullName"></param>
/// <returns></returns>
public static bool ToExcle(this DataTable dt, string fileFullName)
{
try
{
FileInfo fi = new FileInfo(fileFullName);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(fileFullName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
StringBuilder data = new StringBuilder();
//写出列名称-第一行
List<string> cols = new List<string>();
data.Append("序号");
int index = 0;
foreach (DataColumn col in dt.Columns)
{
data.Append("," + col.ColumnName);
cols.Add(col.ColumnName);
}
//换行
sw.WriteLine(data);
//写出各行数据
foreach (DataRow row in dt.Rows)
{
index++;
data = new StringBuilder();
data.Append(index);
foreach (var colName in cols)
{
data.Append("," + row[colName]);
}
//换行
sw.WriteLine(data);
}
//关闭
sw.Close();
fs.Close();
fs.Dispose();
return true;
}
catch(Exception ex)
{
LogHelper.Error($"将Datatable保存为Excel文件失败:" + ex.Message);
return false;
}
}
/// <summary>
/// DataTable 转换为 Html
/// </summary>
/// <param name="dt"></param>
/// <param name="tpl">邮件模板[2020.09.01 新增]</param>
/// <returns></returns>
public static string ToHtml(this DataTable dt, string tpl = "{{!TABLE}}")
{
if (string.IsNullOrWhiteSpace(tpl)) tpl = "{{!TABLE}}";
StringBuilder sb = new StringBuilder();
sb.Append("<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type"content="text/html; charset=utf-8"/><title>" + dt.TableName + "</title><style>table{background:#e6e6e6}table tr:hover td{background:#f2f2f2}table caption{height:38px;line-height:38px}table tr th{height:38px;line-height:38px;font-size:14px;background:#f2f2f2;min-40px;padding:0px 5px;font-weight:normal}table tr td{height:34px;line-height:34px;background:#FFFFFF;padding:0px 5px;min-40px;text-align:center;font-size:12px}table tr.even td{background:#f2f2f2}</style></head><body>" + tpl + "</body></html>");
StringBuilder table = new StringBuilder();
table.Append("<table cellspacing="1"cellPadding="0"border="0"><caption>" + dt.TableName + "</caption><thead><tr><th>序号</th>");
List<string> cols = new List<string>();
//拼接标题栏
foreach (DataColumn col in dt.Columns)
{
table.Append($"<th>{col.ColumnName}</th>");
cols.Add(col.ColumnName);
}
table.Append("</tr></thead><tbody>");
int i = 0;
//拼接行数据
foreach(DataRow row in dt.Rows)
{
i++;
table.Append("<tr" + (i % 2 == 0 ? " class="even"" : "") + $"><td>{i}</td>");
foreach (string colName in cols)
{
table.Append($"<td>{row[colName]}</td>");
}
table.Append("</tr>");
}
table.Append("</tbody></table>");
return sb.ToString().Replace("{{!TABLE}}", table.ToString());
}
#endregion
#region DataSet操作函数
/// <summary>
/// 判断DataSet是否为null
/// </summary>
/// <param name="ds"></param>
/// <returns></returns>
public static bool IsNull(this DataSet ds)
{
if (ds == null || ds.Tables.Count <= 0)
return true;
if (ds.Tables[0].Rows.Count <= 0)
return true;
return false;
}
#endregion
}
}