BaseApplicationHost.cs 26 KB

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