qwj
2022-08-22 63f6c5de8832eaabf066fe9f9d492187f04011b7
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Collections;
using System.Xml;
 
namespace CY_DocumentSynchroWCFService
{
    public partial class ServerUpdate
    {
        public bool IsFirst
        {
            get;
            set;
        }
 
        public Sys_Update m_Sys_Update
        {
            get;
            set;
        }
 
        public ServerUpdate(Sys_Update m_Sys_Update_Parm, bool isFirst = false)
        {
            IsFirst = isFirst;
            m_Sys_Update = m_Sys_Update_Parm;
        }
 
        private string updateUrl = string.Empty;
        private string tempUpdatePath = string.Empty;
        XmlFiles updaterXmlFiles = null;
        private int availableUpdate = 0;
        bool isRun = false;
        string mainAppExe = "";
        private IList<string> verList = null;
        bool IsUpdateSql = false;
        string strCode = string.Empty;
        string ApplicationPath = "";
        List<Sys_Update> m_Sys_UpdateList = new List<Sys_Update>();
        public delegate void SetlvUpdateListItem(string[] arry);
 
        public delegate void CloseMain();
 
        public void FrmUpdate_Load()
        {
#if DEBUG
            ApplicationPath = System.AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "");
#else
            ApplicationPath = System.AppDomain.CurrentDomain.BaseDirectory ;
#endif
            //if (!IsCanUpdate())
            //{
            //    return;
            //}
            IsCanUpdate();
            Init();
            System.Threading.Thread.Sleep(2000);
            DownUpdateFile();
        }
 
