BaseApplicationHost.cs 30 KB

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