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. HTML5之Canvas画圆形

    HTML5之Canvas画圆形 1.设计源码 <!DOCTYPE html> <head> <meta charset="utf-8" /> & ...

  2. MFC 中线程传递CString 是不安全的 转

     MFC 中线程传递CString 是不安全的       在MFC中,向线程传递CString变量参数时,很容易犯一个错误,就是使用一个超出生存期的变量,在主函数中定义的CString变量是局部变量 ...

  3. C#构造函数与析构函数--C#基础

    1.构造函数 1)构造函数没有返回值,也不能写void,必须是public 修饰符 2)构造函数和类名相同 3)构造函数也是可以重载的 public Clerk(string name,Gender ...

  4. [APIO2009]会议中心

    [APIO2009]会议中心 题目大意: 原网址与样例戳我! 给定n个区间,询问以下问题: 1.最多能够选择多少个不相交的区间? 2.在第一问的基础上,输出字典序最小的方案. 数据范围:\(n \le ...

  5. 1.4 如何在main()方法之前执行输出“hello world”

    public class Test{ static{ System.out.println("hello world"); } public static void main(St ...

  6. 前端知识点总结——VUE

    转载自:http://www.bslxx.com/m/view.php?aid=1799 1.框架和库的区别: 框架:framework 有着自己的语法特点.都有对应的各个模块库 library 专注 ...

  7. POI导出Excel的几种情况

    第一种:常见导出[已知表头(长度一定),已知表数据(具体一个对象的集合,并已知对象各个属性的类型)]第二种:不常见导出[已知表头(长度不定),已知表数据(没有具体对象,装在String类型的集合中)] ...

  8. 推荐一款有趣的APP-种子习惯

    在女朋友的影响下接触到了种子习惯的app,一开始不觉得它有多大魅力,只知道它有契约的功能,有很多人分享自己的习惯,记录生活中的点滴. 毕业回家的寒假,家里比较冷,每天起床都需要莫大的勇气,挣扎半天最终 ...

  9. IE浏览器右键菜单插件开发(上篇)——自定义一个IE右键菜单项

    要做一个IE右键浏览器插件,得3步走. 第一,在IE右键菜单上添加自定义菜单名称,是通过注册表实现的,如下: string regkey = @"Software\Microsoft\Int ...

  10. Linux IPMI 配置管理.md

    DELL 服务器 user id 范围:1-16 可以修改用户名和密码 不允许用户名重复 当设置一个已存在的用户名时,无论user id在前或在后,修改密码会将该项用户名设置为空,enable会恢复成 ...