1
zrg
3 天以前 088f1c56e08047c21dcaebbab475d975531905bd
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace DingDingMsg_MES
{
    
    public class DBHelper 
    {
        private SqlConnection MainCn;//创建连接对象
        SqlTransaction MainTran;
        public string sServer;
        public string sDataBase;
        public string sUser;
        public string sPassword;
        //开始事务
        public void BeginTran()
        {
            if (!this.CnOpen())
                return;
            MainTran = MainCn.BeginTransaction();
        }
        //结束事务
        public void Commit()
        {
            MainTran.Commit();
            CnClose();
        }
        //回滚事务
        public void RollBack()
        {
            MainTran.Rollback();
            CnClose();
        }
        public DBHelper()
        {
            sServer = "47.96.97.237,15127";
            sDataBase = "HX_LMESsys";
            sUser = "HX_USER";
            sPassword = "lc@841022";
            ////斯莫尔
            //sServer = "30.10.7.6";
            //sDataBase = "HX_LMESsys_test";
            //sUser = "HX_USER";
            //sPassword = "lc@841022";
        }
 
        private bool CnOpen()//OPEN数据库连接
        {
            if (sServer == "" || sServer == "没有找到!")
            {
                throw new Exception("错误的服务器名!" + System.Environment.CurrentDirectory);
            }
            if (sDataBase == "" || sDataBase == "没有找到!")
            {
                throw new Exception("错误的数据库名!");
            }
            if (MainCn == null)
            {
                MainCn = new SqlConnection("Data Source=" + sServer + ";DataBase=" + sDataBase + ";User ID=" + sUser + ";PWD=" + sPassword + ";max pool size=32767");
            }
            if (MainCn.State == System.Data.ConnectionState.Closed)
            {
                try
                {
                    MainCn.Open();
                    return true;
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message + "," + sServer + "," + sDataBase);
                }
            }
            else
                return true;
        }
 
        public void CnClose()//关闭数据库连接
        {
            if (MainCn != null)
                MainCn.Close();
        }
 
        public void CnDispose()//释放资源
        {
            if (MainCn != null)
            {
                MainCn.Dispose();
                MainCn = null;
            }
        }
 
        /// <summary>
        /// 执行SQL无返回值
        /// </summary>
        /// <param name="procName"></param>
        /// <param name="sErrMessage"></param>
        /// <returns></returns>
        public void RunProc(string procName)
        {
            if (!this.CnOpen())
            {
                return;
                //sErrMessage = "连接数据库失败!";
            }
            try
            {
                SqlCommand cmd = new SqlCommand(procName, MainCn);
                cmd.CommandTimeout = 600;
                cmd.Transaction = MainTran;
                cmd.ExecuteNonQuery();
                return;
            }
            catch (Exception e)
            {
 
                throw (e);
                //return;
            }
        }
 
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="procName"></param>
        /// <param name="sErrMessage"></param>
        /// <returns></returns>
        public void RunProc(string procName, ref string sErr)
        {
            if (!this.CnOpen())
            {
                sErr = "连接数据库失败!";
                return;
 
            }
            try
            {
                //ClsPub.sSQLInfo = procName;
                SqlCommand cmd = new SqlCommand(procName, MainCn);
                cmd.CommandTimeout = 600;
                cmd.Transaction = MainTran;
                cmd.ExecuteNonQuery();
                return;
            }
            catch (Exception e)
            {
                sErr = e.Message;
                //ClsPub.sErrInfo = e.Message;
                throw (e);
                //return;
            }
        }
        /// <summary>
        /// 递入参数执行SQL并返回DATASET
        /// </summary>
        /// <param name="procName">执行语句</param>
        /// <param name="prams">参数</param>
        /// <param name="tbName">表名</param>
        /// <param name="sErrMessage">异常信息</param>
        /// <returns></returns>
        public DataSet RunProcReturn(string procName, SqlParameter[] prams, string tbName)
        {
            SqlDataAdapter dap = CreateDataAdaper(procName, prams);
            if (dap == null)
                return null;
            DataSet ds = new DataSet();
            try
            {
                 //ClsPub.sSQLInfo = procName;
                dap.Fill(ds, tbName);
                return ds;
            }
            catch (Exception e)
            {
                //ClsPub.sErrInfo = e.Message;
                throw (e);
                return null;
            }
        }
        /// <summary>
        /// 执行SQL并返回DATASET
        /// </summary>
        /// <param name="procName">执行语句</param>
        /// <param name="tbName">表名</param>
        /// <param name="sErrMessage">异常信息</param>
        /// <returns></returns>
        public DataSet RunProcReturn(string procName, string tbName)
        {
            SqlDataAdapter dap = CreateDataAdaper(procName, null);
            DataSet ds = new DataSet();
            try
            {
                //ClsPub.sSQLInfo = procName;
                dap.Fill(ds, tbName);
                return ds;
            }
            catch (Exception e)
            {
                //ClsPub.sErrInfo = e.Message;
                throw (e);
                return null;
            }
        }
        /// <summary>
        /// 执行SQL并返回DATASET和错误信息
        /// </summary>
        /// <param name="procName">执行语句</param>
        /// <param name="tbName">表名</param>
        /// <param name="sErrMessage">异常信息</param>
        /// <returns></returns>
        public DataSet RunProcReturn(string procName, string tbName, ref string sErr)
        {
            SqlDataAdapter dap = CreateDataAdaper(procName, null);
            DataSet ds = new DataSet();
            try
            {
                 //ClsPub.sSQLInfo = procName;
                dap.Fill(ds, tbName);
                return ds;
            }
            catch (Exception e)
            {
                sErr = e.Message;
                //ClsPub.sErrInfo = e.Message;
                return null;
            }
        }
 
        private SqlDataAdapter CreateDataAdaper(string procName, SqlParameter[] prams)
        {
            if (this.CnOpen())
            {
                SqlDataAdapter dap = new SqlDataAdapter(procName, MainCn);
                dap.SelectCommand.CommandType = CommandType.Text;
                dap.SelectCommand.CommandTimeout = 600;
                dap.SelectCommand.Transaction = MainTran;
                if (prams != null)
                {
                    foreach (SqlParameter parameter in prams)
                        dap.SelectCommand.Parameters.Add(parameter);
                }
                dap.SelectCommand.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4,
                    ParameterDirection.ReturnValue, false, 0, 0,
                    string.Empty, DataRowVersion.Default, null));
                return dap;
            }
            else
            {
                return null;
            }
        }
        public static Int64 isLong(object message)
        {
            try
            {
                return Convert.ToInt64(message);
            }
            catch (Exception e)
            {
                return 0;
            }
        }
        public static string isStrNull(object message)
        {
            try
            {
                if (message == null)
                {
                    return "";
                }
                else
                {
                    return message.ToString().Trim();
                }
            }
            catch (Exception e)
            {
                return "";
            }
        }
 
        public static int isInt(object message)
        {
            try
            {
                return Convert.ToInt16(message);
            }
            catch (Exception e)
            {
                return 0;
            }
        }
 
        public  Int64 CreateBillID_Prod(string BillCode, ref string sReturn)
        {
            try
            {
                string BillType = "";
                DataSet Ds;
                Int64 lID;
                Ds =  RunProcReturn("exec h_p_Xt_GetMaxBillID '" + BillCode + "'", "h_p_Xt_GetMaxBillID");
                if (Ds == null || Ds.Tables[0].Rows.Count == 0)
                {
                    lID = -1;
                }
                else
                {
                    lID = DBHelper.isLong(Ds.Tables[0].Rows[0]["HBillNo"]);
                }
                CnClose();
                CnDispose();
                Ds = null;
                return lID;
            }
            catch (Exception e)
            {
                return -2;
            }
        }
 
        //得到最大单据号
        public string CreateBillCode(string BillCode, ref string sReturn, bool Add)
        {
            Int64 BillCodeMode;
            string Profix;
            Int64 Glida;
            Int32 CodeLen;
            string sBillNo = "";
            char c = Convert.ToChar("0");
            string sKjYear = DateTime.Today.Year.ToString();
            string sPeriod = DateTime.Today.Month.ToString();
            string sDay = DateTime.Today.Day.ToString();
            //得到单据号表 信息
            DataSet Ds = new DataSet();
            Ds = RunProcReturn("Select * from Gy_BillNumber where BillCode='" + BillCode.Trim() + "'", "Gy_BillNumber");
            if (Ds.Tables[0].Rows.Count != 0)
            {
                BillCodeMode = DBHelper.isLong(Ds.Tables[0].Rows[0]["BillCodeMode"].ToString());
                Profix = DBHelper.isStrNull(Ds.Tables[0].Rows[0]["Profix"].ToString());
                Glida = DBHelper.isLong(Ds.Tables[0].Rows[0]["Glida"].ToString());
                CodeLen = DBHelper.isInt(Ds.Tables[0].Rows[0]["CodeLen"].ToString());
            }
            else
            {
                return "";
            }
            //
            string sStr;
            switch (BillCodeMode)
            {
                case 0:
                    switch (Glida)
                    {
                        case 0://纯流水号
                            Ds = RunProcReturn("Select * from Gy_MaxNum where BillCode='" + BillCode.Trim() + "'", "Gy_MaxNum");
                            if (Ds.Tables[0].Rows.Count != 0)
                            {
                                sStr = new string(c, CodeLen - (Ds.Tables[0].Rows[0]["NowNumBer"].ToString()).Length);
                                sBillNo = Profix.Trim() + sStr + Ds.Tables[0].Rows[0]["NowNumBer"].ToString().Trim();
                            }
                            else //插入新记录
                            {
                                sStr = new string(c, CodeLen - 1);
                                RunProc("insert into Gy_MaxNum(BillCode,NowNumber) values('" + BillCode.Trim() + "',1)");
                                sBillNo = Profix.Trim() + sStr + 1;
                            }
                            if (Add == true)
                            {
                                RunProc("update Gy_Maxnum set NowNumBer=NowNumBer+1 where BillCode='" + BillCode.Trim() + "'");
                            }
                            return sBillNo;
 
                        case 1://根据 YY年+MM月 日 + 流水号  生成单据号 (日 采用了 仓库的字段)
                            sKjYear = sKjYear.Substring(2, 2);
                            sPeriod = "0" + sPeriod;
                            sPeriod = sPeriod.Substring(sPeriod.Length - 2, 2);
                            sDay = "";
                            Ds = RunProcReturn("Select * from Gy_MaxNum where BillCode='" + BillCode.Trim() + "' and KjYear='" + sKjYear + "' and Period='" + sPeriod + "' and whcode='" + sDay + "'", "Gy_MaxNum");
                            if (Ds.Tables[0].Rows.Count != 0)
                            {
                                sStr = new string(c, CodeLen - (Ds.Tables[0].Rows[0]["NowNumBer"].ToString()).Length);
                                sBillNo = Profix.Trim() + sKjYear + sPeriod + sDay + sStr + Ds.Tables[0].Rows[0]["NowNumBer"].ToString().Trim();
                            }
                            else //插入新记录
                            {
                                sStr = new string(c, CodeLen - 1);
                                RunProc("insert into Gy_Maxnum(BillCode,Kjyear,Period,whcode,NowNumber)  values('" + BillCode.Trim() + "','" + sKjYear + "','" + sPeriod + "','" + sDay + "',1)");
                                sBillNo = Profix.Trim() + sKjYear + sPeriod + sDay + sStr + "1";
                            }
                            if (Add == true)
                            {
                                RunProc("update Gy_Maxnum set NowNumBer=NowNumBer+1 where BillCode='" + BillCode.Trim() + "' and KjYear='" + sKjYear + "' and Period='" + sPeriod + "' and whcode='" + sDay + "'");
                            }
                            return sBillNo;
                        case 2:      //根据年+月+日  生成单据号
                            Ds = RunProcReturn("Select * from Gy_MaxNum where BillCode='" + BillCode.Trim() + "' and KjYear='" + sKjYear + "' and Period='" + sPeriod + "' and whcode='" + sDay + "'", "Gy_MaxNum");
                            if (Ds.Tables[0].Rows.Count != 0)
                            {
                                sStr = new string(c, CodeLen - (Ds.Tables[0].Rows[0]["NowNumBer"].ToString()).Length);
                                sBillNo = Profix.Trim() + sKjYear + DBHelper.isStrNull(("0" + sPeriod)).Substring(DBHelper.isStrNull(("0" + sPeriod)).Length - 2, 2) + DBHelper.isStrNull(("0" + sDay)).Substring(DBHelper.isStrNull(("0" + sDay)).Length - 2, 2) + sStr + Ds.Tables[0].Rows[0]["NowNumBer"].ToString().Trim();
                            }
                            else //插入新记录
                            {
                                sStr = new string(c, CodeLen - 1);
                                RunProc("insert into Gy_Maxnum(BillCode,Kjyear,Period,whcode,NowNumber)  values('" + BillCode.Trim() + "','" + sKjYear + "','" + sPeriod + "','" + sDay + "',1)");
                                sBillNo = Profix.Trim() + sKjYear + DBHelper.isStrNull(("0" + sPeriod)).Substring(DBHelper.isStrNull(("0" + sPeriod)).Length - 2, 2) + DBHelper.isStrNull(("0" + sDay)).Substring(DBHelper.isStrNull(("0" + sDay)).Length - 2, 2) + sStr + 1;
                            }
                            if (Add == true)
                            {
                                RunProc("update Gy_Maxnum set NowNumBer=NowNumBer+1 where BillCode='" + BillCode.Trim() + "' and KjYear='" + sKjYear + "' and Period='" + sPeriod + "' and whcode='" + sDay + "'");
                            }
                            return sBillNo;
 
 
                        default:
                            return sBillNo;
 
                    }
 
                case 1:
                    return sBillNo;
 
                default:
                    return sBillNo;
 
            }
            CnClose();
            CnDispose();
        }
 
        private static readonly object lockObj = new object();
        //写日志
        public static void CustomWriteLog(object obj, string FileName, string filePath = "Vlog", bool isAppend = true)
        {
            try
            {
                lock (lockObj)
                {
                    filePath = $@"{filePath}\{FileName}.txt";
 
                    filePath = AppDomain.CurrentDomain.BaseDirectory + filePath;
 
                    if (!System.IO.Directory.Exists(Path.GetDirectoryName(filePath)))
                    {
                        System.IO.Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    }
 
                    bool fileExists = System.IO.File.Exists(filePath);
                    //不存在 则创建该文件
                    if (!fileExists)
                    {
                        System.IO.File.Create(filePath).Close();
                    }
 
                    using (StreamWriter writer = new StreamWriter(filePath, isAppend))
                    {
                        //存在的时候才写一行
                        if (fileExists && isAppend)
                        {
                            writer.WriteLine();
                        }
 
                        var content = obj is string ? obj : JsonConvert.SerializeObject(obj);
                        writer.WriteLine($"{DateTime.Now} {content}");
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
}