        //初始化
        private void Init()
        {
            string localXmlFile = ApplicationPath + "\\UpdateList.xml";
            string serverXmlFile = string.Empty;
            Sys_Update m_Sys_Update = new Sys_Update();
            try
            {
                //从本地读取更新配置文件信息
                updaterXmlFiles = new XmlFiles(localXmlFile);
            }
            catch
            {
                return;
            }
            if (string.IsNullOrEmpty(strCode))
            {
                return;
            }
            //获取服务器地址
            updateUrl = updaterXmlFiles.GetNodeValue("//Url");
            string localVersion = updaterXmlFiles.GetNodeValue("//Version");
            verList = new List<string>();
            try
            {
                bool isCanUpdate = false;
                RegisterService.RegisterSystemClient client = new RegisterService.RegisterSystemClient("WSHttpBinding_IRegisterSystem");
                string[] newVewArry = new string[]{
                };
                int isNew = 0;
                client.GetNewVersion(out newVewArry, out isNew, strCode, localVersion);
                if (isNew == 1)
                {
                    if (newVewArry.Length > 0)
                    {
                        foreach (string str in newVewArry)
                        {
                            verList.Add(str);
                        }
                    }
                    if (verList.Count > 0)
                    {
                        // IDictionary<int, string[]> htUpdateFile = new Dictionary<int, string[]>();
                        Hashtable htUpdateFile = new Hashtable();
                        foreach (string ver in verList)
                        {
                            AppUpdater appUpdater = new AppUpdater();
                            appUpdater.UpdaterUrl = updateUrl + "/" + strCode + "//" + ver + "//UpdateList.xml";
 
                            //与服务器连接,下载更新配置文件
                            string tempUpdateChildPath = string.Empty;
                            try
                            {
                                tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\";
                                tempUpdateChildPath = tempUpdatePath + ver + "\\";
                                appUpdater.DownAutoUpdateFile(tempUpdateChildPath);
                            }
                            catch
                            {
                                return;
                            }
 
                            //获取更新文件列表
                            serverXmlFile = tempUpdateChildPath + "UpdateList.xml";
                            if (!File.Exists(serverXmlFile))
                            {
                                return;
                            }
                            availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile);
                            if (availableUpdate > 0)
                            {
                                for (int i = 0; i < htUpdateFile.Count; i++)
                                {
                                    string[] fileArray = (string[])htUpdateFile[i];
                                    Sys_Update m_Sys_Update_XXXX = new Sys_Update();
                                    m_Sys_Update_XXXX.NowName = fileArray[0];
                                    m_Sys_Update_XXXX.NowVersion = fileArray[1];
                                    m_Sys_UpdateList.Add(m_Sys_Update_XXXX);
                                }
                            }
                        }
                        if (htUpdateFile.Count > 0)
                        {
                            isCanUpdate = true;
                            foreach (var item in htUpdateFile)
                            {
                                int i = 0;
                                string[] fileArray = (string[])htUpdateFile[i];
                                Sys_Update m_Sys_Update_XXXX = new Sys_Update();
                                m_Sys_Update_XXXX.NowName = fileArray[0];
                                m_Sys_Update_XXXX.NowVersion = fileArray[1];
                                m_Sys_UpdateList.Add(m_Sys_Update_XXXX);
                            }
                        }
                        else
                        {
                            isCanUpdate = false;
                        }
                    }
                }
                if (!isCanUpdate)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
 
        //根据更新时间判断是否能够更新
        public bool IsCanUpdate()
        {
            string updateTime = string.Empty;
            bool isCanUpdate = true;
            try
            {
                string updateTimeXML = ApplicationPath + "\\UpdateTime.xml";
                XmlFiles updateTimeXMLFile = new XmlFiles(updateTimeXML);
                updateTime = updateTimeXMLFile.GetNodeValue("//LastUpdateTime");
                strCode = updateTimeXMLFile.GetNodeValue("//SystemCode").Trim();
                if (IsFirst)
                {
                    if (string.IsNullOrEmpty(updateTime))
                    {
                        isCanUpdate = true;
                    }
                    else
                    {
                        DateTime nowDateTime = DateTime.Now;
                        DateTime updateDateTime = DateTime.Parse(updateTime).AddDays(30);
                        if (updateDateTime.CompareTo(nowDateTime) >= 0)
                        {
                            isCanUpdate = false;
                        }
                        else
                        {
                            isCanUpdate = true;
                        }
                    }
                }
                string nowDateTimeStr = DateTime.Now.ToShortDateString();
                updateTimeXMLFile.UpdateNodeValue("//LastUpdateTime", nowDateTimeStr);
            }
            catch (Exception ex)
            {
                isCanUpdate = true;
            }
            return isCanUpdate;
        }
 
        private void DownUpdateFile()
        {
            //this.Cursor = Cursors.WaitCursor;
            mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint");
            Process[] allProcess = Process.GetProcesses();
            foreach (Process p in allProcess)
            {
 
                if (p.ProcessName.ToLower() + ".exe" == mainAppExe.ToLower())
                {
                    for (int i = 0; i < p.Threads.Count; i++)
                        p.Threads[i].Dispose();
                    p.Kill();
                    isRun = true;
                    //break;
                }
            }
            WebClient wcClient = new WebClient();
            for (int i = 0; i < m_Sys_UpdateList.Count; i++)
            {
                Sys_Update item = m_Sys_UpdateList[i];
                string UpdateFile = item.NowName;
                string ver = item.NowVersion;
                if (UpdateFile == "更新数据库")
                {
                    IsUpdateSql = true;
                    continue;
                }
                string updateFileUrl = updateUrl + "/" + strCode + "//" + ver + "//" + UpdateFile;
                long fileLength = 0;
 
                WebRequest webReq = WebRequest.Create(updateFileUrl);
                WebResponse webRes = webReq.GetResponse();
                fileLength = webRes.ContentLength;
 
                try
                {
                    Stream srm = webRes.GetResponseStream();
                    StreamReader srmReader = new StreamReader(srm);
                    byte[] bufferbyte = new byte[fileLength];
                    int allByte = (int)bufferbyte.Length;
                    int startByte = 0;
                    while (fileLength > 0)
                    {
                   //     Application.DoEvents();
                        int downByte = srm.Read(bufferbyte, startByte, allByte);
                        if (downByte == 0)
                        {
                            break;
                        };
                        startByte += downByte;
                        allByte -= downByte;
                     //   pbDownFile.Value += downByte;
 
                        float part = (float)startByte / 1024;
                        float total = (float)bufferbyte.Length / 1024;
                        int percent = Convert.ToInt32((part / total) * 100);
 
                       // this.lvUpdateList.Items[i].SubItems[2].Text = percent.ToString() + "%";
 
                    }
 
                    string tempPath = tempUpdatePath + ver + "//" + UpdateFile;
                    CreateDirtory(tempPath);
                    FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write);
                    fs.Write(bufferbyte, 0, bufferbyte.Length);
                    srm.Close();
                    srmReader.Close();
                    fs.Close();
 
                }
                catch (WebException ex)
                {
                    return;
                }
                finally
                {
                    webRes.Close();
                }
            }
            //InvalidateControl();
            //this.Cursor = Cursors.Default;
        }
        //创建目录
        private void CreateDirtory(string path)
        {
            if (!File.Exists(path))
            {
                string[] dirArray = path.Split('\\');
                string temp = string.Empty;
                for (int i = 0; i < dirArray.Length - 1; i++)
                {
                    temp += dirArray[i].Trim() + "\\";
                    if (!Directory.Exists(temp))
                        Directory.CreateDirectory(temp);
                }
            }
        }
 
