DataTable List<T> 互转 扩展方法 Extension Methods


namespace ConsoleApplication
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Xml.Serialization;
    using Microshaoft;
    public class Class1
    {
        //[STAThread]
        [Serializable]
        public class Entry
        {
            [XmlElement("F1")]
            public string F1 { get; set; }
            [XmlElement("F2")]
            public int F2 { get; set; }
            [XmlAttribute("F3")]
            public DateTime F3 { get; set; }
            public DateTime? FF3 { get; set; }
            [XmlArrayItem("Entry2", typeof(Entry2))]
            [XmlArray("Entry2S")]
            public Entry2[] Entry2S { get; set; }
        };
        public class Entry2
        {
            [XmlElement("F1")]
            public string F1 { get; set; }
            [XmlElement("F2")]
            public int F2 { get; set; }
            [XmlAttribute("F3")]
            public DateTime F3 { get; set; }
            public DateTime? FF3 { get; set; }
        };
        static void Main(string[] args)
        {
            var list = new List<Entry>()
                            {
                                new Entry() 
                                    {
                                        F1 = "a"
                                        , F2= 1
                                        , F3 = DateTime.Now
                                        , FF3 = null
                                        , Entry2S = new []
                                                        {
                                                            new Entry2 ()
                                                            {
                                                                F1 = "sadasd"
                                                                , F2 = 10
                                                                , F3 = DateTime.Now
                                                                , FF3 = null
                                                            }
                                                            , new Entry2 ()
                                                            {
                                                                F1 = "sadasd"
                                                                , F2 = 10
                                                                , F3 = DateTime.Now
                                                                , FF3 = DateTime.Now
                                                            }
                                                            , new Entry2 ()
                                                            {
                                                                F1 = "sadasd"
                                                                , F2 = 10
                                                                , F3 = DateTime.Now
                                                            }
                                                        }
                                    }
                                ,new Entry() 
                                    {
                                        F1= "b"
                                        , F2= 2
                                        , F3 = DateTime.Now
                                        , FF3 = null
                                        , Entry2S = new []
                                                    {
                                                        new Entry2 ()
                                                        {
                                                            F1 = "sadasd"
                                                            , F2 = 10
                                                            , F3 = DateTime.Now
                                                        }
                                                        , new Entry2 ()
                                                        {
                                                            F1 = "sadasd"
                                                            , F2 = 10
                                                            , F3 = DateTime.Now
                                                        }
                                                        , new Entry2 ()
                                                        {
                                                            F1 = "sadasd"
                                                            , F2 = 10
                                                            , F3 = DateTime.Now
                                                        }
                                                    }
                                    }
                                ,new Entry() 
                                    {
                                        F1= "c"
                                        , F2= 3
                                        , F3 = DateTime.Now
                                        , FF3 = DateTime.Now
                                        , Entry2S = new []
                                                    {
                                                        new Entry2 ()
                                                        {
                                                            F1 = "sadasd"
                                                            , F2 = 10
                                                            , F3 = DateTime.Now
                                                        }
                                                        , new Entry2 ()
                                                        {
                                                            F1 = "sadasd"
                                                            , F2 = 10
                                                            , F3 = DateTime.Now
                                                        }
                                                        , new Entry2 ()
                                                        {
                                                            F1 = "sadasd"
                                                            , F2 = 10
                                                            , F3 = DateTime.Now
                                                        }
                                                    }
                                    }
                            };
            var dataTable = list.ToDataTable<Entry>();
            var keyWords = new[] { "", "" };
            dataTable = list.AsEnumerable().ToDataTable();
            var l = dataTable.ToList<Entry>();
            l.ForEach
                (
                    (x) =>
                    {
                        x.Entry2S = new[]
                                        {
                                            new Entry2 ()
                                            {
                                                F1 = "sadasd"
                                                , F2 = 10
                                                , F3 = DateTime.Now
                                            }
                                            , new Entry2 ()
                                            {
                                                F1 = "sadasd"
                                                , F2 = 10
                                                , F3 = DateTime.Now
                                            }
                                            , new Entry2 ()
                                            {
                                                F1 = "sadasd"
                                                , F2 = 10
                                                , F3 = DateTime.Now
                                            }
                                        };
                    }
                );
            string xml = SerializerHelper.XmlSerializerObjectToXml<List<Entry>>(l, Encoding.UTF8);
            Console.WriteLine(xml);
            Console.ReadLine();
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Reflection;
    using System.ComponentModel;
    public static class ExtensionMethodsManager
    {
        public static DataRow[] FullTextSearch(this DataTable dataTable, string[] keyWords)
        {
            return
                dataTable.AsEnumerable().Where<DataRow>
                                        (
                                            (x) =>
                                            {
                                                return
                                                        keyWords.All
                                                                (
                                                                    (xx) =>
                                                                    {
                                                                        return
                                                                                 x.ItemArray
                                                                                        .Select
                                                                                            (
                                                                                                (xxx) =>
                                                                                                {
                                                                                                    return xxx.ToString();
                                                                                                }
                                                                                            )
                                                                                        .Any<string>
                                                                                            (
                                                                                                (xxx) =>
                                                                                                {
                                                                                                    return xxx.Contains(xx);
                                                                                                }
                                                                                            );
                                                                    }
                                                                );
                                            }
                                        ).ToArray();
        }
        private static List<Type> _typesWhiteList = new List<Type>()
                                                        {
                                                            typeof(int)
                                                            , typeof(int?)
                                                            , typeof(long)
                                                            , typeof(long?)
                                                            , typeof(string)
                                                            , typeof(DateTime)
                                                            , typeof(DateTime?)
                                                        };
        private class PropertyAccessor
        {
            public Func<object, object> Getter;
            public Action<object, object> Setter;
            public PropertyInfo Property;
        }
        private static Dictionary
                            <
                                Type
                                , Dictionary
                                        <
                                            string
                                            , PropertyAccessor
                                        >
                            > _typesPropertiesAccessors = new Dictionary<Type, Dictionary<string, PropertyAccessor>>();
        private static Dictionary<string, PropertyAccessor> GetTypePropertiesAccessors(Type type)
        {
            var properties = type.GetProperties();
            Dictionary<string, PropertyAccessor> dictionary = null;
            Array.ForEach
                    (
                        properties
                        , (x) =>
                        {
                            if (
                                    _typesWhiteList.Any
                                                    (
                                                        (xx) =>
                                                        {
                                                            return xx == x.PropertyType;
                                                        }
                                                    )
                                )
                            {
                                var accessor = new PropertyAccessor()
                                {
                                    Getter = DynamicPropertyAccessor.CreateGetPropertyValueFunc(type, x.Name)
                                    ,
                                    Setter = DynamicPropertyAccessor.CreateSetPropertyValueAction(type, x.Name)
                                    ,
                                    Property = x
                                };
                                if (dictionary == null)
                                {
                                    dictionary = new Dictionary<string, PropertyAccessor>();
                                }
                                dictionary.Add(x.Name, accessor);
                            }
                        }
                    );
            return dictionary;
        }
        public static DataTable ToDataTable<TEntry>(this IEnumerable<TEntry> ie)
        {
            var type = typeof(TEntry);
            var accessors = GetTypePropertiesAccessors(type);
            var accessorsList = accessors.ToList();
            DataTable dataTable = GenerateEmptyDataTable(accessorsList);
            DataColumnCollection dcc = dataTable.Columns;
            if (dataTable != null)
            {
                using (IEnumerator<TEntry> enumerator = ie.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        var row = dataTable.NewRow();
                        foreach (DataColumn c in dcc)
                        {
                            PropertyAccessor accessor = null;
                            if (accessors.TryGetValue(c.ColumnName, out accessor))
                            {
                                object v = accessor.Getter(enumerator.Current);
                                if (v == null)
                                {
                                    v = DBNull.Value;
                                }
                                row[c] = v;
                            }
                        }
                        dataTable.Rows.Add(row);
                    }
                }
            }
            return dataTable;
        }
        private static DataTable GenerateEmptyDataTable(List<KeyValuePair<string, PropertyAccessor>> accessorsList)
        {
            DataTable dataTable = null;
            accessorsList
                    .ForEach
                        (
                            (x) =>
                            {
                                if (dataTable == null)
                                {
                                    dataTable = new DataTable();
                                }
                                var propertyType = x.Value.Property.PropertyType;
                                if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                                {
                                    NullableConverter nullableConvert = new NullableConverter(propertyType);
                                    propertyType = nullableConvert.UnderlyingType;
                                }
                                var propertyName = x.Value.Property.Name;
                                var column = new DataColumn
                                                    (
                                                        propertyName
                                                        , propertyType
                                                    );
                                dataTable.Columns.Add(column);
                            }
                        );
            return dataTable;
        }
        public static DataTable ToDataTable<TEntry>(this List<TEntry> list)
        // where TEntry : new()
        {
            var type = typeof(TEntry);
            var accessors = GetTypePropertiesAccessors(type);
            var accessorsList = accessors.ToList();
            DataTable dataTable = GenerateEmptyDataTable(accessorsList);
            DataColumnCollection dcc = dataTable.Columns;
            if (dataTable != null)
            {
                list.ForEach
                        (
                            (x) =>
                            {
                                var row = dataTable.NewRow();
                                foreach (DataColumn c in dcc)
                                {
                                    PropertyAccessor accessor = null;
                                    if (accessors.TryGetValue(c.ColumnName, out accessor))
                                    {
                                        object v = accessor.Getter(x);
                                        if (v == null)
                                        { 
                                            v = DBNull.Value;
                                        }
                                        row[c] = v;
                                    }
                                }
                                dataTable.Rows.Add(row);
                            }
                        );
            }
            return dataTable;
        }
        public static List<TEntry> ToList<TEntry>(this DataTable dataTable)
                                            where TEntry : new()
        {
            var type = typeof(TEntry);
            var columns = dataTable.Columns;
            var actions = new Dictionary<string, Action<object, object>>();
            foreach (DataColumn c in columns)
            {
                var columnName = c.ColumnName;
                var action = DynamicPropertyAccessor.CreateSetPropertyValueAction
                                                (
                                                    typeof(TEntry)
                                                    , columnName
                                                );
                actions[columnName] = action;
            }
            List<TEntry> list = null;
            var rows = dataTable.Rows;
            foreach (DataRow r in rows)
            {
                var entry = new TEntry();
                if (list == null)
                {
                    list = new List<TEntry>();
                }
                foreach (DataColumn c in columns)
                {
                    var columnName = c.ColumnName;
                    var v = r[columnName];
                    if (!DBNull.Value.Equals(v))
                    {
                        var action = actions[columnName];
                        action(entry, v);
                    }
                }
                list.Add(entry);
            }
            return list;
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.ComponentModel;
    public class DynamicPropertyAccessor
    {
        private static Assembly GetAssemblyByTypeName(string typeName)
        {
            return AppDomain.CurrentDomain.GetAssemblies().First
                                                        (
                                                            (a) =>
                                                            {
                                                                return a.GetTypes().Any
                                                                                    (
                                                                                        (t) =>
                                                                                        {
                                                                                            return (t.FullName == typeName);
                                                                                        }
                                                                                    );
                                                            }
                                                        );
        }
        public static Func<object, object> CreateGetPropertyValueFunc(string typeName, string propertyName, bool isTypeFromAssembly = false)
        {
            Type type;
            if (isTypeFromAssembly)
            {
                var assembly = GetAssemblyByTypeName(typeName);
                type = assembly.GetType(typeName);
            }
            else
            {
                type = Type.GetType(typeName);
            }
            return CreateGetPropertyValueFunc(type, propertyName);
        }
        public static Func<object, object> CreateGetPropertyValueFunc(Type type, string propertyName)
        {
            var target = Expression.Parameter(typeof(object), "p");
            var castTarget = Expression.Convert(target, type);
            var getPropertyValue = Expression.Property(castTarget, propertyName);
            //Type typeProperty = typeof(object);
            //if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            //{
            //    NullableConverter nullableConvert = new NullableConverter(type);
            //    type = nullableConvert.UnderlyingType;
            //}
            var castPropertyValue = Expression.Convert(getPropertyValue,typeof(object));
            var lambda = Expression.Lambda<Func<object, object>>(castPropertyValue, target);
            return lambda.Compile();
        }
        public static Func<object, TProperty> CreateGetPropertyValueFunc<TProperty>(string typeName, string propertyName, bool isTypeFromAssembly = false)
        {
            Type type;
            if (isTypeFromAssembly)
            {
                var assembly = GetAssemblyByTypeName(typeName);
                type = assembly.GetType(typeName);
            }
            else
            {
                type = Type.GetType(typeName);
            }
            return CreateGetPropertyValueFunc<TProperty>(type, propertyName);
        }
        public static Func<object, TProperty> CreateGetPropertyValueFunc<TProperty>(Type type, string propertyName)
        {
            var target = Expression.Parameter(typeof(object), "p");
            var castTarget = Expression.Convert(target, type);
            var getPropertyValue = Expression.Property(castTarget, propertyName);
            var lambda = Expression.Lambda<Func<object, TProperty>>(getPropertyValue, target);
            return lambda.Compile();
        }
        public static Func<TProperty> CreateGetStaticPropertyValueFunc<TProperty>(string typeName, string propertyName, bool isTypeFromAssembly = false)
        {
            Type type;
            if (isTypeFromAssembly)
            {
                var assembly = GetAssemblyByTypeName(typeName);
                type = assembly.GetType(typeName);
            }
            else
            {
                type = Type.GetType(typeName);
            }
            return CreateGetStaticPropertyValueFunc<TProperty>(type, propertyName);
        }
        public static Func<TProperty> CreateGetStaticPropertyValueFunc<TProperty>(Type type, string propertyName)
        {
            var property = type.GetProperty(propertyName, typeof(TProperty));
            var getPropertyValue = Expression.Property(null, property);
            var lambda = Expression.Lambda<Func<TProperty>>(getPropertyValue, null);
            return lambda.Compile();
        }
        public static Func<object> CreateGetStaticPropertyValueFunc(Type type, string propertyName)
        {
            var property = type.GetProperty(propertyName);
            var getPropertyValue = Expression.Property(null, property);
            var castPropertyValue = Expression.Convert(getPropertyValue, typeof(object));
            var lambda = Expression.Lambda<Func<object>>(castPropertyValue, null);
            return lambda.Compile();
        }
        public static Func<object> CreateGetStaticPropertyValueFunc(string typeName, string propertyName, bool isTypeFromAssembly = false)
        {
            Type type;
            if (isTypeFromAssembly)
            {
                var assembly = GetAssemblyByTypeName(typeName);
                type = assembly.GetType(typeName);
            }
            else
            {
                type = Type.GetType(typeName);
            }
            return CreateGetStaticPropertyValueFunc(type, propertyName);
        }
        public static Action<object, object> CreateSetPropertyValueAction(Type type, string propertyName)
        {
            var property = type.GetProperty(propertyName);
            var target = Expression.Parameter(typeof(object), "p");
            var propertyValue = Expression.Parameter(typeof(object), "p1");
            var castTarget = Expression.Convert(target, type);
            var castPropertyValue = Expression.Convert(propertyValue, property.PropertyType);
            var getSetMethod = property.GetSetMethod();
            if (getSetMethod == null)
            {
                getSetMethod = property.GetSetMethod(true);
            }
            var call = Expression.Call(castTarget, getSetMethod, castPropertyValue);
            var lambda = Expression.Lambda<Action<object, object>>(call, target, propertyValue);
            return lambda.Compile();
        }
        public static Action<object, object> CreateSetPropertyValueAction(string typeName, string propertyName, bool isTypeFromAssembly = false)
        {
            Type type;
            if (isTypeFromAssembly)
            {
                var assembly = GetAssemblyByTypeName(typeName);
                type = assembly.GetType(typeName);
            }
            else
            {
                type = Type.GetType(typeName);
            }
            return CreateSetPropertyValueAction(type, propertyName);
        }
        public static Action<object, TProperty> CreateSetPropertyValueAction<TProperty>(Type type, string propertyName)
        {
            var property = type.GetProperty(propertyName);
            var target = Expression.Parameter(typeof(object), "p");
            var propertyValue = Expression.Parameter(typeof(TProperty), "p1");
            var castTarget = Expression.Convert(target, type);
            var castPropertyValue = Expression.Convert(propertyValue, property.PropertyType);
            var getSetMethod = property.GetSetMethod();
            if (getSetMethod == null)
            {
                getSetMethod = property.GetSetMethod(true);
            }
            var call = Expression.Call(castTarget, getSetMethod, castPropertyValue);
            var lambda = Expression.Lambda<Action<object, TProperty>>(call, target, propertyValue);
            return lambda.Compile();
        }
        public static Action<object, TProperty> CreateSetPropertyValueAction<TProperty>(string typeName, string propertyName, bool isTypeFromAssembly = false)
        {
            Type type;
            if (isTypeFromAssembly)
            {
                var assembly = GetAssemblyByTypeName(typeName);
                type = assembly.GetType(typeName);
            }
            else
            {
                type = Type.GetType(typeName);
            }
            return CreateSetPropertyValueAction<TProperty>(type, propertyName);
        }
        public static Action<object> CreateSetStaticPropertyValueAction(Type type, string propertyName)
        {
            var property = type.GetProperty(propertyName);
            var propertyValue = Expression.Parameter(typeof(object), "p");
            var castPropertyValue = Expression.Convert(propertyValue, property.PropertyType);
            var getSetMethod = property.GetSetMethod();
            if (getSetMethod == null)
            {
                getSetMethod = property.GetSetMethod(true);
            }
            var call = Expression.Call(null, getSetMethod, castPropertyValue);
            var lambda = Expression.Lambda<Action<object>>(call, propertyValue);
            return lambda.Compile();
        }
        public static Action<object> CreateSetStaticPropertyValueAction(string typeName, string propertyName, bool isTypeFromAssembly = false)
        {
            Type type;
            if (isTypeFromAssembly)
            {
                var assembly = GetAssemblyByTypeName(typeName);
                type = assembly.GetType(typeName);
            }
            else
            {
                type = Type.GetType(typeName);
            }
            return CreateSetStaticPropertyValueAction(type, propertyName);
        }
        public static Action<TProperty> CreateSetStaticPropertyValueAction<TProperty>(Type type, string propertyName)
        {
            var property = type.GetProperty(propertyName);
            var propertyValue = Expression.Parameter(typeof(TProperty), "p");
            //var castPropertyValue = Expression.Convert(propertyValue, property.PropertyType);
            var getSetMethod = property.GetSetMethod();
            if (getSetMethod == null)
            {
                getSetMethod = property.GetSetMethod(true);
            }
            var call = Expression.Call(null, getSetMethod, propertyValue);
            var lambda = Expression.Lambda<Action<TProperty>>(call, propertyValue);
            return lambda.Compile();
        }
        public static Action<TProperty> CreateSetStaticPropertyValueAction<TProperty>(string typeName, string propertyName, bool isTypeFromAssembly = false)
        {
            Type type;
            if (isTypeFromAssembly)
            {
                var assembly = GetAssemblyByTypeName(typeName);
                type = assembly.GetType(typeName);
            }
            else
            {
                type = Type.GetType(typeName);
            }
            return CreateSetStaticPropertyValueAction<TProperty>(type, propertyName);
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Runtime.Serialization.Formatters.Soap;
    public static class SerializerHelper
    {
        public static T XmlSerializerXmlToObject<T>(string Xml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T Object = XmlSerializerXmlToObject<T>(Xml, serializer);
            return Object;
        }
        public static T XmlSerializerXmlToObject<T>(string Xml, XmlSerializer serializer)
        {
            StringReader stringReader = new StringReader(Xml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            return (T)serializer.Deserialize(xmlReader);
        }
        public static string XmlSerializerObjectToXml<T>
                                    (
                                        T Object
                                        , XmlTextWriter writer
                                        , XmlSerializer serializer
                                    )
        {
            serializer.Serialize(writer, Object);
            MemoryStream stream = writer.BaseStream as MemoryStream;
            byte[] bytes = stream.ToArray();
            Encoding e = EncodingHelper.IdentifyEncoding
                                            (
                                                bytes
                                                , Encoding.GetEncoding("gb2312")
                ///                                                , new Encoding[]
                ///                                                        {
                ///                                                            Encoding.UTF8
                ///                                                            , Encoding.Unicode
                ///                                                        }
                                            );
            byte[] buffer = e.GetPreamble();
            int offset = buffer.Length;
            buffer = new byte[bytes.Length - offset];
            Buffer.BlockCopy(bytes, offset, buffer, 0, buffer.Length);
            string s = e.GetString(buffer);
            return s;
        }
        public static string XmlSerializerObjectToXml<T>(T Object, XmlSerializer serializer)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                Encoding e = Encoding.UTF8;
                XmlTextWriter writer = new XmlTextWriter(stream, e);
                string s = XmlSerializerObjectToXml<T>
                                    (
                                        Object
                                        , writer
                                        , serializer
                                    );
                writer.Close();
                writer = null;
                return s;
            }
        }
        public static string XmlSerializerObjectToXml<T>(T Object, Encoding e, XmlSerializer serializer)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlTextWriter writer = new XmlTextWriter(stream, e);
                string s = XmlSerializerObjectToXml<T>
                                    (
                                        Object
                                        , writer
                                        , serializer
                                    );
                writer.Close();
                writer = null;
                return s;
            }
        }
        public static string XmlSerializerObjectToXml<T>(T Object, Encoding e)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                XmlTextWriter writer = new XmlTextWriter(stream, e);
                string s = XmlSerializerObjectToXml<T>
                                    (
                                        Object
                                        , writer
                                        , serializer
                                    );
                writer.Close();
                writer = null;
                return s;
            }
        }
        public static string DataContractSerializerObjectToXml<T>(T Object, DataContractSerializer serializer)
        {
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, Object);
            byte[] buffer = StreamDataHelper.ReadDataToBytes(ms);
            string xml = Encoding.UTF8.GetString(buffer);
            ms.Close();
            ms.Dispose();
            ms = null;
            return xml;
        }
        public static string DataContractSerializerObjectToXml<T>(T Object)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            string xml = DataContractSerializerObjectToXml<T>(Object, serializer);
            return xml;
        }
        public static T DataContractSerializerXmlToObject<T>(string Xml, DataContractSerializer serializer)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(Xml);
            MemoryStream ms = new MemoryStream(buffer);
            //ms.Position = 0;
            T Object = (T)serializer.ReadObject(ms);
            ms.Close();
            ms.Dispose();
            ms = null;
            return Object;
        }
        public static T DataContractSerializerXmlToObject<T>(string Xml)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            byte[] buffer = Encoding.UTF8.GetBytes(Xml);
            MemoryStream ms = new MemoryStream(buffer);
            //ms.Position = 0;
            T Object = (T)serializer.ReadObject(ms);
            ms.Close();
            ms.Dispose();
            ms = null;
            return Object;
        }
        public static string FormatterObjectToSoap<T>
                             (
                                 T Object
                             )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                SoapFormatter formatter = new SoapFormatter();
                formatter.Serialize(stream, Object);
                string soap = Encoding.UTF8.GetString(stream.GetBuffer());
                return soap;
            }
        }
        public static T FormatterSoapToObject<T>
                                    (
                                        string soap
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                SoapFormatter formater = new SoapFormatter();
                byte[] data = Encoding.UTF8.GetBytes(soap);
                stream.Write(data, 0, data.Length);
                stream.Position = 0;
                T Object = (T)formater.Deserialize(stream);
                return Object;
            }
        }
        public static byte[] FormatterObjectToBinary<T>
                                    (
                                        T Object
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(stream, Object);
                byte[] buffer = stream.ToArray();
                return buffer;
            }
        }
        public static string DataContractSerializerObjectToJson<T>(T Object)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            string json = DataContractSerializerObjectToJson<T>(Object);
            return json;
        }
        public static string DataContractSerializerObjectToJson<T>(T Object, DataContractJsonSerializer serializer)
        {
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, Object);
            string json = Encoding.UTF8.GetString(ms.GetBuffer());
            ms.Close();
            ms.Dispose();
            ms = null;
            return json;
        }
        public static T DataContractSerializerJsonToObject<T>(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T Object = DataContractSerializerJsonToObject<T>(json, serializer);
            return Object;
        }
        public static T DataContractSerializerJsonToObject<T>(string json, DataContractJsonSerializer serializer)
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            T Object = (T)serializer.ReadObject(ms);
            ms.Close();
            ms.Dispose();
            ms = null;
            return Object;
        }
    }
}
namespace Microshaoft
{
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    public static class EncodingHelper
    {
        public static Encoding IdentifyEncoding
                                    (
                                        Stream stream
                                        , Encoding defaultEncoding
                                        , Encoding[] identifyEncodings
                                    )
        {
            byte[] data = StreamDataHelper.ReadDataToBytes(stream);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                            , identifyEncodings
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        Stream stream
                                        , Encoding defaultEncoding
                                    )
        {
            byte[] data = StreamDataHelper.ReadDataToBytes(stream);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        byte[] data
                                        , Encoding defaultEncoding
                                    )
        {
            EncodingInfo[] encodingInfos = Encoding.GetEncodings();
            List<Encoding> list = new List<Encoding>();
            foreach (EncodingInfo info in encodingInfos)
            {
                Encoding e = info.GetEncoding();
                if (e.GetPreamble().Length > 0)
                {
                    list.Add(e);
                    //System.Console.WriteLine(e.EncodingName);
                }
            }
            Encoding[] encodings = new Encoding[list.Count];
            list.CopyTo(encodings);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                            , encodings
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        byte[] data
                                        , Encoding defaultEncoding
                                        , Encoding[] identifyEncodings
                                    )
        {
            Encoding encoding = defaultEncoding;
            foreach (Encoding e in identifyEncodings)
            {
                byte[] buffer = e.GetPreamble();
                int l = buffer.Length;
                if (l == 0)
                {
                    continue;
                }
                bool flag = false;
                for (int i = 0; i < l; i++)
                {
                    if (buffer[i] != data[i])
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    continue;
                }
                else
                {
                    encoding = e;
                }
            }
            return encoding;
        }
    }
}
namespace Microshaoft
{
    using System.IO;
    public static class StreamDataHelper
    {
        public static byte[] ReadDataToBytes(Stream stream)
        {
            byte[] buffer = new byte[64 * 1024];
            MemoryStream ms = new MemoryStream();
            int r = 0;
            int l = 0;
            long position = -1;
            if (stream.CanSeek)
            {
                position = stream.Position;
                stream.Position = 0;
            }
            while (true)
            {
                r = stream.Read(buffer, 0, buffer.Length);
                if (r > 0)
                {
                    l += r;
                    ms.Write(buffer, 0, r);
                }
                else
                {
                    break;
                }
            }
            byte[] bytes = new byte[l];
            ms.Position = 0;
            ms.Read(bytes, 0, (int)l);
            ms.Close();
            ms.Dispose();
            ms = null;
            if (position >= 0)
            {
                stream.Position = position;
            }
            return bytes;
        }
    }
}

posted @ 2012-08-16 20:25  于斯人也  阅读(799)  评论(0编辑  收藏  举报