schangxiang@126.com
2025-09-18 49a51c068d62084bc4c3e77c4be94a20de556c4a
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
using iWareSAP.Cache.Entity;
using iWareSAP.IDOC.Entity;
using iWareSAP.IDOC.EnumType;
using iWareSAP.Properties;
using iWareSAP.WCF;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.ServiceModel;
using System.Threading;
using System.Windows.Forms;
using UtilDll.UTIL;
using System.Linq;
using Newtonsoft.Json;
 
namespace iWareSAP
{
    public partial class MainForm : Form
    {
        //库存盘点 不是立库的数据过滤掉  李翠国2021-9-18 改
        //库存盘点 取消分批发送数据给wms (每次100条,这样只会盘点最后一次)李翠国2021-9-18
        private ServiceHost _sapWcfHost = null;
        private List<Thread> _readFileThreads = null;
        private string _logDir;
 
        public MainForm()
        {
 
            var proc = new Process();
            try
            {
                InitializeComponent();
                _logDir = Resources.LogDir + @"\YIRUANTONG";
                _sapWcfHost = new ServiceHost(typeof(SapWcfService));
                try
                {
                    proc.StartInfo.FileName = "cmd.exe";
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.RedirectStandardInput = true;
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.RedirectStandardError = true;
                    proc.StartInfo.CreateNoWindow = true;
                    proc.Start();
                    var path = ConfigurationManager.AppSettings["SapDir"].ToString();
                    //var password = ";'QpAlZm1234";
                    //var username = "qian.zhuang.ext@siemens.com";
 
                    var username = ConfigurationManager.AppSettings["SapUsername"].ToString();
                    var password = ConfigurationManager.AppSettings["SapPassword"].ToString();
                    proc.StandardInput.WriteLine("net use {0} {1} /user:{2}", path, password, username);
 
 
                    string dosLine = "net use " + path + " ";
                    proc.StandardInput.WriteLine(dosLine);
                    proc.StandardInput.WriteLine("exit");
 
                    while (!proc.HasExited)
                    {
                        proc.WaitForExit(1000);
                    }
                    string errormsg = proc.StandardError.ReadToEnd();
                    proc.StandardError.Close();
                    if (!string.IsNullOrEmpty(errormsg))
                    {
                        throw new Exception(errormsg);
                    }
 
                }
                catch (Exception ex)
                {
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "ConnectRemote", "已链接: " + ex.Message);
                }
 
                _readFileThreads = new List<Thread>();
 
            }
            catch (Exception ex)
            {
                LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "ConnectRemote", ex.Message);
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
 
        }
 
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                foreach (var type in Enum.GetValues(typeof(EDocType)))
                {
                    var readFileThread = new Thread(new ParameterizedThreadStart(readFile));
                    readFileThread.Name = string.Format("iWareSAP读取共享文件线程,type={0}", type.ToString());
                    _readFileThreads.Add(readFileThread);
                    ThreadHelper.StartThread(readFileThread, (int)type);
                }
                _sapWcfHost.Open();
                CacheEntity.SapncoClient.RegisterRfcDestination();
            }
            catch (Exception ex)
            {
                LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "MainForm_Load", ex.Message);
            }
        }
 
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_sapWcfHost != null)
            {
                _sapWcfHost.Close();
            }
            //ThreadHelper.CloseThread(_readFileThread);
        }
 
        private void readFile(object obj)
        {
            var type = (int)obj;
            var typeNamedict = new Dictionary<int, string> 
            {
                { (int)EDocType.物料, "MATMAS"},
                { (int)EDocType.出库单, "PPO"},
                { (int)EDocType.对账单, "WMS_STOCK"}
            };
            var path = ConfigurationManager.AppSettings["SapDir"].ToString();
            while (true)
            {
                try
                {
                    var files = Directory.GetFiles(path);
 
                    for (var i = 0; i < files.Length; i++)
                    {
                        try
                        {
                            #region 循环处理
                            var filePath = files[i];
                            var fileName = Path.GetFileName(filePath);
 
                            if (fileName.ToUpper().StartsWith(typeNamedict[type]))
                            {
 
                                var delta = 100.0;
                                LogTextHelper.WriteLine(Resources.LogDir, "正在处理文件{0}", filePath);
                                switch (type)
                                {
                                    case (int)EDocType.物料:
                                        #region sap物料添加修改
                                        var materials = new List<Material>();
                                        using (var reader = new StreamReader(filePath))
                                        {
                                            var line = reader.ReadLine();
                                            while (!string.IsNullOrEmpty(line))
                                            {
                                                materials.Add(new Material(line));
                                                line = reader.ReadLine();
                                            }
                                        }
                                        //下面的注释,删除文件操作改为调取服务成功后才删除 【EditBy shaocx,2022-06-17】
                                        //File.Delete(filePath);
                                        for (var j = 0; j < (int)Math.Ceiling(materials.Count / delta); j++)
                                        {
                                            var ms = new List<WmsWcfService.Material>();
                                            for (var r = j * delta; r < j * delta + delta; r++)
                                            {
                                                if (r == materials.Count)
                                                {
                                                    break;
                                                }
                                                //LogTextHelper.WriteLine(_logDir, "material={0}", materials[(int)r]);
                                                ms.Add(materials[(int)r].ToWmsMaterial());
                                            }
 
                                            string result_addMaterial = CacheEntity.WmsWcfServiceClient.addMaterial(ms.ToArray());
                                            if (!string.IsNullOrEmpty(result_addMaterial))
                                            {//失败
 
                                            }
                                            else
                                            {//成功
                                                File.Delete(filePath);//删除文件
                                            }
                                        }
 
                                        break;
                                        #endregion
 
                                    case (int)EDocType.出库单:
                                        #region SAP出库单
                                        var pickLists = new List<PickList>();
                                        var removepickLists = new List<PickList>();
                                        using (var reader = new StreamReader(filePath))
                                        {
                                            var line = reader.ReadLine();
                                            while (!string.IsNullOrEmpty(line))
                                            {
                                                pickLists.Add(new PickList(line));
                                                line = reader.ReadLine();
                                            }
                                        }
                                        //  File.Move(filePath,path+@"\old");
                                        //下面的注释,删除文件操作改为调取服务成功后才删除 【EditBy shaocx,2022-06-17】
                                        //File.Delete(filePath);
 
                                        if (pickLists.Count > 0)
                                        {
                                            int newDate = Convert.ToInt32(pickLists[pickLists.Count - 1].BDTER);//最后一个是最新日期
                                            foreach (var item in pickLists)
                                            {
                                                try
                                                {
                                                    int compareDate = Convert.ToInt32(item.BDTER);
                                                    if (compareDate == newDate)
                                                    {
                                                        removepickLists.Add(item);//把新日期全部加入这个集合
                                                    }
                                                }
                                                catch (Exception)
                                                {
                                                }
 
                                            }
                                            if (removepickLists.Count > 0)
                                            {
                                                pickLists = removepickLists;
                                            }
                                            var saleOrder = pickLists[0].ToWmsSaleOrder();
                                            var saleOrderLists = new List<WmsWcfService.SaleOrderList>();
                                            foreach (var p in pickLists)
                                            {
                                                if (string.IsNullOrEmpty(p.MATNR))
                                                {
                                                    continue;
                                                }
 
                                                //LogTextHelper.WriteLine(_logDir, "saleOrderList={0}", p);
                                                saleOrderLists.Add(p.ToWmsSaleOrderList());
                                            }
                                            saleOrder.saleChild = saleOrderLists.ToArray();
 
                                            string result = CacheEntity.WmsWcfServiceClient.pickList(saleOrder);
 
                                            if (!string.IsNullOrEmpty(result))
                                            {//失败,就拷贝放到服务器的某个文件夹中
                                                var path_pickList = "D:\\log_MySAP\\Fail_pickList\\" + fileName;
                                                if (!File.Exists(path_pickList))
                                                {
                                                    File.Copy(filePath, path_pickList);
                                                }
                                            }
                                            else
                                            {//成功
                                                File.Move(filePath, "D:\\log_MySAP\\Success_pickList\\" + fileName);//只有成功后才会移走文件
                                            }
                                        }
                                        break;
                                        #endregion
 
                                    case (int)EDocType.对账单:
                                        //文件放到指定目录中,然后再调用服务siemensSapService的takeStock去处理这些信息 
                                        //File.Move(filePath, "D:\\log_ShuYing\\" + fileName);
                                        File.Move(filePath, "D:\\log_takeStock\\" + fileName);//盘点存放文件改为 log_takeStock 【EditBy shaocx,2022-10-12】
                                        var ss = new List<WmsWcfService.ProductStock>();
                                        string result_takeStock = CacheEntity.WmsWcfServiceClient.takeStock(ss.ToArray());
 
 
                                        #region 旧的
 
                                        //var stocks = new List<Stock>();
 
                                        //using (var reader = new StreamReader(filePath))
                                        //{
                                        //    var line = reader.ReadLine();
                                        //    while (!string.IsNullOrEmpty(line))
                                        //    {
                                        //        if (!line.StartsWith("MATNR"))
                                        //        {
                                        //            stocks.Add(new Stock(line));
                                        //        }
                                        //        line = reader.ReadLine();
                                        //    }
                                        //}
 
                                        ////var delta = 100.0; //取消分批发送 (每次100条,这样只会盘点最后一次)李翠国2021-9-18
                                        //#region 拆分发送 每次100条
                                        //  for (var j = 0; j < (int)Math.Ceiling(stocks.Count / delta); j++)
                                        //{
                                        //    var ss = new List<WmsWcfService.ProductStock>();
                                        //    for (var r = j * delta; r < j * delta + delta; r++)
                                        //    {
                                        //        if (r == stocks.Count)
                                        //        {
                                        //            break;
                                        //        }
                                        //        //LogTextHelper.WriteLine(_logDir, "stock={0}", stocks[(int)r]);
                                        //        ss.Add(stocks[(int)r].ToWmsProductStock());
                                        //    }
                                        //       CacheEntity.WmsWcfServiceClient.takeStock(ss.ToArray());
                                        //    //    File.Delete(filePath);
                                        //#endregion
 
                                        //    //List<WmsWcfService.ProductStock> ss = new List<WmsWcfService.ProductStock>();
                                        //    //List<WmsWcfService.ProductStock> mergeed = new List<WmsWcfService.ProductStock>();//根据销售单号 销售项号,物料编号,合并相同项
                                        //    //for (var r = 0 ; r < stocks.Count; r++)
                                        //    //{
                                        //    //    if (stocks[(int)r].WERKS=="3TG1")//不是立库的过滤掉  李翠国2021-9-18 改
                                        //    //    {
                                        //    //        ss.Add(stocks[(int)r].ToWmsProductStock());
                                        //    //    }
 
                                        //    //}
                                        //    //var merge = ss.GroupBy(x => new { x.SaleCode, x.SaleItem, x.materialCode });
                                        //    //foreach (var item in merge)
                                        //    //{
                                        //    //    for (int k = 1; k < item.ToList().Count; k++)
                                        //    //    {
                                        //    //        item.ToList()[0].stockQuantity = item.ToList()[0].stockQuantity + item.ToList()[k].stockQuantity;
                                        //    //    }
                                        //    //    mergeed.Add(item.ToList()[0]);
                                        //    //}
                                        //    //if (mergeed.Count>0)
                                        //    //{
                                        //    //    CacheEntity.WmsWcfServiceClient.takeStock(mergeed.ToArray());
                                        //    //    File.Delete(filePath);
                                        //   }
 
                                        #endregion
                                        break;
 
                                }
 
                                break;
                            }
                            #endregion
                        }
                        catch (Exception ex)
                        {
                            LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "readFile内部循环", ex.Message + ",异常行数:" + ex.StackTrace);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "readFile", ex.Message + ",详细堆栈:" + JsonConvert.SerializeObject(ex));
                    LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "readFile", ex.Message + ",异常行数:" + ex.StackTrace);
                }
                finally
                {
 
                    Thread.Sleep(1000);
                }
            }
        }
 
        private void button_Click(object sender, EventArgs e)
        {
            try
            {
                string msg = "";
                var btn = sender as Button;
                switch (btn.Name)
                {
                    case "button1":
                        textBox1.Text = CacheEntity.SapncoClient.InvokeRFCFunctionGetDate(DateTime.Now.ToString("yyyy-MM-dd"));
                        break;
                    case "button2":
                        var po = CacheEntity.SapncoClient.InvokeRFCFunctionGetPoDetail(textBox2.Text.Trim(), out msg);
                        textBox3.Text = string.IsNullOrEmpty(msg) ? po.ToString() : msg;
                        break;
                    case "button3":
                        var res = CacheEntity.SapncoClient.InvokeRFCFunctionWmsReverser(textBox4.Text.Trim(), out msg);
                        textBox3.Text = string.IsNullOrEmpty(msg) ? res.ToString() : msg;
                        break;
                }
            }
            catch (Exception ex)
            {
                LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "button_Click", ex.Message);
                MessageBox.Show(ex.Message);
            }
        }
 
        private void MainForm_FormClosing_1(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(0);//退出本进程所有线程
        }
    }
}
 
 
 
 
 
 
 
 
 