        //复制文件;
        public void CopyFile(string sourcePath, string objPath)
        {
            //            char[] split = @"\".ToCharArray();
            if (!Directory.Exists(objPath))
            {
                Directory.CreateDirectory(objPath);
            }
            string[] files = Directory.GetFiles(sourcePath);
            for (int i = 0; i < files.Length; i++)
            {
                string[] childfile = files[i].Split('\\');
                File.Copy(files[i], objPath + @"\" + childfile[childfile.Length - 1], true);
            }
            string[] dirs = Directory.GetDirectories(sourcePath);
            for (int i = 0; i < dirs.Length; i++)
            {
                string[] childdir = dirs[i].Split('\\');
                CopyFile(dirs[i], objPath + @"\" + childdir[childdir.Length - 1]);
            }
        }
 
        //点击完成复制更新文件到应用程序目录
        private void btnFinish_Click()
        {
            try
            {
                UpdateSql();
                foreach (string ver in verList)
                {
                    string tempUpdateChildPath = tempUpdatePath + ver + "\\";
                    CopyFile(tempUpdateChildPath, Directory.GetCurrentDirectory());
                }
                System.IO.Directory.Delete(tempUpdatePath, true);
            }
            catch (Exception ex)
            {
                return;
            }
            if (true == this.isRun)
                Process.Start(mainAppExe);
        }
 
        /// <summary>
        /// 更新SQL语句
        /// </summary>
        public void UpdateSql()
        {
            if (IsUpdateSql)
            {
                if (verList.Count > 0)
                {
                    foreach (string ver in verList)
                    {
                        string serverXmlPath = tempUpdatePath + ver + "\\UpdateList.xml";
 
                        XmlFiles serverXmlFiles = new XmlFiles(serverXmlPath);
 
                        XmlNodeList newSqlList = serverXmlFiles.GetNodeList("AutoUpdater/SQLList");
                        if (newSqlList != null && newSqlList.Count > 0)
                        {
 
                            for (int i = 0; i < newSqlList.Count; i++)
                            {
                                string sqlStr = newSqlList.Item(i).InnerText;
                                try
                                {
                                    //AccessHelper.excuteSql(sqlStr);
                                }
                                catch (Exception ex)
                                {
 
                                }
                            }
                        }
                    }
                }
            }
        }
 
        //判断主应用程序是否正在运行
        private bool IsMainAppRun()
        {
            string mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint");
            bool isRun = false;
            Process[] allProcess = Process.GetProcesses();
            foreach (Process p in allProcess)
            {
 
                if (p.ProcessName.ToLower() + ".exe" == mainAppExe.ToLower())
                {
                    isRun = true;
                    //break;
                }
            }
            return isRun;
        }
    }
}