学海无涯

导航

统计

UtilityHelper DbHelper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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 类型转换结束
 
 
 
    }
}

  

posted on   宁静致远.  阅读(16)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示