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