BaseApplicationHost.cs 29 KB

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