BaseApplicationHost.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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. OnLoggerLoaded(true);
  186. LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
  187. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  188. progress.Report(2);
  189. LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
  190. ? LogSeverity.Debug
  191. : LogSeverity.Info;
  192. progress.Report(3);
  193. DiscoverTypes();
  194. progress.Report(14);
  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 void OnLoggerLoaded(bool isFirstLoad)
  206. {
  207. Logger.Info("Application version: {0}", ApplicationVersion);
  208. if (!isFirstLoad)
  209. {
  210. LogEnvironmentInfo(Logger, ApplicationPaths);
  211. }
  212. // Put the app config in the log for troubleshooting purposes
  213. Logger.LogMultiline("Application configuration:", LogSeverity.Info, new StringBuilder(JsonSerializer.SerializeToString(ConfigurationManager.CommonConfiguration)));
  214. if (Plugins != null)
  215. {
  216. var pluginBuilder = new StringBuilder();
  217. foreach (var plugin in Plugins)
  218. {
  219. pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
  220. }
  221. Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder);
  222. }
  223. }
  224. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  225. {
  226. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  227. logger.Info("Server: {0}", Environment.MachineName);
  228. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  229. logger.Info("Processor count: {0}", Environment.ProcessorCount);
  230. logger.Info("64-Bit OS: {0}", Environment.Is64BitOperatingSystem);
  231. logger.Info("64-Bit Process: {0}", Environment.Is64BitProcess);
  232. logger.Info("Program data path: {0}", appPaths.ProgramDataPath);
  233. logger.Info("Application Path: {0}", appPaths.ApplicationPath);
  234. logger.Info("*** When reporting issues please include the entire log file. ***".ToUpper());
  235. }
  236. protected virtual IJsonSerializer CreateJsonSerializer()
  237. {
  238. return new JsonSerializer();
  239. }
  240. private void SetHttpLimit()
  241. {
  242. try
  243. {
  244. // Increase the max http request limit
  245. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  246. }
  247. catch (Exception ex)
  248. {
  249. Logger.ErrorException("Error setting http limit", ex);
  250. }
  251. }
  252. /// <summary>
  253. /// Installs the iso mounters.
  254. /// </summary>
  255. /// <param name="cancellationToken">The cancellation token.</param>
  256. /// <returns>Task.</returns>
  257. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  258. {
  259. var list = new List<IIsoMounter>();
  260. foreach (var isoMounter in GetExports<IIsoMounter>())
  261. {
  262. try
  263. {
  264. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  265. {
  266. Logger.Info("Installing {0}", isoMounter.Name);
  267. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  268. }
  269. list.Add(isoMounter);
  270. }
  271. catch (Exception ex)
  272. {
  273. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  274. }
  275. }
  276. IsoManager.AddParts(list);
  277. }
  278. /// <summary>
  279. /// Runs the startup tasks.
  280. /// </summary>
  281. /// <returns>Task.</returns>
  282. public virtual Task RunStartupTasks()
  283. {
  284. return Task.Run(() =>
  285. {
  286. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  287. Task.Run(() => ConfigureAutorun());
  288. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  289. });
  290. }
  291. /// <summary>
  292. /// Configures the autorun.
  293. /// </summary>
  294. private void ConfigureAutorun()
  295. {
  296. try
  297. {
  298. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  299. }
  300. catch (Exception ex)
  301. {
  302. Logger.ErrorException("Error configuring autorun", ex);
  303. }
  304. }
  305. /// <summary>
  306. /// Gets the composable part assemblies.
  307. /// </summary>
  308. /// <returns>IEnumerable{Assembly}.</returns>
  309. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  310. /// <summary>
  311. /// Gets the configuration manager.
  312. /// </summary>
  313. /// <returns>IConfigurationManager.</returns>
  314. protected abstract IConfigurationManager GetConfigurationManager();
  315. /// <summary>
  316. /// Finds the parts.
  317. /// </summary>
  318. protected virtual void FindParts()
  319. {
  320. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  321. Plugins = GetExports<IPlugin>();
  322. }
  323. /// <summary>
  324. /// Discovers the types.
  325. /// </summary>
  326. protected void DiscoverTypes()
  327. {
  328. FailedAssemblies.Clear();
  329. var assemblies = GetComposablePartAssemblies().ToList();
  330. foreach (var assembly in assemblies)
  331. {
  332. Logger.Info("Loading {0}", assembly.FullName);
  333. }
  334. AllTypes = assemblies.SelectMany(GetTypes).ToArray();
  335. AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
  336. }
  337. /// <summary>
  338. /// Registers resources that classes will depend on
  339. /// </summary>
  340. /// <returns>Task.</returns>
  341. protected virtual Task RegisterResources(IProgress<double> progress)
  342. {
  343. return Task.Run(() =>
  344. {
  345. RegisterSingleInstance(ConfigurationManager);
  346. RegisterSingleInstance<IApplicationHost>(this);
  347. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  348. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger);
  349. RegisterSingleInstance(JsonSerializer);
  350. RegisterSingleInstance(XmlSerializer);
  351. RegisterSingleInstance(LogManager);
  352. RegisterSingleInstance(Logger);
  353. RegisterSingleInstance(TaskManager);
  354. FileSystemManager = CreateFileSystemManager();
  355. RegisterSingleInstance(FileSystemManager);
  356. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger, FileSystemManager, ConfigurationManager);
  357. RegisterSingleInstance(HttpClient);
  358. NetworkManager = CreateNetworkManager(LogManager.GetLogger("NetworkManager"));
  359. RegisterSingleInstance(NetworkManager);
  360. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, NetworkManager, LogManager);
  361. RegisterSingleInstance(SecurityManager);
  362. InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, NetworkManager, ConfigurationManager);
  363. RegisterSingleInstance(InstallationManager);
  364. ZipClient = new ZipClient();
  365. RegisterSingleInstance(ZipClient);
  366. IsoManager = new IsoManager();
  367. RegisterSingleInstance(IsoManager);
  368. RegisterModules();
  369. });
  370. }
  371. private void RegisterModules()
  372. {
  373. var moduleTypes = GetExportTypes<IDependencyModule>();
  374. foreach (var type in moduleTypes)
  375. {
  376. try
  377. {
  378. var instance = Activator.CreateInstance(type) as IDependencyModule;
  379. if (instance != null)
  380. instance.BindDependencies(this);
  381. }
  382. catch (Exception ex)
  383. {
  384. Logger.ErrorException("Error setting up dependency bindings for " + type.Name, ex);
  385. }
  386. }
  387. }
  388. protected virtual IFileSystem CreateFileSystemManager()
  389. {
  390. return new CommonFileSystem(Logger, true);
  391. }
  392. /// <summary>
  393. /// Gets a list of types within an assembly
  394. /// 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
  395. /// </summary>
  396. /// <param name="assembly">The assembly.</param>
  397. /// <returns>IEnumerable{Type}.</returns>
  398. /// <exception cref="System.ArgumentNullException">assembly</exception>
  399. protected IEnumerable<Type> GetTypes(Assembly assembly)
  400. {
  401. if (assembly == null)
  402. {
  403. throw new ArgumentNullException("assembly");
  404. }
  405. try
  406. {
  407. return assembly.GetTypes();
  408. }
  409. catch (ReflectionTypeLoadException ex)
  410. {
  411. // If it fails we can still get a list of the Types it was able to resolve
  412. return ex.Types.Where(t => t != null);
  413. }
  414. }
  415. protected abstract INetworkManager CreateNetworkManager(ILogger logger);
  416. /// <summary>
  417. /// Creates an instance of type and resolves all constructor dependancies
  418. /// </summary>
  419. /// <param name="type">The type.</param>
  420. /// <returns>System.Object.</returns>
  421. public object CreateInstance(Type type)
  422. {
  423. try
  424. {
  425. return Container.GetInstance(type);
  426. }
  427. catch (Exception ex)
  428. {
  429. Logger.Error("Error creating {0}", ex, type.Name);
  430. throw;
  431. }
  432. }
  433. /// <summary>
  434. /// Creates the instance safe.
  435. /// </summary>
  436. /// <param name="type">The type.</param>
  437. /// <returns>System.Object.</returns>
  438. protected object CreateInstanceSafe(Type type)
  439. {
  440. try
  441. {
  442. return Container.GetInstance(type);
  443. }
  444. catch (Exception ex)
  445. {
  446. Logger.Error("Error creating {0}", ex, type.Name);
  447. // Don't blow up in release mode
  448. return null;
  449. }
  450. }
  451. void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
  452. {
  453. RegisterSingleInstance(obj, manageLifetime);
  454. }
  455. /// <summary>
  456. /// Registers the specified obj.
  457. /// </summary>
  458. /// <typeparam name="T"></typeparam>
  459. /// <param name="obj">The obj.</param>
  460. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  461. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  462. where T : class
  463. {
  464. Container.RegisterSingle(obj);
  465. if (manageLifetime)
  466. {
  467. var disposable = obj as IDisposable;
  468. if (disposable != null)
  469. {
  470. DisposableParts.Add(disposable);
  471. }
  472. }
  473. }
  474. void IDependencyContainer.RegisterSingleInstance<T>(Func<T> func)
  475. {
  476. RegisterSingleInstance(func);
  477. }
  478. /// <summary>
  479. /// Registers the single instance.
  480. /// </summary>
  481. /// <typeparam name="T"></typeparam>
  482. /// <param name="func">The func.</param>
  483. protected void RegisterSingleInstance<T>(Func<T> func)
  484. where T : class
  485. {
  486. Container.RegisterSingle(func);
  487. }
  488. void IDependencyContainer.Register(Type typeInterface, Type typeImplementation)
  489. {
  490. Container.Register(typeInterface, typeImplementation);
  491. }
  492. /// <summary>
  493. /// Resolves this instance.
  494. /// </summary>
  495. /// <typeparam name="T"></typeparam>
  496. /// <returns>``0.</returns>
  497. public T Resolve<T>()
  498. {
  499. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  500. }
  501. /// <summary>
  502. /// Resolves this instance.
  503. /// </summary>
  504. /// <typeparam name="T"></typeparam>
  505. /// <returns>``0.</returns>
  506. public T TryResolve<T>()
  507. {
  508. var result = Container.GetRegistration(typeof(T), false);
  509. if (result == null)
  510. {
  511. return default(T);
  512. }
  513. return (T)result.GetInstance();
  514. }
  515. /// <summary>
  516. /// Loads the assembly.
  517. /// </summary>
  518. /// <param name="file">The file.</param>
  519. /// <returns>Assembly.</returns>
  520. protected Assembly LoadAssembly(string file)
  521. {
  522. try
  523. {
  524. return Assembly.Load(File.ReadAllBytes((file)));
  525. }
  526. catch (Exception ex)
  527. {
  528. FailedAssemblies.Add(file);
  529. Logger.ErrorException("Error loading assembly {0}", ex, file);
  530. return null;
  531. }
  532. }
  533. /// <summary>
  534. /// Gets the export types.
  535. /// </summary>
  536. /// <typeparam name="T"></typeparam>
  537. /// <returns>IEnumerable{Type}.</returns>
  538. public IEnumerable<Type> GetExportTypes<T>()
  539. {
  540. var currentType = typeof(T);
  541. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  542. }
  543. /// <summary>
  544. /// Gets the exports.
  545. /// </summary>
  546. /// <typeparam name="T"></typeparam>
  547. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  548. /// <returns>IEnumerable{``0}.</returns>
  549. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  550. {
  551. var parts = GetExportTypes<T>()
  552. .Select(CreateInstanceSafe)
  553. .Where(i => i != null)
  554. .Cast<T>()
  555. .ToList();
  556. if (manageLiftime)
  557. {
  558. lock (DisposableParts)
  559. {
  560. DisposableParts.AddRange(parts.OfType<IDisposable>());
  561. }
  562. }
  563. return parts;
  564. }
  565. private Version _version;
  566. /// <summary>
  567. /// Gets the current application version
  568. /// </summary>
  569. /// <value>The application version.</value>
  570. public Version ApplicationVersion
  571. {
  572. get
  573. {
  574. return _version ?? (_version = GetType().Assembly.GetName().Version);
  575. }
  576. }
  577. /// <summary>
  578. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  579. /// </summary>
  580. /// <param name="sender">The source of the event.</param>
  581. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  582. /// <exception cref="System.NotImplementedException"></exception>
  583. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  584. {
  585. ConfigureAutorun();
  586. }
  587. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  588. /// <summary>
  589. /// Removes the plugin.
  590. /// </summary>
  591. /// <param name="plugin">The plugin.</param>
  592. public void RemovePlugin(IPlugin plugin)
  593. {
  594. var list = Plugins.ToList();
  595. list.Remove(plugin);
  596. Plugins = list;
  597. }
  598. /// <summary>
  599. /// Gets a value indicating whether this instance can self restart.
  600. /// </summary>
  601. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  602. public abstract bool CanSelfRestart { get; }
  603. /// <summary>
  604. /// Notifies that the kernel that a change has been made that requires a restart
  605. /// </summary>
  606. public void NotifyPendingRestart()
  607. {
  608. var changed = !HasPendingRestart;
  609. HasPendingRestart = true;
  610. if (changed)
  611. {
  612. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  613. }
  614. }
  615. /// <summary>
  616. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  617. /// </summary>
  618. public void Dispose()
  619. {
  620. Dispose(true);
  621. }
  622. /// <summary>
  623. /// Releases unmanaged and - optionally - managed resources.
  624. /// </summary>
  625. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  626. protected virtual void Dispose(bool dispose)
  627. {
  628. if (dispose)
  629. {
  630. var type = GetType();
  631. Logger.Info("Disposing " + type.Name);
  632. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  633. DisposableParts.Clear();
  634. foreach (var part in parts)
  635. {
  636. Logger.Info("Disposing " + part.GetType().Name);
  637. try
  638. {
  639. part.Dispose();
  640. }
  641. catch (Exception ex)
  642. {
  643. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  644. }
  645. }
  646. }
  647. }
  648. /// <summary>
  649. /// Restarts this instance.
  650. /// </summary>
  651. public abstract Task Restart();
  652. /// <summary>
  653. /// Gets or sets a value indicating whether this instance can self update.
  654. /// </summary>
  655. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  656. public abstract bool CanSelfUpdate { get; }
  657. /// <summary>
  658. /// Checks for update.
  659. /// </summary>
  660. /// <param name="cancellationToken">The cancellation token.</param>
  661. /// <param name="progress">The progress.</param>
  662. /// <returns>Task{CheckForUpdateResult}.</returns>
  663. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  664. IProgress<double> progress);
  665. /// <summary>
  666. /// Updates the application.
  667. /// </summary>
  668. /// <param name="package">The package that contains the update</param>
  669. /// <param name="cancellationToken">The cancellation token.</param>
  670. /// <param name="progress">The progress.</param>
  671. /// <returns>Task.</returns>
  672. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  673. IProgress<double> progress);
  674. /// <summary>
  675. /// Shuts down.
  676. /// </summary>
  677. public abstract Task Shutdown();
  678. /// <summary>
  679. /// Called when [application updated].
  680. /// </summary>
  681. /// <param name="package">The package.</param>
  682. protected void OnApplicationUpdated(PackageVersionInfo package)
  683. {
  684. Logger.Info("Application has been updated to version {0}", package.versionStr);
  685. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  686. {
  687. Argument = package
  688. }, Logger);
  689. NotifyPendingRestart();
  690. }
  691. }
  692. }