1 using System;
2 using System.Collections.Generic;
3 using System.Data;
4 using System.IO;
5 using System.Linq;
6 using System.Reflection;
7 using System.Runtime.Serialization.Formatters.Binary;
8 using System.Text;
9 using System.Text.RegularExpressions;
10 using System.Xml;
11 using System.Xml.Linq;
12 using System.Xml.Serialization;
13
14 namespace FrameWork.Utilities.Extension
15 {
16 /// <summary>
17 /// 常用枚举
18 /// </summary>
19 public static class HibityExtension
20 {
21 #region 第一天最后一天
22
23 /// <summary>
24 /// 第一天
25 /// </summary>
26 /// <param name="current"></param>
27 /// <returns></returns>
28 public static DateTime First(this DateTime current)
29 {
30 var first = current.AddDays(1 - current.Day);
31 return first;
32 }
33
34 /// <summary>
35 /// 最后一天
36 /// </summary>
37 /// <param name="current"></param>
38 /// <returns></returns>
39 public static DateTime Last(this DateTime current)
40 {
41 var daysInMonth = DateTime.DaysInMonth(current.Year, current.Month);
42 var last = current.First().AddDays(daysInMonth - 1);
43 return last;
44 }
45
46 #endregion
47
48 #region 字符串是否为空
49
50 /// <summary>
51 /// 字符串是否为空
52 /// </summary>
53 /// <param name="s"></param>
54 /// <returns></returns>
55 public static bool IsEmpty(this string s)
56 {
57 return string.IsNullOrWhiteSpace(s);
58 }
59
60 #endregion
61
62 #region 将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式
63
64 /// <summary>
65 /// 将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。
66 /// </summary>
67 /// <param name="format"></param>
68 /// <param name="args"></param>
69 /// <returns></returns>
70 public static string FormatWith(this string format, params object[] args)
71 {
72 return string.Format(format, args);
73 }
74
75 #endregion
76
77 #region 指示所指定的正则表达式在指定的输入字符串中是否找到了匹配项
78
79 /// <summary>
80 /// 指示所指定的正则表达式在指定的输入字符串中是否找到了匹配项。
81 /// </summary>
82 /// <param name="s"></param>
83 /// <param name="pattern"></param>
84 /// <returns></returns>
85 public static bool IsMatch(this string s, string pattern)
86 {
87 return s != null && Regex.IsMatch(s, pattern);
88 }
89
90 #endregion
91
92 #region 验证邮箱
93
94 /// <summary>
95 /// 验证邮箱
96 /// </summary>
97 /// <param name="source"></param>
98 /// <returns></returns>
99 public static bool IsEmail(string source)
100 {
101 return Regex.IsMatch(source,
102 @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$",
103 RegexOptions.IgnoreCase);
104 }
105
106 #endregion
107
108 #region String True Or False 转 bool
109
110 public static bool ToBool(this string value)
111 {
112 if (string.IsNullOrWhiteSpace(value)) return false;
113 return value.ToLower() == "true";
114 }
115
116 #endregion
117
118 #region 比较字符串
119
120 /// <summary>
121 /// 比较两个字符串在忽略大小写的情况下是否相等
122 /// </summary>
123 /// <param name="value">字符串1</param>
124 /// <param name="compareTo">要比较的字符串</param>
125 /// <returns>是否相等</returns>
126 public static bool IsIgnoreCaseEqualTo(this string value, string compareTo)
127 {
128 return string.Compare(value, compareTo, StringComparison.OrdinalIgnoreCase) == 0;
129 }
130
131 #endregion
132
133 #region String.Join
134
135 /// <summary>
136 /// using the specified separator between each
137 /// </summary>
138 /// <param name="source"></param>
139 /// <param name="separator"></param>
140 /// <returns></returns>
141 public static string Join(this IEnumerable<string> source, string separator)
142 {
143 return string.Join(separator, source);
144 }
145
146 #endregion
147
148 #region string转枚举对象
149
150 /// <summary>
151 /// string转枚举对象
152 /// </summary>
153 /// <typeparam name="T"></typeparam>
154 /// <param name="value"></param>
155 /// <returns></returns>
156 public static T ToEnum<T>(this string value)
157 where T : struct
158 {
159 return (T) Enum.Parse(typeof (T), value, true);
160 }
161
162 #endregion
163
164 #region MD5
165
166 /// <summary>
167 /// 计算指定字符串的MD5值
168 /// </summary>
169 /// <param name="key">要计算Hash的字符串</param>
170 /// <returns>字符串的Hash</returns>
171 public static string MD5(this string key)
172 {
173 return key.MD5(Encoding.UTF8);
174 }
175
176 /// <summary>
177 /// 计算指定字符串的MD5值
178 /// </summary>
179 /// <param name="key">要计算Hash的字符串</param>
180 /// <param name="encoding">计算Hash的编码方法</param>
181 /// <returns>字符串的Hash</returns>
182 public static string MD5(this string key, string encoding)
183 {
184 return key.MD5(Encoding.GetEncoding(encoding));
185 }
186
187 /// <summary>
188 /// 计算指定字符串的MD5值
189 /// </summary>
190 /// <param name="key">要计算Hash的字符串</param>
191 /// <param name="encoding">计算Hash的编码方法</param>
192 /// <returns>字符串的Hash</returns>
193 public static string MD5(this string key, Encoding encoding)
194 {
195 if (key == null) throw new ArgumentNullException();
196
197 var md5 = System.Security.Cryptography.MD5.Create();
198 var has = md5.ComputeHash(encoding.GetBytes(key));
199 return BitConverter.ToString(has).Replace("-", "").ToUpper();
200 }
201
202 #endregion
203
204 #region 枚举转list对象
205
206 public static List<T> EnumToList<T>()
207 {
208 var enumType = typeof (T);
209
210 // Can't use type constraints on value types, so have to do check like this
211 if (enumType.BaseType != typeof (Enum))
212 throw new ArgumentException("T must be of type System.Enum");
213
214 var enumValArray = Enum.GetValues(enumType);
215
216 var enumValList = new List<T>(enumValArray.Length);
217 enumValList.AddRange(from int val in enumValArray select (T) Enum.Parse(enumType, val.ToString()));
218 return enumValList;
219 }
220
221 #endregion
222
223 #region 枚举转字典对象
224
225 public static IDictionary<string, int> EnumToDictionary(this Type t)
226 {
227 if (t == null) throw new NullReferenceException();
228 if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");
229
230 var names = Enum.GetNames(t);
231 var values = Enum.GetValues(t);
232
233 return (from i in Enumerable.Range(0, names.Length)
234 select new {Key = names[i], Value = (int) values.GetValue(i)})
235 .ToDictionary(k => k.Key, k => k.Value);
236 }
237
238 #endregion
239
240 #region 序列化反序列化xml
241
242 /// <summary>
243 /// 序列化成UTF8 格式的无命名空间的xml
244 /// </summary>
245 /// <param name="root"></param>
246 /// <returns></returns>
247 public static string ToXml<T>(this T root) where T : new()
248 {
249 var stream = new MemoryStream();
250 var xml = new XmlSerializer(typeof (T));
251 var xwriter = new XmlTextWriter(stream, Encoding.UTF8);
252 //Create our own namespaces for the output
253 var ns = new XmlSerializerNamespaces();
254 //Add an empty namespace and empty value
255 ns.Add("", "");
256 try
257 {
258 //序列化对象
259 xml.Serialize(xwriter, root, ns);
260 }
261 catch (InvalidOperationException)
262 {
263 throw;
264 }
265 stream.Position = 0;
266 var sr = new StreamReader(stream);
267 var str = sr.ReadToEnd();
268 sr.Dispose();
269 stream.Dispose();
270 return str;
271 }
272
273 /// <summary>
274 /// 反序列成对象
275 /// </summary>
276 /// <param name="xml">xml</param>
277 /// <returns></returns>
278 public static object FromXml<T>(this string xml) where T : new()
279 {
280 using (var sr = new StringReader(xml))
281 {
282 var xmldes = new XmlSerializer(typeof (T));
283 return (T) xmldes.Deserialize(sr);
284 }
285 }
286
287 public static T Deserialize<T>(this XDocument xmlDocument)
288 {
289 var xmlSerializer = new XmlSerializer(typeof (T));
290 using (var reader = xmlDocument.CreateReader())
291 return (T) xmlSerializer.Deserialize(reader);
292 }
293
294 #endregion
295
296 #region DataTable转list ,list 转DataTable
297
298 public static DataTable ToDataTable<T>(this IEnumerable<T> varlist)
299 {
300 var dtReturn = new DataTable();
301 // column names
302 PropertyInfo[] oProps = null;
303 if (varlist == null) return dtReturn;
304 foreach (var rec in varlist)
305 {
306 // Use reflection to get property names, to create table, Only first time, others will follow
307 if (oProps == null)
308 {
309 oProps = rec.GetType().GetProperties();
310 foreach (var pi in oProps)
311 {
312 var colType = pi.PropertyType;
313 if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof (Nullable<>)))
314 {
315 colType = colType.GetGenericArguments()[0];
316 }
317 dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
318 }
319 }
320 var dr = dtReturn.NewRow();
321 foreach (var pi in oProps)
322 {
323 dr[pi.Name] = pi.GetValue(rec, null) ?? DBNull.Value;
324 }
325 dtReturn.Rows.Add(dr);
326 }
327 return dtReturn;
328 }
329
330 public static List<T> ToList<T>(this DataTable table) where T : class, new()
331 {
332 try
333 {
334 var list = new List<T>();
335
336 foreach (var row in table.AsEnumerable())
337 {
338 var obj = new T();
339
340 foreach (var prop in obj.GetType().GetProperties())
341 {
342 try
343 {
344 var propertyInfo = obj.GetType().GetProperty(prop.Name);
345 propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType),
346 null);
347 }
348 catch
349 {
350 ;
351 }
352 }
353
354 list.Add(obj);
355 }
356
357 return list;
358 }
359 catch
360 {
361 return null;
362 }
363 }
364
365 #endregion
366
367 #region int类型比较
368
369 public static bool Between<T>(this T me, T lower, T upper) where T : IComparable<T>
370 {
371 return me.CompareTo(lower) >= 0 && me.CompareTo(upper) < 0;
372 }
373
374 public static T Max<T>(T value1, T value2) where T : IComparable
375 {
376 return value1.CompareTo(value2) > 0 ? value1 : value2;
377 }
378
379 public static decimal PercentOf(this double position, int total)
380 {
381 decimal result = 0;
382 if (position > 0 && total > 0)
383 result = (decimal) position/total*100;
384 return result;
385 }
386
387 public static decimal? ToDecimal(this object obj)
388 {
389 decimal result = 0;
390 if (obj == null) return null;
391
392 if (decimal.TryParse(obj.ToString(), out result))
393 return result;
394 return null;
395 }
396
397 #endregion
398
399 #region 克隆一个对象
400
401 /// <summary>
402 /// 克隆一个对象
403 /// </summary>
404 /// <typeparam name="T"></typeparam>
405 /// <param name="item"></param>
406 /// <returns></returns>
407 public static T Clone<T>(this object item)
408 {
409 if (item == null) return default(T);
410 var formatter = new BinaryFormatter();
411 var stream = new MemoryStream();
412 formatter.Serialize(stream, item);
413 stream.Seek(0, SeekOrigin.Begin);
414 var result = (T) formatter.Deserialize(stream);
415 stream.Close();
416 return result;
417 }
418
419 #endregion
420
421 #region 转换成指定类型的对象
422
423 public static T To<T>(this IConvertible value)
424 {
425 try
426 {
427 var t = typeof (T);
428 var u = Nullable.GetUnderlyingType(t);
429
430 if (u != null)
431 {
432 if (value == null || value.Equals(""))
433 return default(T);
434
435 return (T) Convert.ChangeType(value, u);
436 }
437 if (value == null || value.Equals(""))
438 return default(T);
439
440 return (T) Convert.ChangeType(value, t);
441 }
442
443 catch
444 {
445 return default(T);
446 }
447 }
448
449 #endregion
450 }
451 }