BaseApplicationHost.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Implementations.Archiving;
  4. using MediaBrowser.Common.Implementations.IO;
  5. using MediaBrowser.Common.Implementations.ScheduledTasks;
  6. using MediaBrowser.Common.Implementations.Security;
  7. using MediaBrowser.Common.Implementations.Serialization;
  8. using MediaBrowser.Common.Implementations.Updates;
  9. using MediaBrowser.Common.IO;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Common.Plugins;
  12. using MediaBrowser.Common.Progress;
  13. using MediaBrowser.Common.ScheduledTasks;
  14. using MediaBrowser.Common.Security;
  15. using MediaBrowser.Common.Updates;
  16. using MediaBrowser.Model.Events;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Model.Serialization;
  20. using MediaBrowser.Model.Updates;
  21. using ServiceStack;
  22. using SimpleInjector;
  23. using System;
  24. using System.Collections.Generic;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Net;
  28. using System.Reflection;
  29. using System.Text;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. namespace MediaBrowser.Common.Implementations
  33. {
  34. /// <summary>
  35. /// Class BaseApplicationHost
  36. /// </summary>
  37. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  38. public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationHost, IDependencyContainer
  39. where TApplicationPathsType : class, IApplicationPaths
  40. {
  41. /// <summary>
  42. /// Occurs when [has pending restart changed].
  43. /// </summary>
  44. public event EventHandler HasPendingRestartChanged;
  45. /// <summary>
  46. /// Occurs when [application updated].
  47. /// </summary>
  48. public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
  49. /// <summary>
  50. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  51. /// </summary>
  52. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  53. public bool HasPendingRestart { get; private set; }
  54. /// <summary>
  55. /// Gets or sets the logger.
  56. /// </summary>
  57. /// <value>The logger.</value>
  58. protected ILogger Logger { get; private set; }
  59. /// <summary>
  60. /// Gets or sets the plugins.
  61. /// </summary>
  62. /// <value>The plugins.</value>
  63. public IEnumerable<IPlugin> Plugins { get; protected set; }
  64. /// <summary>
  65. /// Gets or sets the log manager.
  66. /// </summary>
  67. /// <value>The log manager.</value>
  68. public ILogManager LogManager { get; protected set; }
  69. /// <summary>
  70. /// Gets the application paths.
  71. /// </summary>
  72. /// <value>The application paths.</value>
  73. protected TApplicationPathsType ApplicationPaths { get; private set; }
  74. /// <summary>
  75. /// The container
  76. /// </summary>
  77. protected readonly Container Container = new Container();
  78. /// <summary>
  79. /// The json serializer
  80. /// </summary>
  81. public IJsonSerializer JsonSerializer { get; private set; }
  82. /// <summary>
  83. /// The _XML serializer
  84. /// </summary>
  85. protected readonly IXmlSerializer XmlSerializer = new XmlSerializer();
  86. /// <summary>
  87. /// Gets assemblies that failed to load
  88. /// </summary>
  89. /// <value>The failed assemblies.</value>
  90. public List<string> FailedAssemblies { get; protected set; }
  91. /// <summary>
  92. /// Gets all types within all running assemblies
  93. /// </summary>
  94. /// <value>All types.</value>
  95. public Type[] AllTypes { get; protected set; }
  96. /// <summary>
  97. /// Gets all concrete types.
  98. /// </summary>
  99. /// <value>All concrete types.</value>
  100. public Type[] AllConcreteTypes { get; protected set; }
  101. /// <summary>
  102. /// The disposable parts
  103. /// </summary>
  104. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  105. /// <summary>
  106. /// Gets a value indicating whether this instance is first run.
  107. /// </summary>
  108. /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
  109. public bool IsFirstRun { get; private set; }
  110. /// <summary>
  111. /// Gets the kernel.
  112. /// </summary>
  113. /// <value>The kernel.</value>
  114. protected ITaskManager TaskManager { get; private set; }
  115. /// <summary>
  116. /// Gets the security manager.
  117. /// </summary>
  118. /// <value>The security manager.</value>
  119. protected ISecurityManager SecurityManager { get; private set; }
  120. /// <summary>
  121. /// Gets the HTTP client.
  122. /// </summary>
  123. /// <value>The HTTP client.</value>
  124. protected IHttpClient HttpClient { get; private set; }
  125. /// <summary>
  126. /// Gets the network manager.
  127. /// </summary>
  128. /// <value>The network manager.</value>
  129. protected INetworkManager NetworkManager { get; private set; }
  130. /// <summary>
  131. /// Gets the configuration manager.
  132. /// </summary>
  133. /// <value>The configuration manager.</value>
  134. protected IConfigurationManager ConfigurationManager { get; private set; }
  135. /// <summary>
  136. /// Gets or sets the installation manager.
  137. /// </summary>
  138. /// <value>The installation manager.</value>
  139. protected IInstallationManager InstallationManager { get; private set; }
  140. protected IFileSystem FileSystemManager { get; private set; }
  141. /// <summary>
  142. /// Gets or sets the zip client.
  143. /// </summary>
  144. /// <value>The zip client.</value>
  145. protected IZipClient ZipClient { get; private set; }
  146. protected IIsoManager IsoManager { get; private set; }
  147. /// <summary>
  148. /// Gets the name.
  149. /// </summary>
  150. /// <value>The name.</value>
  151. public abstract string Name { get; }
  152. /// <summary>
  153. /// Gets a value indicating whether this instance is running as service.
  154. /// </summary>
  155. /// <value><c>true</c> if this instance is running as service; otherwise, <c>false</c>.</value>
  156. public abstract bool IsRunningAsService { get; }
  157. /// <summary>
  158. /// Initializes a new instance of the <see cref="BaseApplicationHost{TApplicationPathsType}"/> class.
  159. /// </summary>
  160. protected BaseApplicationHost(TApplicationPathsType applicationPaths, ILogManager logManager)
  161. {
  162. FailedAssemblies = new List<string>();
  163. ApplicationPaths = applicationPaths;
  164. LogManager = logManager;
  165. ConfigurationManager = GetConfigurationManager();
  166. }
  167. /// <summary>
  168. /// Inits this instance.
  169. /// </summary>
  170. /// <returns>Task.</returns>
  171. public virtual async Task Init(IProgress<double> progress)
  172. {
  173. try
  174. {
  175. // https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.WebHost.IntegrationTests/Web.config#L4
  176. Licensing.RegisterLicense("1001-e1JlZjoxMDAxLE5hbWU6VGVzdCBCdXNpbmVzcyxUeXBlOkJ1c2luZXNzLEhhc2g6UHVNTVRPclhvT2ZIbjQ5MG5LZE1mUTd5RUMzQnBucTFEbTE3TDczVEF4QUNMT1FhNXJMOWkzVjFGL2ZkVTE3Q2pDNENqTkQyUktRWmhvUVBhYTBiekJGUUZ3ZE5aZHFDYm9hL3lydGlwUHI5K1JsaTBYbzNsUC85cjVJNHE5QVhldDN6QkE4aTlvdldrdTgyTk1relY2eis2dFFqTThYN2lmc0JveHgycFdjPSxFeHBpcnk6MjAxMy0wMS0wMX0=");
  177. }
  178. catch
  179. {
  180. // Failing under mono
  181. }
  182. progress.Report(1);
  183. JsonSerializer = CreateJsonSerializer();
  184. Logger = LogManager.GetLogger("App");
  185. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  186. progress.Report(2);
  187. LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
  188. ? LogSeverity.Debug
  189. : LogSeverity.Info;
  190. // Put the app config in the log for troubleshooting purposes
  191. Logger.LogMultiline("Application Configuration:", LogSeverity.Info, new StringBuilder(JsonSerializer.SerializeToString(ConfigurationManager.CommonConfiguration)));
  192. progress.Report(3);
  193. DiscoverTypes();
  194. progress.Report(14);
  195. Logger.Info("Version {0} initializing", ApplicationVersion);
  196. SetHttpLimit();
  197. progress.Report(15);
  198. var innerProgress = new ActionableProgress<double>();
  199. innerProgress.RegisterAction(p => progress.Report((.8 * p) + 15));
  200. await RegisterResources(innerProgress).ConfigureAwait(false);
  201. FindParts();
  202. progress.Report(95);
  203. await InstallIsoMounters(CancellationToken.None).ConfigureAwait(false);
  204. progress.Report(100);
  205. }
  206. protected virtual IJsonSerializer CreateJsonSerializer()
  207. {
  208. return new JsonSerializer();
  209. }
  210. private void SetHttpLimit()
  211. {
  212. try
  213. {
  214. // Increase the max http request limit
  215. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  216. }
  217. catch (Exception ex)
  218. {
  219. Logger.ErrorException("Error setting http limit", ex);
  220. }
  221. }
  222. /// <summary>
  223. /// Installs the iso mounters.
  224. /// </summary>
  225. /// <param name="cancellationToken">The cancellation token.</param>
  226. /// <returns>Task.</returns>
  227. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  228. {
  229. var list = new List<IIsoMounter>();
  230. foreach (var isoMounter in GetExports<IIsoMounter>())
  231. {
  232. try
  233. {
  234. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  235. {
  236. Logger.Info("Installing {0}", isoMounter.Name);
  237. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  238. }
  239. list.Add(isoMounter);
  240. }
  241. catch (Exception ex)
  242. {
  243. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  244. }
  245. }
  246. IsoManager.AddParts(list);
  247. }
  248. /// <summary>
  249. /// Runs the startup tasks.
  250. /// </summary>
  251. /// <returns>Task.</returns>
  252. public virtual Task RunStartupTasks()
  253. {
  254. return Task.Run(() =>
  255. {
  256. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  257. Task.Run(() => ConfigureAutorun());
  258. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  259. });
  260. }
  261. /// <summary>
  262. /// Configures the autorun.
  263. /// </summary>
  264. private void ConfigureAutorun()
  265. {
  266. try
  267. {
  268. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  269. }
  270. catch (Exception ex)
  271. {
  272. Logger.ErrorException("Error configuring autorun", ex);
  273. }
  274. }
  275. /// <summary>
  276. /// Gets the composable part assemblies.
  277. /// </summary>
  278. /// <returns>IEnumerable{Assembly}.</returns>
  279. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  280. /// <summary>
  281. /// Gets the configuration manager.
  282. /// </summary>
  283. /// <returns>IConfigurationManager.</returns>
  284. protected abstract IConfigurationManager GetConfigurationManager();
  285. /// <summary>
  286. /// Finds the parts.
  287. /// </summary>
  288. protected virtual void FindParts()
  289. {
  290. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  291. Plugins = GetExports<IPlugin>();
  292. }
  293. /// <summary>
  294. /// Discovers the types.
  295. /// </summary>
  296. protected void DiscoverTypes()
  297. {
  298. FailedAssemblies.Clear();
  299. var assemblies = GetComposablePartAssemblies().ToList();
  300. foreach (var assembly in assemblies)
  301. {
  302. Logger.Info("Loading {0}", assembly.FullName);
  303. }
  304. AllTypes = assemblies.SelectMany(GetTypes).ToArray();
  305. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  306. }
  307. /// <summary>
  308. /// Registers resources that classes will depend on
  309. /// </summary>
  310. /// <returns>Task.</returns>
  311. protected virtual Task RegisterResources(IProgress<double> progress)
  312. {
  313. return Task.Run(() =>
  314. {
  315. RegisterSingleInstance(ConfigurationManager);
  316. RegisterSingleInstance<IApplicationHost>(this);
  317. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  318. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger);
  319. RegisterSingleInstance(JsonSerializer);
  320. RegisterSingleInstance(XmlSerializer);
  321. RegisterSingleInstance(LogManager);
  322. RegisterSingleInstance(Logger);
  323. RegisterSingleInstance(TaskManager);
  324. FileSystemManager = CreateFileSystemManager();
  325. RegisterSingleInstance(FileSystemManager);
  326. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger, FileSystemManager, ConfigurationManager);
  327. RegisterSingleInstance(HttpClient);
  328. NetworkManager = CreateNetworkManager();
  329. RegisterSingleInstance(NetworkManager);
  330. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, NetworkManager, LogManager);
  331. RegisterSingleInstance(SecurityManager);
  332. InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, NetworkManager, ConfigurationManager);
  333. RegisterSingleInstance(InstallationManager);
  334. ZipClient = new ZipClient();
  335. RegisterSingleInstance(ZipClient);
  336. IsoManager = new IsoManager();
  337. RegisterSingleInstance(IsoManager);
  338. RegisterModules();
  339. });
  340. }
  341. private void RegisterModules()
  342. {
  343. var moduleTypes = GetExportTypes<IDependencyModule>();
  344. foreach (var type in moduleTypes)
  345. {
  346. try
  347. {
  348. var instance = Activator.CreateInstance(type) as IDependencyModule;
  349. if (instance != null)
  350. instance.BindDependencies(this);
  351. }
  352. catch (Exception ex)
  353. {
  354. Logger.ErrorException("Error setting up dependency bindings for " + type.Name, ex);
  355. }
  356. }
  357. }
  358. protected virtual IFileSystem CreateFileSystemManager()
  359. {
  360. return new CommonFileSystem(Logger, true);
  361. }
  362. /// <summary>
  363. /// Gets a list of types within an assembly
  364. /// This will handle situations that would normally throw an exception - such as a type within the assembly that depends on some other non-existant reference
  365. /// </summary>
  366. /// <param name="assembly">The assembly.</param>
  367. /// <returns>IEnumerable{Type}.</returns>
  368. /// <exception cref="System.ArgumentNullException">assembly</exception>
  369. protected IEnumerable<Type> GetTypes(Assembly assembly)
  370. {
  371. if (assembly == null)
  372. {
  373. throw new ArgumentNullException("assembly");
  374. }
  375. try
  376. {
  377. return assembly.GetTypes();
  378. }
  379. catch (ReflectionTypeLoadException ex)
  380. {
  381. // If it fails we can still get a list of the Types it was able to resolve
  382. return ex.Types.Where(t => t != null);
  383. }
  384. }
  385. protected abstract INetworkManager CreateNetworkManager();
  386. /// <summary>
  387. /// Creates an instance of type and resolves all constructor dependancies
  388. /// </summary>
  389. /// <param name="type">The type.</param>
  390. /// <returns>System.Object.</returns>
  391. public object CreateInstance(Type type)
  392. {
  393. try
  394. {
  395. return Container.GetInstance(type);
  396. }
  397. catch (Exception ex)
  398. {
  399. Logger.Error("Error creating {0}", ex, type.Name);
  400. throw;
  401. }
  402. }
  403. /// <summary>
  404. /// Creates the instance safe.
  405. /// </summary>
  406. /// <param name="type">The type.</param>
  407. /// <returns>System.Object.</returns>
  408. protected object CreateInstanceSafe(Type type)
  409. {
  410. try
  411. {
  412. return Container.GetInstance(type);
  413. }
  414. catch (Exception ex)
  415. {
  416. Logger.Error("Error creating {0}", ex, type.Name);
  417. // Don't blow up in release mode
  418. return null;
  419. }
  420. }
  421. void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
  422. {
  423. RegisterSingleInstance(obj, manageLifetime);
  424. }
  425. /// <summary>
  426. /// Registers the specified obj.
  427. /// </summary>
  428. /// <typeparam name="T"></typeparam>
  429. /// <param name="obj">The obj.</param>
  430. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  431. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  432. where T : class
  433. {
  434. Container.RegisterSingle(obj);
  435. if (manageLifetime)
  436. {
  437. var disposable = obj as IDisposable;
  438. if (disposable != null)
  439. {
  440. DisposableParts.Add(disposable);
  441. }
  442. }
  443. }
  444. void IDependencyContainer.RegisterSingleInstance<T>(Func<T> func)
  445. {
  446. RegisterSingleInstance(func);
  447. }
  448. /// <summary>
  449. /// Registers the single instance.
  450. /// </summary>
  451. /// <typeparam name="T"></typeparam>
  452. /// <param name="func">The func.</param>
  453. protected void RegisterSingleInstance<T>(Func<T> func)
  454. where T : class
  455. {
  456. Container.RegisterSingle(func);
  457. }
  458. void IDependencyContainer.Register(Type typeInterface, Type typeImplementation)
  459. {
  460. Container.Register(typeInterface, typeImplementation);
  461. }
  462. /// <summary>
  463. /// Resolves this instance.
  464. /// </summary>
  465. /// <typeparam name="T"></typeparam>
  466. /// <returns>``0.</returns>
  467. public T Resolve<T>()
  468. {
  469. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  470. }
  471. /// <summary>
  472. /// Resolves this instance.
  473. /// </summary>
  474. /// <typeparam name="T"></typeparam>
  475. /// <returns>``0.</returns>
  476. public T TryResolve<T>()
  477. {
  478. var result = Container.GetRegistration(typeof(T), false);
  479. if (result == null)
  480. {
  481. return default(T);
  482. }
  483. return (T)result.GetInstance();
  484. }
  485. /// <summary>
  486. /// Loads the assembly.
  487. /// </summary>
  488. /// <param name="file">The file.</param>
  489. /// <returns>Assembly.</returns>
  490. protected Assembly LoadAssembly(string file)
  491. {
  492. try
  493. {
  494. return Assembly.Load(File.ReadAllBytes((file)));
  495. }
  496. catch (Exception ex)
  497. {
  498. FailedAssemblies.Add(file);
  499. Logger.ErrorException("Error loading assembly {0}", ex, file);
  500. return null;
  501. }
  502. }
  503. /// <summary>
  504. /// Gets the export types.
  505. /// </summary>
  506. /// <typeparam name="T"></typeparam>
  507. /// <returns>IEnumerable{Type}.</returns>
  508. public IEnumerable<Type> GetExportTypes<T>()
  509. {
  510. var currentType = typeof(T);
  511. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  512. }
  513. /// <summary>
  514. /// Gets the exports.
  515. /// </summary>
  516. /// <typeparam name="T"></typeparam>
  517. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  518. /// <returns>IEnumerable{``0}.</returns>
  519. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  520. {
  521. var parts = GetExportTypes<T>()
  522. .Select(CreateInstanceSafe)
  523. .Where(i => i != null)
  524. .Cast<T>()
  525. .ToList();
  526. if (manageLiftime)
  527. {
  528. lock (DisposableParts)
  529. {
  530. DisposableParts.AddRange(parts.OfType<IDisposable>());
  531. }
  532. }
  533. return parts;
  534. }
  535. /// <summary>
  536. /// Gets the current application version
  537. /// </summary>
  538. /// <value>The application version.</value>
  539. public Version ApplicationVersion
  540. {
  541. get
  542. {
  543. return GetType().Assembly.GetName().Version;
  544. }
  545. }
  546. /// <summary>
  547. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  548. /// </summary>
  549. /// <param name="sender">The source of the event.</param>
  550. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  551. /// <exception cref="System.NotImplementedException"></exception>
  552. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  553. {
  554. ConfigureAutorun();
  555. }
  556. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  557. /// <summary>
  558. /// Removes the plugin.
  559. /// </summary>
  560. /// <param name="plugin">The plugin.</param>
  561. public void RemovePlugin(IPlugin plugin)
  562. {
  563. var list = Plugins.ToList();
  564. list.Remove(plugin);
  565. Plugins = list;
  566. }
  567. /// <summary>
  568. /// Gets a value indicating whether this instance can self restart.
  569. /// </summary>
  570. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  571. public abstract bool CanSelfRestart { get; }
  572. /// <summary>
  573. /// Notifies that the kernel that a change has been made that requires a restart
  574. /// </summary>
  575. public void NotifyPendingRestart()
  576. {
  577. var changed = !HasPendingRestart;
  578. HasPendingRestart = true;
  579. if (changed)
  580. {
  581. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  582. }
  583. }
  584. /// <summary>
  585. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  586. /// </summary>
  587. public void Dispose()
  588. {
  589. Dispose(true);
  590. }
  591. /// <summary>
  592. /// Releases unmanaged and - optionally - managed resources.
  593. /// </summary>
  594. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  595. protected virtual void Dispose(bool dispose)
  596. {
  597. if (dispose)
  598. {
  599. var type = GetType();
  600. Logger.Info("Disposing " + type.Name);
  601. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  602. DisposableParts.Clear();
  603. foreach (var part in parts)
  604. {
  605. Logger.Info("Disposing " + part.GetType().Name);
  606. try
  607. {
  608. part.Dispose();
  609. }
  610. catch (Exception ex)
  611. {
  612. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  613. }
  614. }
  615. }
  616. }
  617. /// <summary>
  618. /// Restarts this instance.
  619. /// </summary>
  620. public abstract Task Restart();
  621. /// <summary>
  622. /// Gets or sets a value indicating whether this instance can self update.
  623. /// </summary>
  624. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  625. public abstract bool CanSelfUpdate { get; }
  626. /// <summary>
  627. /// Checks for update.
  628. /// </summary>
  629. /// <param name="cancellationToken">The cancellation token.</param>
  630. /// <param name="progress">The progress.</param>
  631. /// <returns>Task{CheckForUpdateResult}.</returns>
  632. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  633. IProgress<double> progress);
  634. /// <summary>
  635. /// Updates the application.
  636. /// </summary>
  637. /// <param name="package">The package that contains the update</param>
  638. /// <param name="cancellationToken">The cancellation token.</param>
  639. /// <param name="progress">The progress.</param>
  640. /// <returns>Task.</returns>
  641. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  642. IProgress<double> progress);
  643. /// <summary>
  644. /// Shuts down.
  645. /// </summary>
  646. public abstract Task Shutdown();
  647. /// <summary>
  648. /// Called when [application updated].
  649. /// </summary>
  650. /// <param name="package">The package.</param>
  651. protected void OnApplicationUpdated(PackageVersionInfo package)
  652. {
  653. Logger.Info("Application has been updated to version {0}", package.versionStr);
  654. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  655. {
  656. Argument = package
  657. }, Logger);
  658. NotifyPendingRestart();
  659. }
  660. }
  661. }