BaseApplicationHost.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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. Plugins = GetExports<IPlugin>();
  291. }
  292. /// <summary>
  293. /// Discovers the types.
  294. /// </summary>
  295. protected void DiscoverTypes()
  296. {
  297. FailedAssemblies.Clear();
  298. var assemblies = GetComposablePartAssemblies().ToList();
  299. foreach (var assembly in assemblies)
  300. {
  301. Logger.Info("Loading {0}", assembly.FullName);
  302. }
  303. AllTypes = assemblies.SelectMany(GetTypes).ToArray();
  304. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  305. }
  306. /// <summary>
  307. /// Registers resources that classes will depend on
  308. /// </summary>
  309. /// <returns>Task.</returns>
  310. protected virtual Task RegisterResources(IProgress<double> progress)
  311. {
  312. return Task.Run(() =>
  313. {
  314. RegisterSingleInstance(ConfigurationManager);
  315. RegisterSingleInstance<IApplicationHost>(this);
  316. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  317. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger);
  318. RegisterSingleInstance(JsonSerializer);
  319. RegisterSingleInstance(XmlSerializer);
  320. RegisterSingleInstance(LogManager);
  321. RegisterSingleInstance(Logger);
  322. RegisterSingleInstance(TaskManager);
  323. FileSystemManager = CreateFileSystemManager();
  324. RegisterSingleInstance(FileSystemManager);
  325. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger, FileSystemManager);
  326. RegisterSingleInstance(HttpClient);
  327. NetworkManager = CreateNetworkManager();
  328. RegisterSingleInstance(NetworkManager);
  329. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, NetworkManager, LogManager);
  330. RegisterSingleInstance(SecurityManager);
  331. InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, NetworkManager, ConfigurationManager);
  332. RegisterSingleInstance(InstallationManager);
  333. ZipClient = new ZipClient();
  334. RegisterSingleInstance(ZipClient);
  335. IsoManager = new IsoManager();
  336. RegisterSingleInstance(IsoManager);
  337. RegisterModules();
  338. });
  339. }
  340. private void RegisterModules()
  341. {
  342. var moduleTypes = GetExportTypes<IDependencyModule>();
  343. foreach (var type in moduleTypes)
  344. {
  345. try
  346. {
  347. var instance = Activator.CreateInstance(type) as IDependencyModule;
  348. if (instance != null)
  349. instance.BindDependencies(this);
  350. }
  351. catch (Exception ex)
  352. {
  353. Logger.ErrorException("Error setting up dependency bindings for " + type.Name, ex);
  354. }
  355. }
  356. }
  357. protected virtual IFileSystem CreateFileSystemManager()
  358. {
  359. return new CommonFileSystem(Logger, true);
  360. }
  361. /// <summary>
  362. /// Gets a list of types within an assembly
  363. /// 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
  364. /// </summary>
  365. /// <param name="assembly">The assembly.</param>
  366. /// <returns>IEnumerable{Type}.</returns>
  367. /// <exception cref="System.ArgumentNullException">assembly</exception>
  368. protected IEnumerable<Type> GetTypes(Assembly assembly)
  369. {
  370. if (assembly == null)
  371. {
  372. throw new ArgumentNullException("assembly");
  373. }
  374. try
  375. {
  376. return assembly.GetTypes();
  377. }
  378. catch (ReflectionTypeLoadException ex)
  379. {
  380. // If it fails we can still get a list of the Types it was able to resolve
  381. return ex.Types.Where(t => t != null);
  382. }
  383. }
  384. protected abstract INetworkManager CreateNetworkManager();
  385. /// <summary>
  386. /// Creates an instance of type and resolves all constructor dependancies
  387. /// </summary>
  388. /// <param name="type">The type.</param>
  389. /// <returns>System.Object.</returns>
  390. public object CreateInstance(Type type)
  391. {
  392. try
  393. {
  394. return Container.GetInstance(type);
  395. }
  396. catch (Exception ex)
  397. {
  398. Logger.Error("Error creating {0}", ex, type.Name);
  399. throw;
  400. }
  401. }
  402. /// <summary>
  403. /// Creates the instance safe.
  404. /// </summary>
  405. /// <param name="type">The type.</param>
  406. /// <returns>System.Object.</returns>
  407. protected object CreateInstanceSafe(Type type)
  408. {
  409. try
  410. {
  411. return Container.GetInstance(type);
  412. }
  413. catch (Exception ex)
  414. {
  415. Logger.Error("Error creating {0}", ex, type.Name);
  416. // Don't blow up in release mode
  417. return null;
  418. }
  419. }
  420. void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
  421. {
  422. RegisterSingleInstance(obj, manageLifetime);
  423. }
  424. /// <summary>
  425. /// Registers the specified obj.
  426. /// </summary>
  427. /// <typeparam name="T"></typeparam>
  428. /// <param name="obj">The obj.</param>
  429. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  430. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  431. where T : class
  432. {
  433. Container.RegisterSingle(obj);
  434. if (manageLifetime)
  435. {
  436. var disposable = obj as IDisposable;
  437. if (disposable != null)
  438. {
  439. DisposableParts.Add(disposable);
  440. }
  441. }
  442. }
  443. void IDependencyContainer.RegisterSingleInstance<T>(Func<T> func)
  444. {
  445. RegisterSingleInstance(func);
  446. }
  447. /// <summary>
  448. /// Registers the single instance.
  449. /// </summary>
  450. /// <typeparam name="T"></typeparam>
  451. /// <param name="func">The func.</param>
  452. protected void RegisterSingleInstance<T>(Func<T> func)
  453. where T : class
  454. {
  455. Container.RegisterSingle(func);
  456. }
  457. void IDependencyContainer.Register(Type typeInterface, Type typeImplementation)
  458. {
  459. Container.Register(typeInterface, typeImplementation);
  460. }
  461. /// <summary>
  462. /// Resolves this instance.
  463. /// </summary>
  464. /// <typeparam name="T"></typeparam>
  465. /// <returns>``0.</returns>
  466. public T Resolve<T>()
  467. {
  468. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  469. }
  470. /// <summary>
  471. /// Resolves this instance.
  472. /// </summary>
  473. /// <typeparam name="T"></typeparam>
  474. /// <returns>``0.</returns>
  475. public T TryResolve<T>()
  476. {
  477. var result = Container.GetRegistration(typeof(T), false);
  478. if (result == null)
  479. {
  480. return default(T);
  481. }
  482. return (T)result.GetInstance();
  483. }
  484. /// <summary>
  485. /// Loads the assembly.
  486. /// </summary>
  487. /// <param name="file">The file.</param>
  488. /// <returns>Assembly.</returns>
  489. protected Assembly LoadAssembly(string file)
  490. {
  491. try
  492. {
  493. return Assembly.Load(File.ReadAllBytes((file)));
  494. }
  495. catch (Exception ex)
  496. {
  497. FailedAssemblies.Add(file);
  498. Logger.ErrorException("Error loading assembly {0}", ex, file);
  499. return null;
  500. }
  501. }
  502. /// <summary>
  503. /// Gets the export types.
  504. /// </summary>
  505. /// <typeparam name="T"></typeparam>
  506. /// <returns>IEnumerable{Type}.</returns>
  507. public IEnumerable<Type> GetExportTypes<T>()
  508. {
  509. var currentType = typeof(T);
  510. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  511. }
  512. /// <summary>
  513. /// Gets the exports.
  514. /// </summary>
  515. /// <typeparam name="T"></typeparam>
  516. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  517. /// <returns>IEnumerable{``0}.</returns>
  518. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  519. {
  520. var parts = GetExportTypes<T>()
  521. .Select(CreateInstanceSafe)
  522. .Where(i => i != null)
  523. .Cast<T>()
  524. .ToList();
  525. if (manageLiftime)
  526. {
  527. lock (DisposableParts)
  528. {
  529. DisposableParts.AddRange(parts.OfType<IDisposable>());
  530. }
  531. }
  532. return parts;
  533. }
  534. /// <summary>
  535. /// Gets the current application version
  536. /// </summary>
  537. /// <value>The application version.</value>
  538. public Version ApplicationVersion
  539. {
  540. get
  541. {
  542. return GetType().Assembly.GetName().Version;
  543. }
  544. }
  545. /// <summary>
  546. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  547. /// </summary>
  548. /// <param name="sender">The source of the event.</param>
  549. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  550. /// <exception cref="System.NotImplementedException"></exception>
  551. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  552. {
  553. ConfigureAutorun();
  554. }
  555. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  556. /// <summary>
  557. /// Removes the plugin.
  558. /// </summary>
  559. /// <param name="plugin">The plugin.</param>
  560. public void RemovePlugin(IPlugin plugin)
  561. {
  562. var list = Plugins.ToList();
  563. list.Remove(plugin);
  564. Plugins = list;
  565. }
  566. /// <summary>
  567. /// Gets a value indicating whether this instance can self restart.
  568. /// </summary>
  569. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  570. public abstract bool CanSelfRestart { get; }
  571. /// <summary>
  572. /// Notifies that the kernel that a change has been made that requires a restart
  573. /// </summary>
  574. public void NotifyPendingRestart()
  575. {
  576. HasPendingRestart = true;
  577. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  578. }
  579. /// <summary>
  580. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  581. /// </summary>
  582. public void Dispose()
  583. {
  584. Dispose(true);
  585. }
  586. /// <summary>
  587. /// Releases unmanaged and - optionally - managed resources.
  588. /// </summary>
  589. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  590. protected virtual void Dispose(bool dispose)
  591. {
  592. if (dispose)
  593. {
  594. var type = GetType();
  595. Logger.Info("Disposing " + type.Name);
  596. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  597. DisposableParts.Clear();
  598. foreach (var part in parts)
  599. {
  600. Logger.Info("Disposing " + part.GetType().Name);
  601. try
  602. {
  603. part.Dispose();
  604. }
  605. catch (Exception ex)
  606. {
  607. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  608. }
  609. }
  610. }
  611. }
  612. /// <summary>
  613. /// Restarts this instance.
  614. /// </summary>
  615. public abstract Task Restart();
  616. /// <summary>
  617. /// Gets or sets a value indicating whether this instance can self update.
  618. /// </summary>
  619. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  620. public abstract bool CanSelfUpdate { get; }
  621. /// <summary>
  622. /// Checks for update.
  623. /// </summary>
  624. /// <param name="cancellationToken">The cancellation token.</param>
  625. /// <param name="progress">The progress.</param>
  626. /// <returns>Task{CheckForUpdateResult}.</returns>
  627. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  628. IProgress<double> progress);
  629. /// <summary>
  630. /// Updates the application.
  631. /// </summary>
  632. /// <param name="package">The package that contains the update</param>
  633. /// <param name="cancellationToken">The cancellation token.</param>
  634. /// <param name="progress">The progress.</param>
  635. /// <returns>Task.</returns>
  636. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  637. IProgress<double> progress);
  638. /// <summary>
  639. /// Shuts down.
  640. /// </summary>
  641. public abstract Task Shutdown();
  642. /// <summary>
  643. /// Called when [application updated].
  644. /// </summary>
  645. /// <param name="package">The package.</param>
  646. protected void OnApplicationUpdated(PackageVersionInfo package)
  647. {
  648. Logger.Info("Application has been updated to version {0}", package.versionStr);
  649. EventHelper.QueueEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  650. {
  651. Argument = package
  652. }, Logger);
  653. NotifyPendingRestart();
  654. }
  655. }
  656. }