//case "button3":
//    var grMaterials = new List<GRMaterial> 
//    {
//        new GRMaterial
//        {
//            EBELN = "4507524081",
//            EBELP = "00010",
//            MATNR = "A7EQD-5130003798",
//            BWART = "101",
//            WERKS = "3TG1",
//            LGORT = "G021",
//            MENGE = 1.0m
//        }
//    };
//    var res = CacheEntity.SapncoClient.InvokeRFCFunctionPoGR(grMaterials, out msg);
//    textBox4.Text = grMaterials[0].ToString();
//    textBox5.Text = string.IsNullOrEmpty(msg) ? res : msg;
//    break;
//case "button4":
//    var giMaterials = new List<GIMaterial> 
//    {
//        new GIMaterial
//        {
//            BWART = "261",
//            MATNR = "JEGT5007859",
//            WERKS = "3TG1",
//            LGORT = "G003",
//            SOBKZ = "e",
//            LIFNR = "",
//            KDAUF = "3005352431",
//            KDPOS = 10,
//            ERFMG = 1.0m,
//            ERFME = "KG",
//            CHARG = "",
//            SERNR = "",
//            AUFNR = "800021122917",
//            KZEAR = "",
//            RSNUM = 1179434436,
//            RSPOS = 3,
//            BWTAR = ""
//        }
//    };
//    var gi = CacheEntity.SapncoClient.InvokeRFCFunctionWmsGI(giMaterials, out msg);
//    textBox6.Text = giMaterials[0].ToString();
//    textBox7.Text = string.IsNullOrEmpty(msg) ? gi : msg;
//    break;
//case "button5":
//    var movMaterials = new List<MovMaterial> 
//    {
//        new MovMaterial
//        {
//            BWART = "261",
//            MATNR = "JEGT5007859",
//            WERKS = "3TG1",
//            LGORT = "G003",
//            SOBKZ = "e",
//            LIFNR = "",
//            KDAUF = "3005352431",
//            KDPOS = 10,
//            ERFMG = 1.0m,
//            ERFME = "KG",
//            CHARG = "",
//            SERNR = "",
//            UMLGO = "G021",
//            BWTAR = ""
//        }
//    };
//    var m = CacheEntity.SapncoClient.InvokeRFCFunctionWmsStkMov(movMaterials, out msg);
//    textBox8.Text = movMaterials[0].ToString();
//    textBox9.Text = string.IsNullOrEmpty(msg) ? m : msg;
//    break;