BaseApplicationHost.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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 string OperatingSystemDisplayName
  158. {
  159. get { return EnvironmentInfo.OperatingSystemName; }
  160. }
  161. /// <summary>
  162. /// The container
  163. /// </summary>
  164. protected readonly SimpleInjector.Container Container = new SimpleInjector.Container();
  165. protected ISystemEvents SystemEvents { get; private set; }
  166. protected IMemoryStreamFactory MemoryStreamFactory { get; private set; }
  167. /// <summary>
  168. /// Initializes a new instance of the <see cref="BaseApplicationHost{TApplicationPathsType}"/> class.
  169. /// </summary>
  170. protected BaseApplicationHost(TApplicationPathsType applicationPaths,
  171. ILogManager logManager,
  172. IFileSystem fileSystem,
  173. IEnvironmentInfo environmentInfo,
  174. ISystemEvents systemEvents,
  175. IMemoryStreamFactory memoryStreamFactory,
  176. INetworkManager networkManager)
  177. {
  178. NetworkManager = networkManager;
  179. EnvironmentInfo = environmentInfo;
  180. SystemEvents = systemEvents;
  181. MemoryStreamFactory = memoryStreamFactory;
  182. // hack alert, until common can target .net core
  183. BaseExtensions.CryptographyProvider = CryptographyProvider;
  184. XmlSerializer = new MyXmlSerializer(fileSystem, logManager.GetLogger("XmlSerializer"));
  185. FailedAssemblies = new List<string>();
  186. ApplicationPaths = applicationPaths;
  187. LogManager = logManager;
  188. FileSystemManager = fileSystem;
  189. ConfigurationManager = GetConfigurationManager();
  190. // Initialize this early in case the -v command line option is used
  191. Logger = LogManager.GetLogger("App");
  192. }
  193. /// <summary>
  194. /// Inits this instance.
  195. /// </summary>
  196. /// <returns>Task.</returns>
  197. public virtual async Task Init(IProgress<double> progress)
  198. {
  199. progress.Report(1);
  200. JsonSerializer = CreateJsonSerializer();
  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 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 directory: {0}", appPaths.ProgramSystemPath));
  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(MemoryStreamFactory);
  428. RegisterSingleInstance(SystemEvents);
  429. RegisterSingleInstance(LogManager);
  430. RegisterSingleInstance(Logger);
  431. RegisterSingleInstance(TaskManager);
  432. RegisterSingleInstance(EnvironmentInfo);
  433. RegisterSingleInstance(FileSystemManager);
  434. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, MemoryStreamFactory, GetDefaultUserAgent);
  435. RegisterSingleInstance(HttpClient);
  436. RegisterSingleInstance(NetworkManager);
  437. IsoManager = new IsoManager();
  438. RegisterSingleInstance(IsoManager);
  439. ProcessFactory = new ProcessFactory();
  440. RegisterSingleInstance(ProcessFactory);
  441. TimerFactory = new TimerFactory();
  442. RegisterSingleInstance(TimerFactory);
  443. SocketFactory = new SocketFactory(LogManager.GetLogger("SocketFactory"));
  444. RegisterSingleInstance(SocketFactory);
  445. RegisterSingleInstance(CryptographyProvider);
  446. return Task.FromResult(true);
  447. }
  448. private string GetDefaultUserAgent()
  449. {
  450. var name = FormatAttribute(Name);
  451. return name + "/" + ApplicationVersion.ToString();
  452. }
  453. private string FormatAttribute(string str)
  454. {
  455. var arr = str.ToCharArray();
  456. arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
  457. || char.IsWhiteSpace(c))));
  458. var result = new string(arr);
  459. if (string.IsNullOrWhiteSpace(result))
  460. {
  461. result = "Emby";
  462. }
  463. return result;
  464. }
  465. /// <summary>
  466. /// Gets a list of types within an assembly
  467. /// 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
  468. /// </summary>
  469. /// <param name="assembly">The assembly.</param>
  470. /// <returns>IEnumerable{Type}.</returns>
  471. /// <exception cref="System.ArgumentNullException">assembly</exception>
  472. protected IEnumerable<Type> GetTypes(Assembly assembly)
  473. {
  474. if (assembly == null)
  475. {
  476. throw new ArgumentNullException("assembly");
  477. }
  478. try
  479. {
  480. return assembly.GetTypes();
  481. }
  482. catch (ReflectionTypeLoadException ex)
  483. {
  484. if (ex.LoaderExceptions != null)
  485. {
  486. foreach (var loaderException in ex.LoaderExceptions)
  487. {
  488. Logger.Error("LoaderException: " + loaderException.Message);
  489. }
  490. }
  491. // If it fails we can still get a list of the Types it was able to resolve
  492. return ex.Types.Where(t => t != null);
  493. }
  494. }
  495. /// <summary>
  496. /// Creates an instance of type and resolves all constructor dependancies
  497. /// </summary>
  498. /// <param name="type">The type.</param>
  499. /// <returns>System.Object.</returns>
  500. public object CreateInstance(Type type)
  501. {
  502. try
  503. {
  504. return Container.GetInstance(type);
  505. }
  506. catch (Exception ex)
  507. {
  508. Logger.ErrorException("Error creating {0}", ex, type.FullName);
  509. throw;
  510. }
  511. }
  512. /// <summary>
  513. /// Creates the instance safe.
  514. /// </summary>
  515. /// <param name="type">The type.</param>
  516. /// <returns>System.Object.</returns>
  517. protected object CreateInstanceSafe(Type type)
  518. {
  519. try
  520. {
  521. return Container.GetInstance(type);
  522. }
  523. catch (Exception ex)
  524. {
  525. Logger.ErrorException("Error creating {0}", ex, type.FullName);
  526. // Don't blow up in release mode
  527. return null;
  528. }
  529. }
  530. /// <summary>
  531. /// Registers the specified obj.
  532. /// </summary>
  533. /// <typeparam name="T"></typeparam>
  534. /// <param name="obj">The obj.</param>
  535. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  536. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  537. where T : class
  538. {
  539. Container.RegisterSingleton(obj);
  540. if (manageLifetime)
  541. {
  542. var disposable = obj as IDisposable;
  543. if (disposable != null)
  544. {
  545. DisposableParts.Add(disposable);
  546. }
  547. }
  548. }
  549. /// <summary>
  550. /// Registers the single instance.
  551. /// </summary>
  552. /// <typeparam name="T"></typeparam>
  553. /// <param name="func">The func.</param>
  554. protected void RegisterSingleInstance<T>(Func<T> func)
  555. where T : class
  556. {
  557. Container.RegisterSingleton(func);
  558. }
  559. /// <summary>
  560. /// Resolves this instance.
  561. /// </summary>
  562. /// <typeparam name="T"></typeparam>
  563. /// <returns>``0.</returns>
  564. public T Resolve<T>()
  565. {
  566. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  567. }
  568. /// <summary>
  569. /// Resolves this instance.
  570. /// </summary>
  571. /// <typeparam name="T"></typeparam>
  572. /// <returns>``0.</returns>
  573. public T TryResolve<T>()
  574. {
  575. var result = Container.GetRegistration(typeof(T), false);
  576. if (result == null)
  577. {
  578. return default(T);
  579. }
  580. return (T)result.GetInstance();
  581. }
  582. /// <summary>
  583. /// Loads the assembly.
  584. /// </summary>
  585. /// <param name="file">The file.</param>
  586. /// <returns>Assembly.</returns>
  587. protected Assembly LoadAssembly(string file)
  588. {
  589. try
  590. {
  591. #if NET46
  592. return Assembly.Load(File.ReadAllBytes(file));
  593. #elif NETSTANDARD1_6
  594. return AssemblyLoadContext.Default.LoadFromStream(new MemoryStream(File.ReadAllBytes(file)));
  595. #endif
  596. return null;
  597. }
  598. catch (Exception ex)
  599. {
  600. FailedAssemblies.Add(file);
  601. Logger.ErrorException("Error loading assembly {0}", ex, file);
  602. return null;
  603. }
  604. }
  605. /// <summary>
  606. /// Gets the export types.
  607. /// </summary>
  608. /// <typeparam name="T"></typeparam>
  609. /// <returns>IEnumerable{Type}.</returns>
  610. public IEnumerable<Type> GetExportTypes<T>()
  611. {
  612. var currentType = typeof(T);
  613. #if NET46
  614. return AllConcreteTypes.Where(currentType.IsAssignableFrom);
  615. #elif NETSTANDARD1_6
  616. var currentTypeInfo = currentType.GetTypeInfo();
  617. return AllConcreteTypes.Where(currentTypeInfo.IsAssignableFrom);
  618. #endif
  619. return new List<Type>();
  620. }
  621. /// <summary>
  622. /// Gets the exports.
  623. /// </summary>
  624. /// <typeparam name="T"></typeparam>
  625. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  626. /// <returns>IEnumerable{``0}.</returns>
  627. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  628. {
  629. var parts = GetExportTypes<T>()
  630. .Select(CreateInstanceSafe)
  631. .Where(i => i != null)
  632. .Cast<T>()
  633. .ToList();
  634. if (manageLiftime)
  635. {
  636. lock (DisposableParts)
  637. {
  638. DisposableParts.AddRange(parts.OfType<IDisposable>());
  639. }
  640. }
  641. return parts;
  642. }
  643. /// <summary>
  644. /// Gets the application version.
  645. /// </summary>
  646. /// <value>The application version.</value>
  647. public abstract Version ApplicationVersion { get; }
  648. /// <summary>
  649. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  650. /// </summary>
  651. /// <param name="sender">The source of the event.</param>
  652. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  653. /// <exception cref="System.NotImplementedException"></exception>
  654. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  655. {
  656. ConfigureAutorun();
  657. }
  658. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  659. /// <summary>
  660. /// Removes the plugin.
  661. /// </summary>
  662. /// <param name="plugin">The plugin.</param>
  663. public void RemovePlugin(IPlugin plugin)
  664. {
  665. var list = Plugins.ToList();
  666. list.Remove(plugin);
  667. Plugins = list.ToArray();
  668. }
  669. /// <summary>
  670. /// Gets a value indicating whether this instance can self restart.
  671. /// </summary>
  672. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  673. public abstract bool CanSelfRestart { get; }
  674. /// <summary>
  675. /// Notifies that the kernel that a change has been made that requires a restart
  676. /// </summary>
  677. public void NotifyPendingRestart()
  678. {
  679. Logger.Info("App needs to be restarted.");
  680. var changed = !HasPendingRestart;
  681. HasPendingRestart = true;
  682. if (changed)
  683. {
  684. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  685. }
  686. }
  687. /// <summary>
  688. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  689. /// </summary>
  690. public void Dispose()
  691. {
  692. Dispose(true);
  693. }
  694. /// <summary>
  695. /// Releases unmanaged and - optionally - managed resources.
  696. /// </summary>
  697. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  698. protected virtual void Dispose(bool dispose)
  699. {
  700. if (dispose)
  701. {
  702. var type = GetType();
  703. Logger.Info("Disposing " + type.Name);
  704. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  705. DisposableParts.Clear();
  706. foreach (var part in parts)
  707. {
  708. Logger.Info("Disposing " + part.GetType().Name);
  709. try
  710. {
  711. part.Dispose();
  712. }
  713. catch (Exception ex)
  714. {
  715. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  716. }
  717. }
  718. }
  719. }
  720. /// <summary>
  721. /// Restarts this instance.
  722. /// </summary>
  723. public abstract Task Restart();
  724. /// <summary>
  725. /// Gets or sets a value indicating whether this instance can self update.
  726. /// </summary>
  727. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  728. public virtual bool CanSelfUpdate
  729. {
  730. get
  731. {
  732. return false;
  733. }
  734. }
  735. /// <summary>
  736. /// Checks for update.
  737. /// </summary>
  738. /// <param name="cancellationToken">The cancellation token.</param>
  739. /// <param name="progress">The progress.</param>
  740. /// <returns>Task{CheckForUpdateResult}.</returns>
  741. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  742. IProgress<double> progress);
  743. /// <summary>
  744. /// Updates the application.
  745. /// </summary>
  746. /// <param name="package">The package that contains the update</param>
  747. /// <param name="cancellationToken">The cancellation token.</param>
  748. /// <param name="progress">The progress.</param>
  749. /// <returns>Task.</returns>
  750. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  751. IProgress<double> progress);
  752. /// <summary>
  753. /// Shuts down.
  754. /// </summary>
  755. public abstract Task Shutdown();
  756. /// <summary>
  757. /// Called when [application updated].
  758. /// </summary>
  759. /// <param name="package">The package.</param>
  760. protected void OnApplicationUpdated(PackageVersionInfo package)
  761. {
  762. Logger.Info("Application has been updated to version {0}", package.versionStr);
  763. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  764. {
  765. Argument = package
  766. }, Logger);
  767. NotifyPendingRestart();
  768. }
  769. }
  770. }