码迷,mamicode.com
首页 > 其他好文 > 详细

帮助类

时间:2016-08-25 23:47:09      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

#region 生成日期随机码
 2         /// <summary>
 3         /// 生成日期随机码
 4         /// </summary>
 5         /// <returns></returns>
 6         public static string GetRamCode()
 7         {
 8             #region
 9             return DateTime.Now.ToString("yyyyMMddHHmmssffff");
10             #endregion
11         }
12         #endregion

#region 生成随机字母或数字
 2         /// <summary>
 3         /// 生成随机数字
 4         /// </summary>
 5         /// <param name="length">生成长度</param>
 6         /// <returns></returns>
 7         public static string Number(int Length)
 8         {
 9             return Number(Length, false);
10         }
11 
12         /// <summary>
13         /// 生成随机数字
14         /// </summary>
15         /// <param name="Length">生成长度</param>
16         /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
17         /// <returns></returns>
18         public static string Number(int Length, bool Sleep)
19         {
20             if (Sleep)
21                 System.Threading.Thread.Sleep(3);
22             string result = "";
23             System.Random random = new Random();
24             for (int i = 0; i < Length; i++)
25             {
26                 result += random.Next(10).ToString();
27             }
28             return result;
29         }
30         /// <summary>
31         /// 生成随机字母字符串(数字字母混和)
32         /// </summary>
33         /// <param name="codeCount">待生成的位数</param>
34         public static string GetCheckCode(int codeCount)
35         {
36             string str = string.Empty;
37             int rep = 0;
38             long num2 = DateTime.Now.Ticks + rep;
39             rep++;
40             Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
41             for (int i = 0; i < codeCount; i++)
42             {
43                 char ch;
44                 int num = random.Next();
45                 if ((num % 2) == 0)
46                 {
47                     ch = (char)(0x30 + ((ushort)(num % 10)));
48                 }
49                 else
50                 {
51                     ch = (char)(0x41 + ((ushort)(num % 0x1a)));
52                 }
53                 str = str + ch.ToString();
54             }
55             return str;
56         }
57         /// <summary>
58         /// 根据日期和随机码生成订单号
59         /// </summary>
60         /// <returns></returns>
61         public static string GetOrderNumber()
62         {
63             string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
64             return num + Number(2).ToString();
65         }
66         private static int Next(int numSeeds, int length)
67         {
68             byte[] buffer = new byte[length];
69             System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
70             Gen.GetBytes(buffer);
71             uint randomResult = 0x0;//这里用uint作为生成的随机数  
72             for (int i = 0; i < length; i++)
73             {
74                 randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
75             }
76             return (int)(randomResult % numSeeds);
77         }
78         #endregion
技术分享
 
