UpdateForm.xaml.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Runtime.Serialization.Formatters.Binary;
  9. using System.Text;
  10. using System.Windows;
  11. using System.Windows.Controls;
  12. using System.Windows.Data;
  13. using System.Windows.Documents;
  14. using System.Windows.Input;
  15. using System.Windows.Media;
  16. using System.Windows.Media.Imaging;
  17. using System.Windows.Shapes;
  18. namespace Muchinfo.MTPClient.Update
  19. {
  20. /// <summary>
  21. /// UpdateForm.xaml 的交互逻辑
  22. /// </summary>
  23. public partial class UpdateForm : Window
  24. {
  25. public UpdateForm(string updateUrl ,UpdateInfo updateInfo)
  26. {
  27. InitializeComponent();
  28. applictionUpdateUrl = updateUrl;
  29. updateInfos = updateInfo;
  30. this.Loaded += MainWindow_Loaded;
  31. this.bnt_Close.Click += bnt_Close_Click;
  32. this.MouseDown += new MouseButtonEventHandler(Window_MouseDown);
  33. //this.Closing += MainWindow_Closing;
  34. Application.Current.Exit += Current_Exit;
  35. }
  36. // private Queue<UpdateFile> _downList = new Queue<UpdateFile>();
  37. const string Update_GetConfigEx = "获取配置文件异常";
  38. const string APP_Updating = "应用程序正在更新...";
  39. const string Update_NoNewFileDowm = "没有提供最新的文件下载";
  40. const string Update_GetServiceFileEx = "获取服务器文件信息出错";
  41. const string Update_NowDownFile = "正在下载文件";
  42. const string Update_FileAllFinish = "全部下载完成";
  43. private const string update_bakDir = "Update_bak";
  44. private const string update_Dir = "Update";
  45. private UpdateInfo updateInfos;
  46. private string applictionUpdateUrl;
  47. private WebClient webClient = null;
  48. /// <summary>
  49. /// 程序文件夹
  50. /// </summary>
  51. private string localAppFolder = AppDomain.CurrentDomain.BaseDirectory;
  52. /// <summary>
  53. /// 更新文件夹
  54. /// </summary>
  55. private string localUpdateFolder = AppDomain.CurrentDomain.BaseDirectory + update_Dir;
  56. /// <summary>
  57. /// 备份文件夹
  58. /// </summary>
  59. private string localBackupFolder = AppDomain.CurrentDomain.BaseDirectory + update_bakDir;
  60. /// <summary>
  61. /// 消息提示
  62. /// </summary>
  63. private string msg = string.Empty;
  64. /// <summary>
  65. /// 总下载数
  66. /// </summary>
  67. private float totalCount = 0f;
  68. /// <summary>
  69. /// 当前下载数
  70. /// </summary>
  71. private float totalCount_Completed = 0f;
  72. /// <summary>
  73. /// 下载状态
  74. /// </summary>
  75. private bool isRunning = false;
  76. private Queue<UpdateFile> _downList = new Queue<UpdateFile>();
  77. /// <summary>
  78. /// 下载列表
  79. /// </summary>
  80. public Queue<UpdateFile> DownList
  81. {
  82. get { return _downList; }
  83. set { _downList = value; }
  84. }
  85. #region 私有方法
  86. #region 下载线程
  87. void MainWindow_Loaded(object sender, RoutedEventArgs e)
  88. {
  89. BackgroundWorker bw = new BackgroundWorker();
  90. bw.DoWork += bw_DoWork;
  91. bw.RunWorkerCompleted += bw_RunWorkerCompleted;
  92. bw.RunWorkerAsync();
  93. }
  94. void bw_DoWork(object sender, DoWorkEventArgs e)
  95. {
  96. try
  97. {
  98. if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Client.Update.old.exe"))
  99. {
  100. File.Delete(AppDomain.CurrentDomain.BaseDirectory + "Client.Update.old.exe");
  101. }
  102. if (updateInfos == null)
  103. return;
  104. if (updateInfos != null && updateInfos.UpdateFiles != null && !updateInfos.UpdateFiles.Any())
  105. {
  106. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  107. {
  108. SetMessageText(Update_NoNewFileDowm);
  109. }));
  110. }
  111. }
  112. catch (Exception ex)
  113. {
  114. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  115. {
  116. SetMessageText(Update_GetServiceFileEx);
  117. }));
  118. }
  119. }
  120. void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  121. {
  122. if (updateInfos != null && updateInfos.UpdateFiles != null && !updateInfos.UpdateFiles.Any())
  123. {
  124. return;
  125. }
  126. DownLoad();
  127. }
  128. #endregion
  129. #region WebClient下载
  130. public void DownLoad()
  131. {
  132. webClient = new WebClient();
  133. webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
  134. webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
  135. //删除并且重新创建Update文件夹
  136. if (Directory.Exists(localUpdateFolder))
  137. {
  138. Directory.Delete(localUpdateFolder, true);
  139. }
  140. Directory.CreateDirectory(localUpdateFolder);
  141. this.totalCount = updateInfos.UpdateFiles.Count;
  142. foreach (var updateFile in updateInfos.UpdateFiles)
  143. {
  144. DownList.Enqueue(updateFile);
  145. }
  146. UpdateFile updateFileInfo = DownList.Dequeue();
  147. totalCount_Completed++;
  148. this.msg = Update_NowDownFile + updateFileInfo.FilePath;
  149. SetMessageText(this.msg);
  150. string downloadfile= updateFileInfo.FilePath;
  151. if (updateInfos.IsCompress && !updateFileInfo.IsConfig)
  152. {
  153. downloadfile =downloadfile.Substring(0,downloadfile.LastIndexOf(updateFileInfo.Extension))+".gz"; ////下载压缩文件
  154. downloadfile= downloadfile.Replace('\\','/');
  155. }
  156. string localFileName = string.Format("{0}/{1}", localUpdateFolder, downloadfile);
  157. string remotefile = string.Format("{0}/{1}", applictionUpdateUrl, downloadfile);
  158. FileInfo fileInfo = new FileInfo(localFileName);
  159. if (!Directory.Exists(fileInfo.DirectoryName))
  160. {
  161. Directory.CreateDirectory(fileInfo.DirectoryName);
  162. }
  163. //下载更新至本地
  164. webClient.DownloadFileAsync(new Uri(remotefile), localFileName, updateFileInfo);
  165. isRunning = true;
  166. }
  167. //下载中途,进度条控制,百分比显示
  168. void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  169. {
  170. float totalBytesToReceive = e.TotalBytesToReceive;
  171. float bytesReceived = e.BytesReceived;
  172. int progressPercentage = e.ProgressPercentage;
  173. msg = (e.UserState as UpdateFile).FilePath;
  174. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  175. {
  176. pbCurrent.Value = progressPercentage;
  177. tbCurrentControl.Text = (bytesReceived / totalBytesToReceive).ToString("0%");
  178. }));
  179. }
  180. //下载完成
  181. void webClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
  182. {
  183. if (e.Error != null)
  184. {
  185. SetMessageText((e.UserState as UpdateFile).FilePath + e.Error.Message);
  186. isRunning = false;
  187. return;
  188. }
  189. try
  190. {
  191. if (!isRunning)
  192. {
  193. return;
  194. }
  195. //进度条控制,百分比显示
  196. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  197. {
  198. pbTotal.Value = (100 / totalCount) * totalCount_Completed;
  199. tbControl.Text = (totalCount_Completed / totalCount).ToString("0%");
  200. }));
  201. if (DownList.Count > 0)
  202. {
  203. UpdateFile updateFileInfo = DownList.Dequeue();
  204. totalCount_Completed++;
  205. this.msg = Update_NowDownFile + updateFileInfo.FilePath;
  206. SetMessageText(this.msg);
  207. string downloadfile = updateFileInfo.FilePath;
  208. if (updateInfos.IsCompress && !updateFileInfo.IsConfig)
  209. {
  210. downloadfile = downloadfile.Substring(0, downloadfile.LastIndexOf(updateFileInfo.Extension)) + ".gz"; ////下载压缩文件
  211. downloadfile = downloadfile.Replace('\\', '/');
  212. }
  213. string localFileName = string.Format("{0}/{1}", localUpdateFolder, downloadfile);
  214. string remotefile = string.Format("{0}/{1}", applictionUpdateUrl, downloadfile);
  215. FileInfo fileInfo = new FileInfo(localFileName);
  216. if (!Directory.Exists(fileInfo.DirectoryName))
  217. {
  218. Directory.CreateDirectory(fileInfo.DirectoryName);
  219. }
  220. webClient.DownloadFileAsync(new Uri(remotefile), localFileName, updateFileInfo);
  221. }
  222. else
  223. {
  224. //全部下载完成
  225. SetMessageText(APP_Updating);
  226. BackUpdateFile();
  227. ReplaceFiles();
  228. CreateUpdateConfig();
  229. SetMessageText(Update_FileAllFinish);
  230. isRunning = false;
  231. App.Current.Shutdown();
  232. }
  233. }
  234. catch (Exception ex)
  235. {
  236. throw ex;
  237. }
  238. }
  239. /// <summary>
  240. /// 备份旧版本至bak
  241. /// </summary>
  242. private void BackUpdateFile()
  243. {
  244. try
  245. {
  246. if (Directory.Exists(localBackupFolder))
  247. {
  248. Directory.Delete(localBackupFolder, true);
  249. }
  250. Directory.CreateDirectory(localBackupFolder);
  251. foreach (var item in updateInfos.UpdateFiles)
  252. {
  253. string tempItem = item.FilePath.Replace('/', '\\');
  254. if (File.Exists(localAppFolder + tempItem))
  255. {
  256. var directoryIndex = tempItem.LastIndexOf("\\", System.StringComparison.Ordinal);
  257. if (directoryIndex > 0)
  258. {
  259. var directory = item.FilePath.Substring(0, directoryIndex);
  260. Directory.CreateDirectory(localBackupFolder + "\\" + directory);
  261. }
  262. File.Copy(localAppFolder + tempItem, localBackupFolder + "\\" + tempItem, true);
  263. }
  264. }
  265. }
  266. catch (Exception ex)
  267. {
  268. throw ex;
  269. }
  270. }
  271. /// <summary>
  272. /// 下载更新的文件从Update覆盖到使用目录
  273. /// </summary>
  274. private void ReplaceFiles()
  275. {
  276. try
  277. {
  278. foreach (var item in updateInfos.UpdateFiles)
  279. {
  280. //如果更新的是Muchinfo.MTPClient.Update,则先把源文件重命名,然后复制过去。最后删除重命名过的源文件
  281. var isfileExists = File.Exists(localUpdateFolder + "\\" + item.FilePath) ||
  282. File.Exists(localUpdateFolder + "\\" +
  283. item.FilePath.Replace(item.Extension, ".gz"));
  284. if (isfileExists)
  285. {
  286. if (item.FilePath == "Client.Update.exe")
  287. {
  288. File.Move(localAppFolder + item.FilePath, localAppFolder + "Client.Update.old.exe");
  289. }
  290. var directoryIndex = item.FilePath.LastIndexOf("\\", System.StringComparison.Ordinal);
  291. if (directoryIndex > 0)
  292. {
  293. var directory = item.FilePath.Substring(0, directoryIndex);
  294. var direPath = localAppFolder + "\\" + directory;
  295. if (!Directory.Exists(direPath))
  296. {
  297. Directory.CreateDirectory(direPath);
  298. }
  299. }
  300. if (updateInfos.IsCompress && !item.IsConfig) //解压文件
  301. {
  302. var compressFile = localUpdateFolder + "\\" + item.FilePath.Replace(item.Extension,".gz") ;
  303. DeCompress(compressFile, localAppFolder + item.FilePath);
  304. }
  305. else
  306. {
  307. File.Copy(localUpdateFolder + "\\" + item.FilePath, localAppFolder + item.FilePath, true);
  308. }
  309. }
  310. }
  311. }
  312. catch (Exception ex)
  313. {
  314. throw ex;
  315. }
  316. }
  317. /// <summary>
  318. /// 对目标压缩文件解压缩,将内容解压缩到指定文件夹
  319. /// </summary>
  320. /// <param name="sourceName">压缩文件</param>
  321. /// <param name="targetPath">解压缩目录</param>
  322. public static void DeCompress(string sourceName, string targetPath)
  323. {
  324. using (Stream source = File.OpenRead(sourceName))
  325. {
  326. using (FileStream destination = new FileStream(targetPath, FileMode.Create, FileAccess.Write))
  327. {
  328. using (GZipStream input = new GZipStream(source, CompressionMode.Decompress, true))
  329. {
  330. byte[] bytes = new byte[4096];
  331. int n;
  332. while ((n = input.Read(bytes, 0, bytes.Length)) != 0)
  333. {
  334. destination.Write(bytes, 0, n);
  335. }
  336. }
  337. destination.Flush();
  338. destination.Close();
  339. }
  340. }
  341. }
  342. /// <summary>
  343. /// 生成本地配置目录
  344. /// </summary>
  345. private void CreateUpdateConfig()
  346. {
  347. var updateHelper = new UpdateHelper();
  348. var updateInfo = updateHelper.CreateUpdateInfoFile(AppDomain.CurrentDomain.BaseDirectory, new string[] { update_bakDir, update_Dir });
  349. var savePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
  350. updateInfo.GetType().Name + ".xml");
  351. updateHelper.SaveUpdateXml(updateInfo, savePath);
  352. }
  353. #endregion
  354. void Current_Exit(object sender, ExitEventArgs e)
  355. {
  356. if (webClient != null)
  357. {
  358. webClient.Dispose();
  359. }
  360. if (updateInfos == null)
  361. {
  362. return;
  363. }
  364. //下载中途、完成后关闭Appliction程序
  365. UpdateManage.RegisterChart(); ////图表更新
  366. if (updateInfos.ReStart)
  367. {
  368. string appName = updateInfos.StartAppName;
  369. if (!string.IsNullOrEmpty(appName))
  370. {
  371. string path = localAppFolder + appName;
  372. if (File.Exists(path))
  373. {
  374. System.Diagnostics.Process.Start(path);
  375. }
  376. }
  377. }
  378. }
  379. void bnt_Close_Click(object sender, RoutedEventArgs e)
  380. {
  381. App.Current.Shutdown();
  382. }
  383. private void Window_MouseDown(object sender, MouseButtonEventArgs e)
  384. {
  385. if (e.LeftButton == MouseButtonState.Pressed)
  386. DragMove();
  387. }
  388. private void SetMessageText(string text)
  389. {
  390. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  391. {
  392. this.tbMessage.Text = text;
  393. }));
  394. }
  395. #endregion
  396. }
  397. }