BaseApplicationHost.cs 31 KB

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