BaseApplicationHost.cs 31 KB

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