随笔
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml;
using System.Xml.Serialization;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using Accessibility;
namespace System
{
using OEP.Model;
using System.Configuration;
using System.Web;
using System.Collections;
using System.Reflection;
/// <summary>
///Extension method
/// </summary>
public static class Extension
{
/// <summary>
/// Toes the int32.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <remarks></remarks>
public static int ToInt32(this object value)
{
if (value == null)
{
return -1;
}
int result;
bool b = int.TryParse(value.ToString(), out result);
return result;
}
public static char ToChar(this object value)
{
char c;
char.TryParse(value.ToString(), out c);
return c;
}
public static double ToDouble(this object value)
{
double d;
double.TryParse(value.ToString(), out d);
return d;
}
public static Decimal ToDecimal(this object value)
{
Decimal d;
Decimal.TryParse(value.ToString(), out d);
return d;
}
/// <summary>
/// Toes the date time.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <remarks></remarks>
public static DateTime ToDateTime(this object value)
{
if (value == null)
{
return DateTime.MinValue;
}
DateTime result;
bool b = DateTime.TryParse(value.ToString(), out result);
return result;
}
/// <summary>
/// Toes the json.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">The obj.</param>
/// <returns></returns>
/// <remarks></remarks>
public static string ToJson<T>(this T obj)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
jsSerializer.MaxJsonLength = 10240 * 10240;
return jsSerializer.Serialize(obj);
}
/// <summary>
/// Toes the obj.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json">The json.</param>
/// <returns></returns>
/// <remarks></remarks>
public static T ToObj<T>(this string json)
where T : class
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
jsSerializer.MaxJsonLength = 102400;
return jsSerializer.Deserialize<T>(json);
}
const string KEY_64 = "VavicApp";
const string IV_64 = "VavicApp";
/// <summary>
/// Encodes the specified data.
/// </summary>
/// <param name="data">The data.</param>
/// <returns>string</returns>
/// <remarks></remarks>
public static string Encode(this string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
/// <summary>
/// Decodes the specified data.
/// </summary>
/// <param name="data">The data.</param>
/// <returns>string</returns>
/// <remarks></remarks>
public static string Decode(this string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst);
return sr.ReadToEnd();
}
/// <summary>
/// Format Date time To string (yy年mm月dd日)
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <remarks></remarks>
public static string DatetimeFormat(this DateTime value)
{
string result = string.Empty;
string year = value.Year.ToString();
string month = value.Month.ToString();
string day = value.Day.ToString();
result = year + "年" + month + "月" + day + "日";
return result;
}
/// <summary>
/// Toes the XML.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static string ToXml<T>(this T obj)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
string xml = string.Empty;
using (Stream stream = new MemoryStream())
{
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = Formatting.None;
xmlSerializer.Serialize(writer, obj);
stream.Position = 0;
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
reader.Close();
}
writer.Close();
xml = sb.ToString();
}
return xml;
}
public static string ToXml1<T>(this T obj)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
string xml = string.Empty;
using (Stream stream = new MemoryStream())
{
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = Formatting.None;
xmlSerializer.Serialize(writer, obj);
stream.Position = 0;
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
reader.Close();
}
writer.Close();
xml = sb.ToString();
}
string s = xml;
return xml;
}
/// <summary>
/// Toes the SGV XML.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">The obj.</param>
/// <returns></returns>
/// <remarks></remarks>
public static string ToSGVXml<T>(this T obj)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
string xml = string.Empty;
using (Stream stream = new MemoryStream())
{
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = Formatting.None;
xmlSerializer.Serialize(writer, obj);
stream.Position = 0;
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
reader.Close();
}
writer.Close();
xml = sb.ToString();
}
return xml;
}
/// <summary>
/// XMLs to.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml">The XML.</param>
/// <returns></returns>
public static T XmlTo<T>(this string xml)
{
StringReader sr = new StringReader(xml);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(sr);
}
/// <summary>
/// Dates the time compare to.
/// </summary>
/// <param name="d1">The d1.</param>
/// <param name="d2">The d2.</param>
/// <returns></returns>
public static bool DateTimeCompareTo(this DateTime d1, DateTime d2)
{
bool b = false;
TimeSpan ts = d1 - d2;
b = ts.Ticks > 0;
return b;
}
/// <summary>
/// Toes the byte.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static byte ToByte(this object value)
{
byte result = 0;
byte.TryParse(value.ToString(), out result);
return result;
}
/// <summary>
/// Eaches the specified list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="DO">The DO.</param>
public static void Each<T>(this IEnumerable<T> list, Do<T> DO)
{
foreach (T e in list)
{
DO(e);
}
}
/// <summary>
/// Filters the specified list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="condi">The condi.</param>
/// <returns>List<T></returns>
public static IEnumerable<T> Filter<T>(this IEnumerable<T> list, Condi<T> condi)
{
List<T> newlist = new List<T>();
foreach (T e in list)
{
if (condi(e))
{
newlist.Add(e);
}
}
return newlist;
}
public static DataTable ToDataTalbe(this List<BS_OrderModel> list)
{
//取得 UsersAttribute類別中的成員名稱和屬性型別
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(BS_OrderModel));
DataTable dt = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
dt.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (BS_OrderModel item in list)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
} dt.Rows.Add(values);
}
return dt;
}
public static string CheckGuding(this string value)
{
if (value == null)
{
return string.Empty;
}
return value.Substring(10, 2).Equals("00") ? "0" : "1";
}
public static string OutXmlText(this DataTable tdt, string SqlTableName)
{
if (tdt == null)
{
return "";
}
else
{
string strXML = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r";
strXML += "<SGV allcount=\"" + tdt.TableName + "\">\r";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LanguageListColumnsXML"].ToString()));
for (int ri = -1; ri < tdt.Rows.Count; ri++)
{
strXML += "<Table>\r";
for (int ci = 0; ci < tdt.Columns.Count; ci++)
{
if (ri == -1)
{
strXML += "<" + tdt.Columns[ci].ColumnName + " ob=\"" + ReadXmlNode(xmldoc, "OEP/" + SqlTableName + "/" + tdt.Columns[ci].ColumnName, "ob") + "\">" + ReadXmlNode(xmldoc, "OEP/" + SqlTableName + "/" + tdt.Columns[ci].ColumnName) + "</" + tdt.Columns[ci].ColumnName + ">\r";
}
else
{
strXML += "<" + tdt.Columns[ci].ColumnName + ">" + tdt.Rows[ri][ci].ToString().Trim() + "</" + tdt.Columns[ci].ColumnName + ">\r";
}
}
strXML += "</Table>\r";
}
strXML += "</SGV>";
return strXML;
}
}
public static string OutXmlText(this DataTable tdt, int dataCount)
{
if (tdt == null)
{
return "";
}
else
{
string strXML = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r";
strXML += "<SGV allcount=\"" + dataCount.ToString() + "\">\r";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LanguageListColumnsXML"].ToString()));
for (int ri = -1; ri < tdt.Rows.Count; ri++)
{
strXML += "<Table>\r";
for (int ci = 0; ci < tdt.Columns.Count; ci++)
{
if (ri == -1)
{
strXML += "<" + tdt.Columns[ci].ColumnName + " ob=\"" + ReadXmlNode(xmldoc, "OEP/" + dataCount.ToString() + "/" + tdt.Columns[ci].ColumnName, "ob") + "\">" + ReadXmlNode(xmldoc, "OEP/" + dataCount.ToString() + "/" + tdt.Columns[ci].ColumnName) + "</" + tdt.Columns[ci].ColumnName + ">\r";
}
else
{
strXML += "<" + tdt.Columns[ci].ColumnName + ">" + tdt.Rows[ri][ci].ToString().Trim() + "</" + tdt.Columns[ci].ColumnName + ">\r";
}
}
strXML += "</Table>\r";
}
strXML += "</SGV>";
return strXML;
}
}
public static string ReadXmlNode(XmlDocument XmlDoc, string NodeName, string NodeAttribute)
{
if (XmlDoc.ChildNodes.Count < 1)
{
return "";
}
else
{
XmlNode txn = XmlDoc.SelectSingleNode(NodeName);
if (txn == null)
{
return "";
}
else
{
if (txn.Attributes[NodeAttribute] != null)
{
return txn.Attributes[NodeAttribute].Value;
}
else
{
return "";
}
}
}
}
public static string ReadXmlNode(XmlDocument XmlDoc, string NodeName)
{
if (XmlDoc.ChildNodes.Count < 1)
{
return null;
}
else
{
XmlNode txn = XmlDoc.SelectSingleNode(NodeName);
if (txn == null)
{
return null;
}
else
{
return txn.InnerText;
}
}
}
public static string ReadXmlNode(XmlDocument XmlDoc, string NodeName, string strkey, string strvalue)
{
if (XmlDoc.ChildNodes.Count < 1)
{
return "";
}
else
{
XmlNode txn = XmlDoc.SelectSingleNode(NodeName);
if (txn == null)
{
return "";
}
else
{
string t_text = "";
if (strkey + "" != "")
{
for (int ti = 0; ti < txn.ChildNodes.Count; ti++)
{
if (txn.ChildNodes[ti].Attributes[strkey].Value == strvalue)
{
t_text = txn.ChildNodes[ti].InnerText;
break;
}
}
}
else
{
t_text = txn.InnerText;
}
return t_text;
}
}
}
public static object DefaultValue(this Type targetType)
{
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
/// <summary>
/// Subs the array.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="length">The length.</param>
/// <returns></returns>
/// <remarks></remarks>
public static Array SubArray(this Array source, Int32 startIndex, Int32 length)
{
if (startIndex < 0 || startIndex > source.Length || length < 0)
{
throw new ArgumentOutOfRangeException();
}
Array Destination;
if (startIndex + length <= source.Length)
{
Destination = Array.CreateInstance(source.GetType(), length);
Array.Copy(source, startIndex, Destination, 0, length);
}
else
{
Destination = Array.CreateInstance(source.GetType(), source.Length - startIndex);
Array.Copy(source, startIndex, Destination, 0, source.Length - startIndex);
}
return Destination;
}
/// <summary>
/// Toes the list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt">The dt.</param>
/// <returns></returns>
/// <remarks></remarks>
public static List<T> ToList<T>(this DataTable dt) where T : new()
{
List<T> result = new List<T>();
Type t = typeof(T);
foreach (DataRow item in dt.Rows)
{
var itemResult = new T { };
PropertyInfo[] ts = t.GetProperties();
foreach (PropertyInfo i in ts)
{
if (item[i.Name] == DBNull.Value)
{
continue;
}
i.SetValue(itemResult, item[i.Name], null);
}
result.Add(itemResult);
}
return result;
}
public static DataTable ToDataTable<T>(this IEnumerable<T> list) where T : class, new()
{
DataTable dt = new DataTable();
DataColumn column;
DataRow row;
Type t = typeof(T);
T t1 = new T { };
PropertyInfo[] ts = t.GetProperties();
foreach (PropertyInfo item in ts)
{
string typeName = string.Empty;
if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type columnType = item.PropertyType.GetGenericArguments()[0];
typeName = columnType.FullName;
}
else
{
typeName = item.PropertyType.FullName;
}
column = new DataColumn();
column.DataType = Type.GetType(typeName);
column.ColumnName = item.Name;
dt.Columns.Add(column);
}
foreach (T item in list)
{
row = dt.NewRow();
foreach (PropertyInfo item1 in ts)
{
row[item1.Name] = item1.GetValue(item, null);
}
dt.Rows.Add(row);
row = null;
}
return dt;
}
public static List<T> SubList<T>(this IEnumerable<T> list, int startIndex, int count)
{
int allCount = list.Count();
count = allCount - startIndex - count > 0 ? count : allCount;
List<T> oldList = list.ToList();
List<T> newList = new List<T>();
for (int i = startIndex; i < count; i++)
{
newList.Add(oldList[i]);
}
return newList;
}
/// <summary>
/// Transes the specified list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="K"></typeparam>
/// <param name="list">The list.</param>
/// <param name="tran">The tran.</param>
/// <returns>List<K></returns>
/// <remarks></remarks>
public static List<K> Trans<T, K>(List<T> list, Transto<T, K> tran)
{
List<K> newlist = new List<K>();
foreach (T e in list)
{
newlist.Add(tran(e));
}
return newlist;
}
/// <summary>
/// Adds the list item.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listValue">The list value.</param>
/// <returns></returns>
/// <remarks></remarks>
public static long AddListItem<T>(this IEnumerable<T> listValue) where T : struct
{
long l = 0;
foreach (T item in listValue)
{
long temp = Convert.ToInt64(item);
l += temp;
}
return l;
}
public static string GetMd5Code(this string value)
{
string result = string.Empty;
MD5CryptoServiceProvider aMD5CSP = new MD5CryptoServiceProvider();
Byte[] aHashTable = aMD5CSP.ComputeHash(Encoding.ASCII.GetBytes(value));
result = System.BitConverter.ToString(aHashTable).Replace("-", "");
return result;
}
public static string GetFileMd5Code(this string filepath)
{
FileStream aFs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
System.Security.Cryptography.MD5CryptoServiceProvider aMD5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] aHashTable = aMD5CSP.ComputeHash(aFs);
string aMD5Code = System.BitConverter.ToString(aHashTable).Replace("-", "");
return aMD5Code;
}
#region Delegate method
public delegate bool Condi<T>(T ele);
public delegate void Do<T>(T e);
public delegate K Transto<T, K>(T ele);
#endregion
}
}