BaseApplicationHost.cs 30 KB

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