#region 截取字符长度
 2         /// <summary>
 3         /// 截取字符长度
 4         /// </summary>
 5         /// <param name="inputString">字符</param>
 6         /// <param name="len">长度</param>
 7         /// <returns></returns>
 8         public static string CutString(string inputString, int len)
 9         {
10             if (string.IsNullOrEmpty(inputString))
11                 return "";
12             inputString = DropHTML(inputString);
13             ASCIIEncoding ascii = new ASCIIEncoding();
14             int tempLen = 0;
15             string tempString = "";
16             byte[] s = ascii.GetBytes(inputString);
17             for (int i = 0; i < s.Length; i++)
18             {
19                 if ((int)s[i] == 63)
20                 {
21                     tempLen += 2;
22                 }
23                 else
24                 {
25                     tempLen += 1;
26                 }
27 
28                 try
29                 {
30                     tempString += inputString.Substring(i, 1);
31                 }
32                 catch
33                 {
34                     break;
35                 }
36 
37                 if (tempLen > len)
38                     break;
39             }
40             //如果截过则加上半个省略号 
41             byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
42             if (mybyte.Length > len)
43                 tempString += "…";
44             return tempString;
45         }
46         #endregion
技术分享
#region 对象<-->JSON 4.0使用
 2         /// <summary>
 3         /// 对象转JSON
 4         /// </summary>
 5         /// <typeparam name="T">对象实体</typeparam>
 6         /// <param name="t">内容</param>
 7         /// <returns>json包</returns>
 8         public static string ObjetcToJson<T>(T t)
 9         {
10             try
11             {
12                 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
13                 string szJson = "";
14                 using (MemoryStream stream = new MemoryStream())
15                 {
16                     json.WriteObject(stream, t);
17                     szJson = Encoding.UTF8.GetString(stream.ToArray());
18                 }
19                 return szJson;
20             }
21             catch { return ""; }
22         }
23 
24         /// <summary>
25         /// Json包转对象
26         /// </summary>
27         /// <typeparam name="T">对象</typeparam>
28         /// <param name="jsonstring">json包</param>
29         /// <returns>异常抛null</returns>
30         public static object JsonToObject<T>(string jsonstring)
31         {
32             object result = null;
33             try
34             {
35                 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
36                 using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonstring)))
37                 {
38                     result = json.ReadObject(stream);
39                 }
40                 return result;
41             }
42             catch { return result; }
43         }
44         #endregion
技术分享
 #region 对象<-->JSON 2.0 使用litjson插件
 2         /// <summary>
 3         /// 对象转JSON  jsonData
 4         /// </summary>
 5         /// <typeparam name="T"></typeparam>
 6         /// <param name="t"></param>
 7         /// <returns></returns>
 8         //public static string ObjetcToJsonData<T>(T t)
 9         //{
