2
0

BaseApplicationHost.cs 29 KB

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