BaseApplicationHost.cs 30 KB

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