using System;
using Newtonsoft.Json;
using System.IO;
using System.Text; namespace CarHailing.Base
{
/// <summary>
/// 数据帮助类
/// </summary>
public class DataHelper
{
/// <summary>
/// 英文逗号
/// </summary>
public const string EnglishComma = ","; /// <summary>
/// 中文逗号
/// </summary>
public const string ChineseComma = ","; /// <summary>
/// 竖线
/// </summary>
public const string VerticalLine = "|"; #region 取程序运行所在地址 /// <summary>
/// 取程序运行所在地址
/// </summary>
/// <returns></returns>
public static string GetPath()
{
string resFilePath = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase)
+ Path.DirectorySeparatorChar;
return resFilePath;
} #endregion #region 把对象转换为Json格式
/// <summary>
/// 把对象转换为Json格式
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">参数</param>
/// <returns>加密后字符串</returns>
public static string ObjToJson<T>(T obj)
{
return JsonConvert.SerializeObject(obj);
}
#endregion #region 把Json转换为对象
/// <summary>
/// 把Json转换为对象
/// </summary>
/// <typeparam name="T">返回对象类型</typeparam>
/// <param name="str">解密字符串</param>
/// <returns>解密结果对象</returns>
public static T JsonToObj<T>(string str)
{
return JsonConvert.DeserializeObject<T>(str);
}
#endregion #region 比较普通对象内全部属性,并把修改过的属性的属性值和原属性值存入操作日志表 /// <summary>
/// 比较普通对象内全部属性,并把修改过的属性的属性值和原属性值存入操作日志表
/// 注:现存入操作日志对象的值 为 oldValue | newValue , 如果T1 T2对象位置互换,则为 newValue | oldValue
/// </summary>
/// <typeparam name="T">普通对象(eg:Line)</typeparam>
/// <typeparam name="C">普通对象对应的操作日志对象(eg:LineDoLog)</typeparam>
/// <param name="t1">old普通对象</param>
/// <param name="t2">修改后的普通对象</param>
/// <param name="c1">操作日志对象</param>
/// <returns></returns>
public static C CompareAndAddLog<T, C>(T t1, T t2)
where T : class, new()
where C : class, new()
{
try
{
C c1 = new C();
System.Reflection.PropertyInfo[] mPi = typeof(T).GetProperties();
System.Reflection.PropertyInfo[] logMpi = typeof(C).GetProperties(); foreach (var pi in mPi)
{
//比较,只比较值类型
if ((pi.PropertyType.IsValueType || pi.PropertyType.Name.StartsWith("String")))
{
//string oldValue = pi.GetValue(t1, null).ToString();
//string newValue = pi.GetValue(t2, null).ToString(); //object getOldValue = pi.GetValue(t1, null);
//object getNewValue = pi.GetValue(t2, null);
//string oldValue = string.Empty;
//string newValue = string.Empty;
//if (getOldValue != null)
//{
// oldValue = getOldValue.ToString();
//}
//else
//{
// oldValue = "";
//}
//if (getNewValue != null)
//{
// newValue = getNewValue.ToString();
//}
//else
//{
// newValue = "";
//} object getOldValue = pi.GetValue(t1, null) ?? "";
object getNewValue = pi.GetValue(t2, null) ?? "";
string oldValue = getOldValue.ToString();
string newValue = getNewValue.ToString();
string oldName = pi.Name;
if (!oldValue.Equals(newValue))
{
string s = oldValue + "|" + newValue;
foreach (var p in logMpi)
{
if ((p.PropertyType.IsValueType || p.PropertyType.Name.StartsWith("String")))
{
string logDoName = p.Name;
if (logDoName.Equals(oldName))
{
p.SetValue(c1, s);
//p.SetValue(c1, Convert.ChangeType(s, p.PropertyType), null);
break;
}
} }
}
else
{
foreach (var p in logMpi)
{
if ((p.PropertyType.IsValueType || p.PropertyType.Name.StartsWith("String")))
{
string logDoName = p.Name;
if (logDoName.Equals(oldName))
{
p.SetValue(c1, oldValue);
//p.SetValue(c1, Convert.ChangeType("", p.PropertyType), null);
break;
}
} }
}
} }
return c1;
}
catch (Exception ex)
{
throw ex;
//return null;
}
}
//for (int i = 0; i < mPi.Length; i++)
//{
// System.Reflection.PropertyInfo pi = mPi[i]; // string oldValue = pi.GetValue(t1, null).ToString();
// string newValue = pi.GetValue(t2, null).ToString();
// string oldName = pi.Name;
// if (!oldValue.Equals(newValue))
// {
// string s = oldValue + "|" + newValue;
// //pi.SetValue(emptyLine, s);
// for (int n = 0; n < logMpi.Length; n++)
// {
// System.Reflection.PropertyInfo p = logMpi[n];
// string logDoName = p.Name;
// if (logDoName.Equals(oldName))
// {
// //p.SetValue(emptyLineDoLog, s);
// p.SetValue(c1, Convert.ChangeType(s, p.PropertyType), null);
// }
// }
// }
// else
// {
// for (int n = 0; n < logMpi.Length; n++)
// {
// System.Reflection.PropertyInfo p = logMpi[n];
// string logDoName = p.Name;
// if (logDoName.Equals(oldName))
// {
// //p.SetValue(emptyLineDoLog, oldValue);
// p.SetValue(c1, Convert.ChangeType("", p.PropertyType), null);
// }
// }
// }
//}
#endregion #region 对象间赋值 /// <summary>
/// 对象间赋值
/// </summary>
/// 部分类型不能进行强制转换、名称必须一致且所有子集合间及父集合间名称不能重复
/// <typeparam name="T">传入对象</typeparam>
/// <typeparam name="L">输出对象</typeparam>
/// <param name="t">传入数据</param>
/// <returns></returns>
public static L Mapper<T, L>(T t) where L : new()
{
if (t == null)
{
return default(L);
}
System.Reflection.PropertyInfo[] propertiesT = typeof(T).GetProperties();//GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
System.Reflection.PropertyInfo[] propertiesL = typeof(L).GetProperties();
L setT = new L();
foreach (System.Reflection.PropertyInfo itemL in propertiesL)
{
foreach (System.Reflection.PropertyInfo itemT in propertiesT)
{
if (itemL.Name == itemT.Name)
{
object value = itemT.GetValue(t, null);
itemL.SetValue(setT, value, null);
}
}
}
return setT;
}
#endregion #region 获取随机字符串 /// <summary>
/// 获取随机字符串
/// </summary>
/// <param name="strLength">字符串长度</param>
/// <param name="Seed">随机函数种子值</param>
/// <returns>指定长度的随机字符串</returns>
public static string GetRandomString(int strLength, params int[] Seed)
{
string strSep = ",";
char[] chrSep = strSep.ToCharArray();
string strChar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"
+ ",A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] aryChar = strChar.Split(chrSep, strChar.Length);
string strRandom = string.Empty;
Random Rnd;
if (Seed != null && Seed.Length > )
{
long tick = DateTime.Now.Ticks;
int speed = (int)(tick & 0xffffffffL) | (int)(tick >> );
Rnd = new Random(speed + Seed[]);
}
else
{
Rnd = new Random();
}
//生成随机字符串
for (int i = ; i < strLength; i++)
{
strRandom += aryChar[Rnd.Next(aryChar.Length)];
}
return strRandom;
} #endregion #region base64编码的文本转为图片 /// <summary>
/// base64编码的文本 转为 图片
/// </summary>
/// <param name="basedata">文件流</param>
/// <param name="savePath">保存路径</param>
/// <param name="name">文件名</param>
/// <returns>Ex</returns>
public static string Base64StringToImage(string basedata, string savePath, string name)
{
try
{
if (!Valid.IsBase64String(basedata))
{
LoggerHelper.Error("非base64编码");
throw new NullReferenceException("非base64编码!");
}
if (!Directory.Exists(savePath))//地图存放的默认文件夹是否存在
{
Directory.CreateDirectory(savePath);//不存在则创建
}
string[] sArray = basedata.Split(',');
int i = basedata.IndexOf("/") + ;
int j = basedata.IndexOf(";");
string str = basedata.Substring(i, j - i);
string fileName = name + "." + str;//文件名
string fileFullPath = Path.Combine(savePath, fileName);//合并路径生成文件存放路径
byte[] arr2 = Convert.FromBase64String(sArray[]);
using (MemoryStream ms2 = new MemoryStream(arr2))
{
System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2);
////只有把当前的图像复制一份,然后把旧的Dispose掉,那个文件就不被锁住了,
////这样就可以放心覆盖原始文件,否则GDI+一般性错误(A generic error occurred in GDI+)
System.Drawing.Bitmap bmpNew = new System.Drawing.Bitmap(bmp2);
bmp2.Dispose();
bmp2 = null; switch (str)
{
case "bmp":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Bmp);
break;
case "emf":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Emf);
break;
case "exif":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Exif);
break;
case "gif":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Gif);
break;
case "icon":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Icon);
break;
case "jpeg":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
//case "jpg":
// bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
// break;
case "memorybmp":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.MemoryBmp);
break;
case "png":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Png);
break;
case "tiff":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Tiff);
break;
case "wmf":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Wmf);
break;
default:
LoggerHelper.Error("错误的图片格式!");
throw new Exception("错误的图片格式");
}
bmpNew.Dispose();
}
return str;
}
catch (Exception ex)
{
//string result = "Base64StringToImage 转换失败\nException:" + ex.Message;
LoggerHelper.Error("Base64StringToImage 转换失败\nException:", ex);
throw ex;
}
} #endregion #region 字符串写文件
/// <summary>
/// 字符串写文件
/// </summary>
/// <param name="file">文件目录</param>
/// <param name="data">数据</param>
public static void WriteStream(string file, string data)
{
FileStream fileStream = new FileStream(file, FileMode.Append);
StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
streamWriter.Write(data + "\r\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
/// <summary>
/// 字符串写文件
/// </summary>
/// <param name="file">文件目录</param>
/// <param name="data">数据</param>
public static void WriteStream(string data)
{
var file = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase)
+ Path.DirectorySeparatorChar + "Info.txt";
if (!File.Exists(file))
{
FileStream fileStream = new FileStream(file, FileMode.Append);
StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
streamWriter.WriteLine(data + "\r\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
else
{ FileStream fileStream = new FileStream(file, FileMode.Append);
StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
streamWriter.WriteLine(data + "\r\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
} #endregion #region 取文本右边内容
/// <summary>
/// 取文本右边内容
/// </summary>
/// <param name="str">文本</param>
/// <param name="s">标识符</param>
/// <returns>右边内容</returns>
public static string GetRight(string str, string s)
{
//int start = str.IndexOf(s);
int strLength = str.Length;
int sLength = s.Length;
int start = sLength;
int end = strLength - sLength;
string temp = str.Substring(start, end);
return temp;
}
#endregion #region 字符串转首字母大写 /// <summary> /// 在指定的字符串列表CnStr中检索符合拼音索引字符串 /// </summary> /// <param name="CnStr">汉字字符串</param> /// <returns>相对应的汉语拼音首字母串</returns> public static string GetSpellCode(string CnStr)
{ string strTemp = ""; int iLen = CnStr.Length; int i = ; for (i = ; i <= iLen - ; i++)
{ strTemp += GetCharSpellCode(CnStr.Substring(i, )); } return strTemp; } /// <summary>
/// 得到一个汉字的拼音第一个字母,如果是一个英文字母则直接返回大写字母
/// </summary>
/// <param name="CnChar">单个汉字</param>
/// <returns>单个大写字母</returns> private static string GetCharSpellCode(string CnChar)
{ long iCnChar; byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar); //如果是字母,则直接返回 if (ZW.Length == )
{ return CnChar.ToUpper(); } else
{ // get the array of byte from the single char int i1 = (short)(ZW[]); int i2 = (short)(ZW[]); iCnChar = i1 * + i2; } // iCnChar match the constant if ((iCnChar >= ) && (iCnChar <= ))
{ return "A"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "B"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "C"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "D"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "E"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "F"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "G"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "H"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "J"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "K"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "L"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "M"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "N"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "O"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "P"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Q"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "R"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "S"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "T"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "W"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "X"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Y"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Z"; }
else return ("?"); } #endregion
}
}

一份数据帮助类,比较粗超,最后这个方法貌似有点问题,有些字符貌似转不出来(应该是编码区域不对吧),具体我也忘了,路过的各位大佬,有兴趣帮忙指证。qqq。

C#,DataHelper,一个通用的帮助类,留个备份。的更多相关文章

  1. 一个通用数据库访问类(C#,SqlClient)

    本文转自:http://www.7139.com/jsxy/cxsj/c/200607/114291.html使用ADO.NET时,每次数据库操作都要设置connection属性.建立connecti ...

  2. PHP封装一个通用好用的文件上传处理类

    封装一个文件上传类完成基本功能如下: 1.可上传多个或单个文件 2.上传成功返回一个或多个文件名 3.上传失败则返回每个失败文件的错误信息 上传类中的基本功能: 1.构造参数,用户可以自定义配置参数, ...

  3. 一个爬取https和http通用的工具类(JDK自带的URL的用法)

    今天在java爬取天猫的时候因为ssl报错,所以从网上找了一个可以爬取https和http通用的工具类.但是有的时候此工具类爬到的数据不全,此处不得不说python爬虫很厉害. package cn. ...

  4. 免费IP代理池定时维护,封装通用爬虫工具类每次随机更新IP代理池跟UserAgent池,并制作简易流量爬虫

    前言 我们之前的爬虫都是模拟成浏览器后直接爬取,并没有动态设置IP代理以及UserAgent标识,本文记录免费IP代理池定时维护,封装通用爬虫工具类每次随机更新IP代理池跟UserAgent池,并制作 ...

  5. DataAccess通用数据库访问类,简单易用,功能强悍

    以下是我编写的DataAccess通用数据库访问类,简单易用,支持:内联式创建多个参数.支持多事务提交.支持参数复用.支持更换数据库类型,希望能帮到大家,若需支持查出来后转换成实体,可以自行扩展dat ...

  6. Linux C编程学习之开发工具3---多文件项目管理、Makefile、一个通用的Makefile

    GNU Make简介 大型项目的开发过程中,往往会划分出若干个功能模块,这样可以保证软件的易维护性. 作为项目的组成部分,各个模块不可避免的存在各种联系,如果其中某个模块发生改动,那么其他的模块需要相 ...

  7. 通用数据库操作类,前端easyui-datagrid,form

    实现功能:     左端datagrid显示简略信息,右侧显示选中行详细信息,数据库增删改 (1)点击选中行,右侧显示详细信息,其中[新增].[修改].[删除]按钮可用,[保存]按钮禁用 (2)点击[ ...

  8. 封装一个通用递归算法,使用TreeIterator和TreeMap来简化你的开发工作。

    在实际工作中,你肯定会经常的对树进行遍历,并在树和集合之间相互转换,你会频繁的使用递归. 事实上,这些算法在逻辑上都是一样的,因此可以抽象出一个通用的算法来简化工作. 在这篇文章里,我向你介绍,我封装 ...

  9. 利用RBAC模型实现一个通用的权限管理系统

    本文主要描述一个通用的权限系统实现思路与过程.也是对此次制作权限管理模块的总结. 制作此系统的初衷是为了让这个权限系统得以“通用”.就是生产一个web系统通过调用这个权限系统(生成的dll文件), 就 ...

随机推荐

  1. devDependencies和dependencies的版本写法

    devDependencies和dependencies的版本写法 指定版本:比如1.2.2,遵循大版本.次要版本.小版本的格式规定,安装时只安装指定版本. 波浪号(tilde)+指定版本:比如~1. ...

  2. JustMock .NET单元测试利器(一)

    1.什么是Mock? Mock一词是指模仿或者效仿,用于创建实例和静态模拟.安排和验证行为.在软件开发中提及"mock",通常理解为模拟对象.模拟对象的概念就是我们想要创建一个可以 ...

  3. 启动就加载(三)initializingbean实现afterPropertiesSet方法

    TransactionTemplate,就直接以TransactionTemplate为入口开始学习. TransactionTemplate的源码如下: public class Transacti ...

  4. [UVA 10529]Dumb Bones

    题面在这里 题意 放\(n\)个相连的骨牌,每次放的时候有\(pl\)的概率往左倒,有\(pr\)的概率往右倒,骨牌倒的时候可能会打翻左边相邻或者右边相邻的骨牌,并引起连锁反应直到最后一个骨牌旁边没有 ...

  5. Nginx负载均衡——基础功能

    熟悉Nginx的小伙伴都知道,Nginx是一个非常好的负载均衡器.除了用的非常普遍的Http负载均衡,Nginx还可以实现Email,FastCGI的负载均衡,甚至可以支持基于Tcp/UDP协议的各种 ...

  6. .NET Core 配置Configuration杂谈

    前言 .NET Core 在配置文件的操作上相对于.NET Framework做了不少改变,今天来聊一聊.关于Configuration的Package都是以Microsoft.Extensions. ...

  7. centos7.2 配置内网ntp服务器进行时间同步

    (一)修改/etc/ntp.conf 配置文件,注意红色部分,其他部分不需要改  ########################################################### ...

  8. c#多线程同步之EventWaitHandle使用

    有这么一个场景,我需要借助windows剪贴板把数据插入到word域中. 实现步骤: 1.把剪贴板数据保存到变量. 2.使用剪贴板实现我们的业务. 3.把变量里的数据存回剪贴板. 但是结果却令人诧异, ...

  9. js备战春招の四の表单

    表单验证:required="required"(浏览器自动验证) javascript表单验证: <input id="numb">这条html标 ...

  10. MSIL实用指南-局部变量的声明、保存和加载

    这一篇讲解方法内的局部变量是怎么声明.怎样保存.怎样加载的. 声明局部变量声明用ILGenerator的DeclareLocal方法,参数是局部变量的数据类型,得到一个局部变量对应的创建类LocalB ...