UtilityHelper DbHelper

发布时间 2023-06-10 17:12:55作者: 宁静致远.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;

namespace IOS.DBUtility
{
    public class UtilityHelper
    {
        /// <summary>
        /// 深度复制对象,被复制对象必须是可序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="RealObject"></param>
        /// <returns></returns>
        public static T Clone<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }

        }

        /// <summary>
        /// 将实体转换成具有相同结构的DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model">要转换的实体</param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(T model)
        {
            //检查实体集合不能为空
            if (model == null)
            {
                throw new Exception("需转换的集合为空");
            }
            //取出第一个实体的所有Propertie
            Type entityType = model.GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();

            //生成DataTable的structure
            //生产代码中,应将生成的DataTable结构Cache起来,此处略
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                Type colType = entityProperties[i].PropertyType;
                if(colType.IsGenericType && colType.GetGenericTypeDefinition()==typeof(Nullable<>))
                {
                    colType = colType.GetGenericArguments()[0];
                }
                dt.Columns.Add(entityProperties[i].Name,colType);
            }
            return dt;
        }

        public static void FullDataRow<T>(T model, DataRow row)
        {
            //检查实体集合不能为空
            if (model == null)
            {
                throw new Exception("需转换的集合为空");
            }
            //取出第一个实体的所有Propertie
            Type entityType = model.GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                object value= entityProperties[i].GetValue(model, null);
                if(value==null)
                {
                    value = DBNull.Value;
                }
                row[entityProperties[i].Name] = value;
            }
        }
        /// <summary>
        /// 用DataRow的数据设置实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="sourceDataRow"></param>
        public static void SetModel<T>(T model, DataRow sourceDataRow)
        {
            Type entityType = model.GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

            foreach (PropertyInfo info in entityProperties)
            {
                if (sourceDataRow.Table.Columns.Contains(info.Name))
                {
                    if (sourceDataRow[info.Name] != DBNull.Value)
                    {
                        info.SetValue(model, sourceDataRow[info.Name], null);
                    }
                }
            }
        }
        /// <summary>
        /// 得到size的字段名FieldName,当size为空时,FieldName="Empty"
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GetFieldName(string size)
        {
            if (string.IsNullOrEmpty(size))
            {
                return "Empty";
            }
            else
            {
                return size.ToString();
            }
        }
        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        /// <summary>
        /// 获取类中的属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetModelValue(string FieldName, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object o = Ts.GetProperty(FieldName).GetValue(obj, null);
                string Value = Convert.ToString(o);
                if (string.IsNullOrEmpty(Value)) return null;
                return Value;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 设置类中的属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SetModelValue(string FieldName, object Value, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType);
                Ts.GetProperty(FieldName).SetValue(obj, v, null);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 将原对象的属性值赋值到目标对象对应的属性
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static T CopyToModel<T>(T source, T target)
        {
            Type tSource = source.GetType();
            Type tTarget = target.GetType();
            foreach (System.Reflection.PropertyInfo p in tSource.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase))
            {
                if (p.CanWrite)
                {
                    try
                    {
                        object value = p.GetValue(source, null);
                        tTarget.GetProperty(p.Name).SetValue(target, value, null);
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            return target;
        }


        /// <summary>
        /// 判断控件是否处在设计模式下,注意:当添加的控件将会被其它控件调用时,应当在控件的构造函数和Load事件进行判断处理(仅对用户添加的代码)
        /// </summary>
        /// <returns></returns>
        public static bool IsDesignMode()
        {
            bool returnFlag = false;
#if DEBUG
            if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
            {
                returnFlag = true;
            }
            else if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv")
            {
                returnFlag = true;
            }
#endif
            return returnFlag;
        }

        /// <summary>
        /// 把过滤出来的数据生成到新的DataTable并返回
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="strCondition">过滤条件</param>
        /// <returns></returns>
        public static DataTable GetNewTable(DataTable dt, string strCondition)
        {
            DataTable tempDT = dt.Clone();
            DataRow[] rows = dt.Select(strCondition);
            foreach (DataRow dr in rows)
            {
                tempDT.ImportRow(dr);
            }
            return tempDT;
        }

        /// <summary>
        /// 得到以Sql语法形式的字符串,以便用于Sql语句查询
        /// </summary>
        /// <param name="items">以逗号分隔的字符串</param>
        /// <returns></returns>
        public static string GetStringBySql(string items)
        {
            if (string.IsNullOrEmpty(items))
            {
                return items;
            }
            else
            {
                StringBuilder results = new StringBuilder();
                foreach (string item in items.Split(',').ToList())
                {
                    if (results.Length == 0)
                    {
                        results.AppendFormat("'{0}'", item);
                    }
                    else
                    {
                        results.AppendFormat(",'{0}'", item);
                    }
                }
                return results.ToString();
            }
        }

        #region 类型转换
        #region 日期
        /// <summary>
        /// 转换成日期
        /// </summary>
        /// <param name="value">日期值</param>
        /// <returns></returns>
        public static DateTime ToDateTime(object value)
        {
            if (DBHelper.IsNull(value))
            {
                return DBHelper.MinDate;
            }
            else
            {
                DateTime result = DBHelper.MinDate;
                return DateTime.TryParse(value.ToString(), out result) ? result : DBHelper.MinDate;
            }
        }


        #endregion 日期结束

        public static double ToDouble(object value)
        {
            if (DBHelper.IsNull(value))
            {
                return 0;
            }
            else
            {
                double result = 0;
                return double.TryParse(value.ToString(), out result) ? result : 0;
            }
        }
        public static int ToInt(object value)
        {
            if (DBHelper.IsNull(value))
            {
                return 0;
            }
            else
            {
                int result = 0;
                return int.TryParse(value.ToString(), out result) ? result : 0;
            }
        }
        public static bool ToBool(object value)
        {
            if (DBHelper.IsNull(value))
            {
                return false;
            }
            else
            {
                bool result = false;
                return bool.TryParse(value.ToString(), out result) ? result : false;
            }
        }
        public static string ToString(object value)
        {
            if (DBHelper.IsNull(value))
            {
                return string.Empty;
            }
            else
            {
                return value.ToString().Trim();
            }
        }

        #endregion 类型转换结束



    }
}