AppUpdater.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. using System;
  2. using System.Collections;
  3. using System.ComponentModel;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Windows.Forms;
  8. namespace Microsoft.Samples.AppUpdater
  9. {
  10. public class AppUpdater : Component, ISupportInitialize
  11. {
  12. public delegate bool CheckForUpdateEventHandler(object sender, EventArgs e);
  13. public delegate void UpdateDetectedEventHandler(object sender, UpdateDetectedEventArgs e);
  14. public delegate void UpdateCompleteEventHandler(object sender, UpdateCompleteEventArgs e);
  15. public delegate void NotifyUpdateFileInfoEventHandler(object sender, NotifyUpdateFileInfoEventArgs e);
  16. public const int RestartAppReturnValue = 2;
  17. private Container components;
  18. private bool LoadingAssembly;
  19. private Control EventControl;
  20. internal AppManifest Manifest;
  21. private AppDownloader _Downloader;
  22. private ServerPoller _Poller;
  23. private string _UpdateUrl = "http://localhost/";
  24. private ChangeDetectionModes _ChangeDetectionMode = ChangeDetectionModes.DirectFileCheck;
  25. private bool _ShowDefaultUI;
  26. private bool _AutoFileLoad;
  27. [Category("AppUpdate Configuration")]
  28. [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
  29. [Description("The object that downloads and installs new updates.")]
  30. [TypeConverter(typeof(ExpandableObjectConverter))]
  31. public AppDownloader Downloader
  32. {
  33. get
  34. {
  35. return _Downloader;
  36. }
  37. set
  38. {
  39. _Downloader = value;
  40. }
  41. }
  42. [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
  43. [TypeConverter(typeof(ExpandableObjectConverter))]
  44. [Description("The object that periodically polls for new updates.")]
  45. [Category("AppUpdate Configuration")]
  46. public ServerPoller Poller
  47. {
  48. get
  49. {
  50. return _Poller;
  51. }
  52. set
  53. {
  54. _Poller = value;
  55. }
  56. }
  57. [Category("AppUpdate Configuration")]
  58. [Description("The Url to download updates from.")]
  59. [DefaultValue("http://localhost/")]
  60. public string UpdateUrl
  61. {
  62. get
  63. {
  64. return _UpdateUrl;
  65. }
  66. set
  67. {
  68. _UpdateUrl = value;
  69. }
  70. }
  71. [Category("AppUpdate Configuration")]
  72. [Description("The way to detect new updates.")]
  73. [DefaultValue(ChangeDetectionModes.DirectFileCheck)]
  74. public ChangeDetectionModes ChangeDetectionMode
  75. {
  76. get
  77. {
  78. return _ChangeDetectionMode;
  79. }
  80. set
  81. {
  82. _ChangeDetectionMode = value;
  83. }
  84. }
  85. [Category("AppUpdate Configuration")]
  86. [Description("Determines whether the default UI is shown or supressed.")]
  87. [DefaultValue(false)]
  88. public bool ShowDefaultUI
  89. {
  90. get
  91. {
  92. return _ShowDefaultUI;
  93. }
  94. set
  95. {
  96. _ShowDefaultUI = value;
  97. }
  98. }
  99. [DefaultValue(false)]
  100. [Description("Enables auto-download of missing assemblies.")]
  101. [Category("AppUpdate Configuration")]
  102. public bool AutoFileLoad
  103. {
  104. get
  105. {
  106. return _AutoFileLoad;
  107. }
  108. set
  109. {
  110. _AutoFileLoad = value;
  111. }
  112. }
  113. public event CheckForUpdateEventHandler OnCheckForUpdate;
  114. public event UpdateDetectedEventHandler OnUpdateDetected;
  115. public event UpdateCompleteEventHandler OnUpdateComplete;
  116. public event NotifyUpdateFileInfoEventHandler OnNotifyUpdateFileInfo;
  117. public AppUpdater()
  118. {
  119. Poller = new ServerPoller(this);
  120. Downloader = new AppDownloader(this);
  121. }
  122. public AppUpdater(IContainer container)
  123. {
  124. Poller = new ServerPoller(this);
  125. Downloader = new AppDownloader(this);
  126. container.Add(this);
  127. InitializeComponent();
  128. }
  129. public AppUpdater(string updateUrl, ChangeDetectionModes changeDetectionMode, bool showDefaultUI, bool autoFileLoad, bool validateAssemblies)
  130. {
  131. Poller = new ServerPoller(this);
  132. Downloader = new AppDownloader(this);
  133. UpdateUrl = updateUrl;
  134. ChangeDetectionMode = changeDetectionMode;
  135. ShowDefaultUI = showDefaultUI;
  136. AutoFileLoad = autoFileLoad;
  137. Downloader.ValidateAssemblies = validateAssemblies;
  138. Initialize();
  139. }
  140. public void BeginInit()
  141. {
  142. }
  143. public void EndInit()
  144. {
  145. if (!base.DesignMode)
  146. {
  147. Initialize();
  148. }
  149. }
  150. private void InitializeComponent()
  151. {
  152. components = new Container();
  153. }
  154. public void Initialize()
  155. {
  156. string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";
  157. string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
  158. fileNameWithoutExtension += ".xml";
  159. path = Path.Combine(path, fileNameWithoutExtension);
  160. Manifest = AppManifest.Load(path);
  161. if (ChangeDetectionMode == ChangeDetectionModes.DirectFileCheck)
  162. {
  163. EnableManifestGeneration();
  164. }
  165. if (AutoFileLoad)
  166. {
  167. EnableFileAutoLoad();
  168. }
  169. if (Poller.AutoStart)
  170. {
  171. Poller.Start();
  172. }
  173. Downloader.OnUpdateComplete += OnDownloaderComplete;
  174. Downloader.OnNotifyUpdateFileInfo += OnDownloaderUpdateFileInfo;
  175. Application.ApplicationExit += OnApplicationExit;
  176. EventControl = new Control();
  177. _ = EventControl.Handle;
  178. if (Manifest.State.Phase != 0)
  179. {
  180. Downloader.Start();
  181. }
  182. }
  183. public void DownloadUpdate()
  184. {
  185. Downloader.Start();
  186. }
  187. public bool CheckForUpdates()
  188. {
  189. bool flag = false;
  190. if (this.OnCheckForUpdate != null)
  191. {
  192. flag = this.OnCheckForUpdate(this, new EventArgs());
  193. }
  194. else if (ChangeDetectionMode == ChangeDetectionModes.ServerManifestCheck)
  195. {
  196. ServerManifest serverManifest = new ServerManifest();
  197. serverManifest.Load(UpdateUrl);
  198. flag = serverManifest.IsServerVersionNewer(GetLatestInstalledVersion());
  199. }
  200. else
  201. {
  202. foreach (object resource2 in Manifest.Resources.ResourceList)
  203. {
  204. Resource resource = (Resource)((DictionaryEntry)resource2).Value;
  205. string url = UpdateUrl + resource.Name;
  206. string filePath = resource.FilePath;
  207. if (WebFileLoader.CheckForFileUpdate(url, filePath))
  208. {
  209. flag = true;
  210. }
  211. }
  212. }
  213. if (this.OnUpdateDetected != null)
  214. {
  215. Delegate[] invocationList = this.OnUpdateDetected.GetInvocationList();
  216. for (int i = 0; i < invocationList.Length; i++)
  217. {
  218. UpdateDetectedEventHandler method = (UpdateDetectedEventHandler)invocationList[i];
  219. UpdateDetectedEventArgs updateDetectedEventArgs = new UpdateDetectedEventArgs();
  220. updateDetectedEventArgs.HasNewVersion = flag;
  221. EventControl.BeginInvoke(method, this, updateDetectedEventArgs);
  222. }
  223. }
  224. return flag;
  225. }
  226. public static Version GetLatestInstalledVersion()
  227. {
  228. string directoryName = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
  229. directoryName = Path.Combine(Directory.GetParent(directoryName).FullName, "AppStart.config");
  230. AppStartConfig appStartConfig = AppStartConfig.Load(directoryName);
  231. AssemblyName assemblyName = AssemblyName.GetAssemblyName(appStartConfig.AppExePath);
  232. return assemblyName.Version;
  233. }
  234. public void RestartApp()
  235. {
  236. Environment.ExitCode = 2;
  237. Application.Exit();
  238. Poller.Stop();
  239. Downloader.Stop();
  240. }
  241. private void OnDownloaderComplete(object sender, UpdateCompleteEventArgs args)
  242. {
  243. if (this.OnUpdateComplete != null)
  244. {
  245. Delegate[] invocationList = this.OnUpdateComplete.GetInvocationList();
  246. for (int i = 0; i < invocationList.Length; i++)
  247. {
  248. UpdateCompleteEventHandler method = (UpdateCompleteEventHandler)invocationList[i];
  249. EventControl.BeginInvoke(method, sender, args);
  250. }
  251. }
  252. EventControl.BeginInvoke(new UpdateCompleteEventHandler(UpdateCompleteOps), sender, args);
  253. }
  254. private void OnDownloaderUpdateFileInfo(object sender, NotifyUpdateFileInfoEventArgs args)
  255. {
  256. if (this.OnUpdateComplete != null)
  257. {
  258. Delegate[] invocationList = this.OnNotifyUpdateFileInfo.GetInvocationList();
  259. for (int i = 0; i < invocationList.Length; i++)
  260. {
  261. NotifyUpdateFileInfoEventHandler method = (NotifyUpdateFileInfoEventHandler)invocationList[i];
  262. EventControl.BeginInvoke(method, sender, args);
  263. }
  264. }
  265. }
  266. private void UpdateCompleteOps(object sender, UpdateCompleteEventArgs args)
  267. {
  268. if (!ShowDefaultUI)
  269. {
  270. return;
  271. }
  272. if (args.UpdateSucceeded)
  273. {
  274. UpdateForm updateForm = new UpdateForm();
  275. if (updateForm.ShowDialog() == DialogResult.Yes)
  276. {
  277. RestartApp();
  278. }
  279. }
  280. else
  281. {
  282. string text = "The auto-update of this application failed with the following error message: \r\n\r\n" + args.ErrorMessage + "\r\n\r\nTo correct this problem, try rebooting the computer & re-launching this application.";
  283. MessageBox.Show(text, "Application Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  284. }
  285. }
  286. private void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args)
  287. {
  288. string[] array = args.LoadedAssembly.Location.Split('\\');
  289. int num = array.Length - 1;
  290. string name = array[num];
  291. if (!Manifest.Resources.ResourceExists(name) && IsLocalAssembly(args.LoadedAssembly))
  292. {
  293. Resource resource = new Resource();
  294. resource.FilePath = args.LoadedAssembly.Location;
  295. resource.Name = name;
  296. resource.AddedAtRuntime = true;
  297. Manifest.Resources.AddResource(resource);
  298. Manifest.Update();
  299. }
  300. }
  301. private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
  302. {
  303. if (LoadingAssembly)
  304. {
  305. return null;
  306. }
  307. LoadingAssembly = true;
  308. string[] array = args.Name.Split(new char[1]
  309. {
  310. ','
  311. }, 2);
  312. string text = array[0] + ".dll";
  313. string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, text);
  314. string text2;
  315. if (ChangeDetectionMode == ChangeDetectionModes.DirectFileCheck)
  316. {
  317. text2 = UpdateUrl + text;
  318. }
  319. else
  320. {
  321. ServerManifest serverManifest = new ServerManifest();
  322. serverManifest.Load(UpdateUrl);
  323. text2 = Path.Combine(serverManifest.ApplicationUrl, text);
  324. }
  325. try
  326. {
  327. WebFileLoader.UpdateFile(text2, filePath);
  328. }
  329. catch (Exception)
  330. {
  331. if (ShowDefaultUI)
  332. {
  333. MessageBox.Show("Unable to auto-download the missing parts of the application from:\r\n" + text2 + "\r\n\r\nMake sure your connected to the network. If the problem persists re-install the application.");
  334. }
  335. return null;
  336. }
  337. try
  338. {
  339. return Assembly.Load(args.Name);
  340. }
  341. catch (Exception)
  342. {
  343. return null;
  344. }
  345. finally
  346. {
  347. LoadingAssembly = false;
  348. }
  349. }
  350. private bool IsLocalAssembly(Assembly assembly)
  351. {
  352. string text = assembly.Location.Replace("/", "\\").ToLower(new CultureInfo("en-US"));
  353. string text2 = AppDomain.CurrentDomain.BaseDirectory.ToLower(new CultureInfo("en-US"));
  354. if (text.StartsWith(text2.ToLower(new CultureInfo("en-US"))) && !assembly.FullName.StartsWith("AppManager"))
  355. {
  356. return true;
  357. }
  358. return false;
  359. }
  360. private void OnApplicationExit(object sender, EventArgs args)
  361. {
  362. Poller.Stop();
  363. Downloader.Stop();
  364. }
  365. private void EnableFileAutoLoad()
  366. {
  367. AppDomain currentDomain = AppDomain.CurrentDomain;
  368. currentDomain.AssemblyResolve += OnAssemblyResolve;
  369. }
  370. private void DisableFileAutoLoad()
  371. {
  372. AppDomain currentDomain = AppDomain.CurrentDomain;
  373. currentDomain.AssemblyResolve -= OnAssemblyResolve;
  374. }
  375. private void EnableManifestGeneration()
  376. {
  377. AppDomain currentDomain = AppDomain.CurrentDomain;
  378. currentDomain.AssemblyLoad += OnAssemblyLoad;
  379. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  380. for (int i = 0; i < assemblies.Length; i++)
  381. {
  382. if (IsLocalAssembly(assemblies[i]))
  383. {
  384. Resource resource = new Resource();
  385. string[] array = assemblies[i].Location.Split('\\');
  386. int num = array.Length - 1;
  387. resource.FilePath = assemblies[i].Location;
  388. resource.Name = array[num];
  389. resource.AddedAtRuntime = true;
  390. Manifest.Resources.AddResource(resource);
  391. Manifest.Update();
  392. }
  393. }
  394. }
  395. private void DisableManifestGeneration()
  396. {
  397. AppDomain currentDomain = AppDomain.CurrentDomain;
  398. currentDomain.AssemblyLoad -= OnAssemblyLoad;
  399. }
  400. }
  401. }