BaseApplicationHost.cs 31 KB

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