10         //    try
11         //    {
12         //        JsonData json = new JsonData(t);
13         //        return json.ToJson();
14         //    }
15         //    catch
16         //    {
17         //        return "";
18         //    }
19         //}
20 
21         ///// <summary>
22         ///// 对象转JSON jsonMapper
23         ///// </summary>
24         ///// <typeparam name="T"></typeparam>
25         ///// <param name="t"></param>
26         ///// <returns></returns>
27         //public static string ObjetcToJsonMapper<T>(T t)
28         //{
29         //    try
30         //    {
31         //        JsonData json = JsonMapper.ToJson(t);
32         //        return json.ToJson();
33         //    }
34         //    catch
35         //    {
36         //        return "";
37         //    }
38         //}
39 
40         ///// <summary>
41         ///// json转对象 jsonMapper
42         ///// </summary>
43         ///// <param name="jsons"></param>
44         ///// <returns></returns>
45         //public static object JsonToObject(string jsons)
46         //{
47         //    try
48         //    {
49         //        JsonData jsonObject = JsonMapper.ToObject(jsons);
50         //        return jsonObject;
51         //    }
52         //    catch { return null; }
53         //}
54 
55         #endregion
技术分享
#region DataTable<-->JSON
 2         /// <summary> 
 3         /// DataTable转为json 
 4         /// </summary> 
 5         /// <param name="dt">DataTable</param> 
 6         /// <returns>json数据</returns> 
 7         public static string DataTableToJson(DataTable dt)
 8         {
 9             List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
10             foreach (DataRow dr in dt.Rows)
11             {
12                 Dictionary<string, object> result = new Dictionary<string, object>();
13                 foreach (DataColumn dc in dt.Columns)
14                 {
15                     result.Add(dc.ColumnName, dr[dc]);
16                 }
17                 list.Add(result);
18             }
19 
20             return SerializeToJson(list);
21         }
22         /// <summary>
23         /// 序列化对象为Json字符串
24         /// </summary>
25         /// <param name="obj">要序列化的对象</param>
26         /// <param name="recursionLimit">序列化对象的深度,默认为100</param>
27         /// <returns>Json字符串</returns>
28         public static string SerializeToJson(object obj, int recursionLimit = 100)
29         {
30             try
31             {
32                 JavaScriptSerializer serialize = new JavaScriptSerializer();
33                 serialize.RecursionLimit = recursionLimit;
34                 return serialize.Serialize(obj);
35             }
36             catch { return ""; }
37         }
38         /// <summary>
39         /// json包转DataTable
40         /// </summary>
41         /// <param name="jsons"></param>
42         /// <returns></returns>
43         public static DataTable JsonToDataTable(string jsons)
44         {
45             DataTable dt = new DataTable();
46             try
47             {
48                 JavaScriptSerializer serialize = new JavaScriptSerializer();
49                 serialize.MaxJsonLength = Int32.MaxValue;
50                 ArrayList list = serialize.Deserialize<ArrayList>(jsons);
51                 if (list.Count > 0)
52                 {
53                     foreach (Dictionary<string, object> item in list)
54                     {
55                         if (item.Keys.Count == 0)//无值返回空
56                         {
57                             return dt;
58                         }
59                         if (dt.Columns.Count == 0)//初始Columns
60                         {
61                             foreach (string current in item.Keys)
62                             {
63                                 dt.Columns.Add(current, item[current].GetType());
64                             }
65                         }
66                         DataRow dr = dt.NewRow();
67                         foreach (string current in item.Keys)
68                         {
69                             dr[current] = item[current];
70                         }
71                         dt.Rows.Add(dr);
72                     }
73                 }
74             }
75             catch
76             {
77                 return dt;
78             }
79             return dt;
80         }
81         #endregion
技术分享
  #region List<--->DataTable
  2         /// <summary>
  3         /// DataTable转换泛型集合
  4         /// </summary>
  5         /// <typeparam name="T"></typeparam>
  6         /// <param name="table"></param>
  7         /// <returns></returns>
  8         public static List<T> DataTableToList<T>(DataTable table)
  9         {
 10             List<T> list = new List<T>();
 11             T t = default(T);
 12             PropertyInfo[] propertypes = null;
 13             string tempName = string.Empty;
 14             foreach (DataRow row in table.Rows)
 15             {
 16                 t = Activator.CreateInstance<T>();
 17                 propertypes = t.GetType().GetProperties();
 18                 foreach (PropertyInfo pro in propertypes)
 19                 {
 20                     tempName = pro.Name;
 21                     if (table.Columns.Contains(tempName))
 22                     {
 23                         object value = row[tempName];
 24                         if (!value.ToString().Equals(""))
 25                         {
 26                             pro.SetValue(t, value, null);
 27                         }
 28                     }
 29                 }
 30                 list.Add(t);
 31             }
 32             return list.Count == 0 ? null : list;
 33         }
 34 
 35         /// <summary>
 36         /// 将集合类转换成DataTable
 37         /// </summary>
 38         /// <param name="list">集合</param>
 39         /// <returns>DataTable</returns>
 40         public static DataTable ListToDataTable(IList list)
 41         {
 42             DataTable result = new DataTable();
 43             if (list != null && list.Count > 0)
 44             {
 45                 PropertyInfo[] propertys = list[0].GetType().GetProperties();
 46                 foreach (PropertyInfo pi in propertys)
 47                 {
 48                     result.Columns.Add(pi.Name, pi.PropertyType);
 49                 }
 50                 for (int i = 0; i < list.Count; i++)
 51                 {
 52                     ArrayList tempList = new ArrayList();
 53                     foreach (PropertyInfo pi in propertys)
 54                     {
 55                         object obj = pi.GetValue(list[i], null);
 56                         tempList.Add(obj);
 57                     }
 58                     object[] array = tempList.ToArray();
 59                     result.LoadDataRow(array, true);
 60                 }
 61             }
 62             return result;
 63         }
 64          public static List<T> ConvertTo<T>(DataTable dt) where T : new()
 65         {
 66             if (dt == null) return null;
 67             if (dt.Rows.Count <= 0) return null;
 68  
 69             List<T> list = new List<T>();
 70             try
 71             {
 72                 List<string> columnsName = new List<string>();  
 73                 foreach (DataColumn dataColumn in dt.Columns)
 74                 {
 75                     columnsName.Add(dataColumn.ColumnName);//得到所有的表头
 76                 }
 77                 list = dt.AsEnumerable().ToList().ConvertAll<T>(row => GetObject<T>(row, columnsName));  //转换
 78                 return list;
 79             }
 80             catch 
 81             {
 82                 return null;
 83             }
 84         }
 85  
 86         public static T GetObject<T>(DataRow row, List<string> columnsName) where T : new()
 87         {
 88             T obj = new T();
 89             try
 90             {
 91                 string columnname = "";
 92                 string value = "";
 93                 PropertyInfo[] Properties = typeof(T).GetProperties();
 94                 foreach (PropertyInfo objProperty in Properties)  //遍历T的属性
 95                 {
 96                     columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower()); //寻找可以匹配的表头名称
 97                     if (!string.IsNullOrEmpty(columnname))
 98                     {
 99                         value = row[columnname].ToString();
100                         if (!string.IsNullOrEmpty(value))
101                         {
102                             if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) //存在匹配的表头
103                             {
104                                 value = row[columnname].ToString().Replace("$", "").Replace(",", ""); //从dataRow中提取数据
105                                 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null); //赋值操作
106                             }
107                             else
108                             {
109                                 value = row[columnname].ToString().Replace("%", ""); //存在匹配的表头
110                                 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);//赋值操作
111                             }
112                         }
113                     }
114                 }
115                 return obj;
116             }
117             catch
118             {
119                 return obj;
120             }
121         }
122         /// <summary>
123         /// 将泛型集合类转换成DataTable
124         /// </summary>
125         /// <typeparam name="T">集合项类型</typeparam>
126         /// <param name="list">集合</param>
127         /// <param name="propertyName">需要返回的列的列名</param>
128         /// <returns>数据集(表)</returns>
129         public static DataTable ListToDataTable<T>(IList<T> list, params string[] propertyName)
130         {
131             List<string> propertyNameList = new List<string>();
132             if (propertyName != null)
133                 propertyNameList.AddRange(propertyName);
134             DataTable result = new DataTable();
135             if (list != null && list.Count > 0)
136             {
137                 PropertyInfo[] propertys = list[0].GetType().GetProperties();
138                 foreach (PropertyInfo pi in propertys)
139                 {
140                     if (propertyNameList.Count == 0)
141                     {
142                         result.Columns.Add(pi.Name, pi.PropertyType);
143                     }
144                     else
145                     {
146                         if (propertyNameList.Contains(pi.Name))
147                             result.Columns.Add(pi.Name, pi.PropertyType);
148                     }
149                 }
150                 for (int i = 0; i < list.Count; i++)
151                 {
152                     ArrayList tempList = new ArrayList();
153                     foreach (PropertyInfo pi in propertys)
154                     {
155                         if (propertyNameList.Count == 0)
156                         {
157                             object obj = pi.GetValue(list[i], null);
158                             tempList.Add(obj);
159                         }
160                         else
161                         {
162                             if (propertyNameList.Contains(pi.Name))
163                             {
164                                 object obj = pi.GetValue(list[i], null);
165                                 tempList.Add(obj);
166                             }
167                         }
168                     }
169                     object[] array = tempList.ToArray();
170                     result.LoadDataRow(array, true);
171                 }
172             }
173             return result;
174         }
175 
176         #endregion
 #region 清除HTML标记
 2         public static string DropHTML(string Htmlstring)
 3         {
 4             if (string.IsNullOrEmpty(Htmlstring)) return "";
 5             //删除脚本  
 6             Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
 7             //删除HTML  
 8             Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
 9             Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
10             Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
11             Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
12             Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
13             Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
14             Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
15             Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
16             Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
17             Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
18             Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
19             Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
20             Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
21 
22             Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
23             Htmlstring.Replace("<", "");
24             Htmlstring.Replace(">", "");
25             Htmlstring.Replace("\r\n", "");
26             Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
27             return Htmlstring;
28         }
29         #endregion
技术分享



技术分享

帮助类

标签:

原文地址:http://www.cnblogs.com/zhangxiaolei521/p/5808665.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!