BaseApplicationHost.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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. public 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. RegisterModules();
  350. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  351. Plugins = GetExports<IPlugin>();
  352. }
  353. /// <summary>
  354. /// Discovers the types.
  355. /// </summary>
  356. protected void DiscoverTypes()
  357. {
  358. FailedAssemblies.Clear();
  359. var assemblies = GetComposablePartAssemblies().ToList();
  360. foreach (var assembly in assemblies)
  361. {
  362. Logger.Info("Loading {0}", assembly.FullName);
  363. }
  364. AllConcreteTypes = assemblies
  365. .SelectMany(GetTypes)
  366. .Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType)
  367. .ToArray();
  368. }
  369. /// <summary>
  370. /// Registers resources that classes will depend on
  371. /// </summary>
  372. /// <returns>Task.</returns>
  373. protected virtual Task RegisterResources(IProgress<double> progress)
  374. {
  375. RegisterSingleInstance(ConfigurationManager);
  376. RegisterSingleInstance<IApplicationHost>(this);
  377. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  378. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager);
  379. RegisterSingleInstance(JsonSerializer);
  380. RegisterSingleInstance(XmlSerializer);
  381. RegisterSingleInstance(LogManager);
  382. RegisterSingleInstance(Logger);
  383. RegisterSingleInstance(TaskManager);
  384. RegisterSingleInstance(FileSystemManager);
  385. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager);
  386. RegisterSingleInstance(HttpClient);
  387. NetworkManager = CreateNetworkManager(LogManager.GetLogger("NetworkManager"));
  388. RegisterSingleInstance(NetworkManager);
  389. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager);
  390. RegisterSingleInstance(SecurityManager);
  391. InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager);
  392. RegisterSingleInstance(InstallationManager);
  393. ZipClient = new ZipClient(FileSystemManager);
  394. RegisterSingleInstance(ZipClient);
  395. IsoManager = new IsoManager();
  396. RegisterSingleInstance(IsoManager);
  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 (ex.LoaderExceptions != null)
  436. {
  437. foreach (var loaderException in ex.LoaderExceptions)
  438. {
  439. Logger.Error("LoaderException: " + loaderException.Message);
  440. }
  441. }
  442. // If it fails we can still get a list of the Types it was able to resolve
  443. return ex.Types.Where(t => t != null);
  444. }
  445. }
  446. protected abstract INetworkManager CreateNetworkManager(ILogger logger);
  447. /// <summary>
  448. /// Creates an instance of type and resolves all constructor dependancies
  449. /// </summary>
  450. /// <param name="type">The type.</param>
  451. /// <returns>System.Object.</returns>
  452. public object CreateInstance(Type type)
  453. {
  454. try
  455. {
  456. return Container.GetInstance(type);
  457. }
  458. catch (Exception ex)
  459. {
  460. Logger.Error("Error creating {0}", ex, type.Name);
  461. throw;
  462. }
  463. }
  464. /// <summary>
  465. /// Creates the instance safe.
  466. /// </summary>
  467. /// <param name="type">The type.</param>
  468. /// <returns>System.Object.</returns>
  469. protected object CreateInstanceSafe(Type type)
  470. {
  471. try
  472. {
  473. return Container.GetInstance(type);
  474. }
  475. catch (Exception ex)
  476. {
  477. Logger.Error("Error creating {0}", ex, type.Name);
  478. // Don't blow up in release mode
  479. return null;
  480. }
  481. }
  482. void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
  483. {
  484. RegisterSingleInstance(obj, manageLifetime);
  485. }
  486. /// <summary>
  487. /// Registers the specified obj.
  488. /// </summary>
  489. /// <typeparam name="T"></typeparam>
  490. /// <param name="obj">The obj.</param>
  491. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  492. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  493. where T : class
  494. {
  495. Container.RegisterSingleton(obj);
  496. if (manageLifetime)
  497. {
  498. var disposable = obj as IDisposable;
  499. if (disposable != null)
  500. {
  501. DisposableParts.Add(disposable);
  502. }
  503. }
  504. }
  505. void IDependencyContainer.RegisterSingleInstance<T>(Func<T> func)
  506. {
  507. RegisterSingleInstance(func);
  508. }
  509. /// <summary>
  510. /// Registers the single instance.
  511. /// </summary>
  512. /// <typeparam name="T"></typeparam>
  513. /// <param name="func">The func.</param>
  514. protected void RegisterSingleInstance<T>(Func<T> func)
  515. where T : class
  516. {
  517. Container.RegisterSingleton(func);
  518. }
  519. void IDependencyContainer.Register(Type typeInterface, Type typeImplementation)
  520. {
  521. Container.Register(typeInterface, typeImplementation);
  522. }
  523. /// <summary>
  524. /// Resolves this instance.
  525. /// </summary>
  526. /// <typeparam name="T"></typeparam>
  527. /// <returns>``0.</returns>
  528. public T Resolve<T>()
  529. {
  530. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  531. }
  532. /// <summary>
  533. /// Resolves this instance.
  534. /// </summary>
  535. /// <typeparam name="T"></typeparam>
  536. /// <returns>``0.</returns>
  537. public T TryResolve<T>()
  538. {
  539. var result = Container.GetRegistration(typeof(T), false);
  540. if (result == null)
  541. {
  542. return default(T);
  543. }
  544. return (T)result.GetInstance();
  545. }
  546. /// <summary>
  547. /// Loads the assembly.
  548. /// </summary>
  549. /// <param name="file">The file.</param>
  550. /// <returns>Assembly.</returns>
  551. protected Assembly LoadAssembly(string file)
  552. {
  553. try
  554. {
  555. return Assembly.Load(File.ReadAllBytes((file)));
  556. }
  557. catch (Exception ex)
  558. {
  559. FailedAssemblies.Add(file);
  560. Logger.ErrorException("Error loading assembly {0}", ex, file);
  561. return null;
  562. }
  563. }
  564. /// <summary>
  565. /// Gets the export types.
  566. /// </summary>
  567. /// <typeparam name="T"></typeparam>
  568. /// <returns>IEnumerable{Type}.</returns>
  569. public IEnumerable<Type> GetExportTypes<T>()
  570. {
  571. var currentType = typeof(T);
  572. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  573. }
  574. /// <summary>
  575. /// Gets the exports.
  576. /// </summary>
  577. /// <typeparam name="T"></typeparam>
  578. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  579. /// <returns>IEnumerable{``0}.</returns>
  580. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  581. {
  582. var parts = GetExportTypes<T>()
  583. .Select(CreateInstanceSafe)
  584. .Where(i => i != null)
  585. .Cast<T>()
  586. .ToList();
  587. if (manageLiftime)
  588. {
  589. lock (DisposableParts)
  590. {
  591. DisposableParts.AddRange(parts.OfType<IDisposable>());
  592. }
  593. }
  594. return parts;
  595. }
  596. /// <summary>
  597. /// Gets the application version.
  598. /// </summary>
  599. /// <value>The application version.</value>
  600. public abstract Version ApplicationVersion { get; }
  601. /// <summary>
  602. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  603. /// </summary>
  604. /// <param name="sender">The source of the event.</param>
  605. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  606. /// <exception cref="System.NotImplementedException"></exception>
  607. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  608. {
  609. ConfigureAutorun();
  610. }
  611. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  612. /// <summary>
  613. /// Removes the plugin.
  614. /// </summary>
  615. /// <param name="plugin">The plugin.</param>
  616. public void RemovePlugin(IPlugin plugin)
  617. {
  618. var list = Plugins.ToList();
  619. list.Remove(plugin);
  620. Plugins = list;
  621. }
  622. /// <summary>
  623. /// Gets a value indicating whether this instance can self restart.
  624. /// </summary>
  625. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  626. public abstract bool CanSelfRestart { get; }
  627. /// <summary>
  628. /// Notifies that the kernel that a change has been made that requires a restart
  629. /// </summary>
  630. public void NotifyPendingRestart()
  631. {
  632. var changed = !HasPendingRestart;
  633. HasPendingRestart = true;
  634. if (changed)
  635. {
  636. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  637. }
  638. }
  639. /// <summary>
  640. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  641. /// </summary>
  642. public void Dispose()
  643. {
  644. Dispose(true);
  645. }
  646. /// <summary>
  647. /// Releases unmanaged and - optionally - managed resources.
  648. /// </summary>
  649. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  650. protected virtual void Dispose(bool dispose)
  651. {
  652. if (dispose)
  653. {
  654. var type = GetType();
  655. Logger.Info("Disposing " + type.Name);
  656. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  657. DisposableParts.Clear();
  658. foreach (var part in parts)
  659. {
  660. Logger.Info("Disposing " + part.GetType().Name);
  661. try
  662. {
  663. part.Dispose();
  664. }
  665. catch (Exception ex)
  666. {
  667. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  668. }
  669. }
  670. }
  671. }
  672. /// <summary>
  673. /// Restarts this instance.
  674. /// </summary>
  675. public abstract Task Restart();
  676. /// <summary>
  677. /// Gets or sets a value indicating whether this instance can self update.
  678. /// </summary>
  679. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  680. public abstract bool CanSelfUpdate { get; }
  681. /// <summary>
  682. /// Checks for update.
  683. /// </summary>
  684. /// <param name="cancellationToken">The cancellation token.</param>
  685. /// <param name="progress">The progress.</param>
  686. /// <returns>Task{CheckForUpdateResult}.</returns>
  687. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  688. IProgress<double> progress);
  689. /// <summary>
  690. /// Updates the application.
  691. /// </summary>
  692. /// <param name="package">The package that contains the update</param>
  693. /// <param name="cancellationToken">The cancellation token.</param>
  694. /// <param name="progress">The progress.</param>
  695. /// <returns>Task.</returns>
  696. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  697. IProgress<double> progress);
  698. /// <summary>
  699. /// Shuts down.
  700. /// </summary>
  701. public abstract Task Shutdown();
  702. /// <summary>
  703. /// Called when [application updated].
  704. /// </summary>
  705. /// <param name="package">The package.</param>
  706. protected void OnApplicationUpdated(PackageVersionInfo package)
  707. {
  708. Logger.Info("Application has been updated to version {0}", package.versionStr);
  709. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  710. {
  711. Argument = package
  712. }, Logger);
  713. NotifyPendingRestart();
  714. }
  715. }
  716. }