BaseApplicationHost.cs 31 KB

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