BaseApplicationHost.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. }
  363. var isFirstRun = !File.Exists(plugin.ConfigurationFilePath);
  364. plugin.SetStartupInfo(isFirstRun, File.GetLastWriteTimeUtc, s => Directory.CreateDirectory(s));
  365. }
  366. catch (Exception ex)
  367. {
  368. Logger.ErrorException("Error loading plugin {0}", ex, plugin.GetType().FullName);
  369. return null;
  370. }
  371. return plugin;
  372. }
  373. /// <summary>
  374. /// Discovers the types.
  375. /// </summary>
  376. protected void DiscoverTypes()
  377. {
  378. FailedAssemblies.Clear();
  379. var assemblies = GetComposablePartAssemblies().ToList();
  380. foreach (var assembly in assemblies)
  381. {
  382. Logger.Info("Loading {0}", assembly.FullName);
  383. }
  384. AllConcreteTypes = assemblies
  385. .SelectMany(GetTypes)
  386. .Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType)
  387. .ToArray();
  388. }
  389. /// <summary>
  390. /// Registers resources that classes will depend on
  391. /// </summary>
  392. /// <returns>Task.</returns>
  393. protected virtual Task RegisterResources(IProgress<double> progress)
  394. {
  395. RegisterSingleInstance(ConfigurationManager);
  396. RegisterSingleInstance<IApplicationHost>(this);
  397. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  398. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager, SystemEvents);
  399. RegisterSingleInstance(JsonSerializer);
  400. RegisterSingleInstance(XmlSerializer);
  401. RegisterSingleInstance(MemoryStreamFactory);
  402. RegisterSingleInstance(SystemEvents);
  403. RegisterSingleInstance(LogManager);
  404. RegisterSingleInstance(Logger);
  405. RegisterSingleInstance(TaskManager);
  406. RegisterSingleInstance(EnvironmentInfo);
  407. RegisterSingleInstance(FileSystemManager);
  408. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, MemoryStreamFactory, GetDefaultUserAgent);
  409. RegisterSingleInstance(HttpClient);
  410. RegisterSingleInstance(NetworkManager);
  411. IsoManager = new IsoManager();
  412. RegisterSingleInstance(IsoManager);
  413. ProcessFactory = new ProcessFactory();
  414. RegisterSingleInstance(ProcessFactory);
  415. TimerFactory = new TimerFactory();
  416. RegisterSingleInstance(TimerFactory);
  417. SocketFactory = new SocketFactory(LogManager.GetLogger("SocketFactory"));
  418. RegisterSingleInstance(SocketFactory);
  419. RegisterSingleInstance(CryptographyProvider);
  420. return Task.FromResult(true);
  421. }
  422. private string GetDefaultUserAgent()
  423. {
  424. var name = FormatAttribute(Name);
  425. return name + "/" + ApplicationVersion.ToString();
  426. }
  427. private string FormatAttribute(string str)
  428. {
  429. var arr = str.ToCharArray();
  430. arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
  431. || char.IsWhiteSpace(c))));
  432. var result = new string(arr);
  433. if (string.IsNullOrWhiteSpace(result))
  434. {
  435. result = "Emby";
  436. }
  437. return result;
  438. }
  439. /// <summary>
  440. /// Gets a list of types within an assembly
  441. /// 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
  442. /// </summary>
  443. /// <param name="assembly">The assembly.</param>
  444. /// <returns>IEnumerable{Type}.</returns>
  445. /// <exception cref="System.ArgumentNullException">assembly</exception>
  446. protected IEnumerable<Type> GetTypes(Assembly assembly)
  447. {
  448. if (assembly == null)
  449. {
  450. throw new ArgumentNullException("assembly");
  451. }
  452. try
  453. {
  454. return assembly.GetTypes();
  455. }
  456. catch (ReflectionTypeLoadException ex)
  457. {
  458. if (ex.LoaderExceptions != null)
  459. {
  460. foreach (var loaderException in ex.LoaderExceptions)
  461. {
  462. Logger.Error("LoaderException: " + loaderException.Message);
  463. }
  464. }
  465. // If it fails we can still get a list of the Types it was able to resolve
  466. return ex.Types.Where(t => t != null);
  467. }
  468. }
  469. /// <summary>
  470. /// Creates an instance of type and resolves all constructor dependancies
  471. /// </summary>
  472. /// <param name="type">The type.</param>
  473. /// <returns>System.Object.</returns>
  474. public object CreateInstance(Type type)
  475. {
  476. try
  477. {
  478. return Container.GetInstance(type);
  479. }
  480. catch (Exception ex)
  481. {
  482. Logger.ErrorException("Error creating {0}", ex, type.FullName);
  483. throw;
  484. }
  485. }
  486. /// <summary>
  487. /// Creates the instance safe.
  488. /// </summary>
  489. /// <param name="type">The type.</param>
  490. /// <returns>System.Object.</returns>
  491. protected object CreateInstanceSafe(Type type)
  492. {
  493. try
  494. {
  495. return Container.GetInstance(type);
  496. }
  497. catch (Exception ex)
  498. {
  499. Logger.ErrorException("Error creating {0}", ex, type.FullName);
  500. // Don't blow up in release mode
  501. return null;
  502. }
  503. }
  504. /// <summary>
  505. /// Registers the specified obj.
  506. /// </summary>
  507. /// <typeparam name="T"></typeparam>
  508. /// <param name="obj">The obj.</param>
  509. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  510. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  511. where T : class
  512. {
  513. Container.RegisterSingleton(obj);
  514. if (manageLifetime)
  515. {
  516. var disposable = obj as IDisposable;
  517. if (disposable != null)
  518. {
  519. DisposableParts.Add(disposable);
  520. }
  521. }
  522. }
  523. /// <summary>
  524. /// Registers the single instance.
  525. /// </summary>
  526. /// <typeparam name="T"></typeparam>
  527. /// <param name="func">The func.</param>
  528. protected void RegisterSingleInstance<T>(Func<T> func)
  529. where T : class
  530. {
  531. Container.RegisterSingleton(func);
  532. }
  533. /// <summary>
  534. /// Resolves this instance.
  535. /// </summary>
  536. /// <typeparam name="T"></typeparam>
  537. /// <returns>``0.</returns>
  538. public T Resolve<T>()
  539. {
  540. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  541. }
  542. /// <summary>
  543. /// Resolves this instance.
  544. /// </summary>
  545. /// <typeparam name="T"></typeparam>
  546. /// <returns>``0.</returns>
  547. public T TryResolve<T>()
  548. {
  549. var result = Container.GetRegistration(typeof(T), false);
  550. if (result == null)
  551. {
  552. return default(T);
  553. }
  554. return (T)result.GetInstance();
  555. }
  556. /// <summary>
  557. /// Loads the assembly.
  558. /// </summary>
  559. /// <param name="file">The file.</param>
  560. /// <returns>Assembly.</returns>
  561. protected Assembly LoadAssembly(string file)
  562. {
  563. try
  564. {
  565. return Assembly.Load(File.ReadAllBytes(file));
  566. }
  567. catch (Exception ex)
  568. {
  569. FailedAssemblies.Add(file);
  570. Logger.ErrorException("Error loading assembly {0}", ex, file);
  571. return null;
  572. }
  573. }
  574. /// <summary>
  575. /// Gets the export types.
  576. /// </summary>
  577. /// <typeparam name="T"></typeparam>
  578. /// <returns>IEnumerable{Type}.</returns>
  579. public IEnumerable<Type> GetExportTypes<T>()
  580. {
  581. var currentType = typeof(T);
  582. return AllConcreteTypes.Where(currentType.IsAssignableFrom);
  583. }
  584. /// <summary>
  585. /// Gets the exports.
  586. /// </summary>
  587. /// <typeparam name="T"></typeparam>
  588. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  589. /// <returns>IEnumerable{``0}.</returns>
  590. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  591. {
  592. var parts = GetExportTypes<T>()
  593. .Select(CreateInstanceSafe)
  594. .Where(i => i != null)
  595. .Cast<T>()
  596. .ToList();
  597. if (manageLiftime)
  598. {
  599. lock (DisposableParts)
  600. {
  601. DisposableParts.AddRange(parts.OfType<IDisposable>());
  602. }
  603. }
  604. return parts;
  605. }
  606. /// <summary>
  607. /// Gets the application version.
  608. /// </summary>
  609. /// <value>The application version.</value>
  610. public abstract Version ApplicationVersion { get; }
  611. /// <summary>
  612. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  613. /// </summary>
  614. /// <param name="sender">The source of the event.</param>
  615. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  616. /// <exception cref="System.NotImplementedException"></exception>
  617. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  618. {
  619. ConfigureAutorun();
  620. }
  621. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  622. /// <summary>
  623. /// Removes the plugin.
  624. /// </summary>
  625. /// <param name="plugin">The plugin.</param>
  626. public void RemovePlugin(IPlugin plugin)
  627. {
  628. var list = Plugins.ToList();
  629. list.Remove(plugin);
  630. Plugins = list.ToArray();
  631. }
  632. /// <summary>
  633. /// Gets a value indicating whether this instance can self restart.
  634. /// </summary>
  635. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  636. public abstract bool CanSelfRestart { get; }
  637. /// <summary>
  638. /// Notifies that the kernel that a change has been made that requires a restart
  639. /// </summary>
  640. public void NotifyPendingRestart()
  641. {
  642. Logger.Info("App needs to be restarted.");
  643. var changed = !HasPendingRestart;
  644. HasPendingRestart = true;
  645. if (changed)
  646. {
  647. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  648. }
  649. }
  650. /// <summary>
  651. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  652. /// </summary>
  653. public void Dispose()
  654. {
  655. Dispose(true);
  656. }
  657. /// <summary>
  658. /// Releases unmanaged and - optionally - managed resources.
  659. /// </summary>
  660. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  661. protected virtual void Dispose(bool dispose)
  662. {
  663. if (dispose)
  664. {
  665. var type = GetType();
  666. Logger.Info("Disposing " + type.Name);
  667. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  668. DisposableParts.Clear();
  669. foreach (var part in parts)
  670. {
  671. Logger.Info("Disposing " + part.GetType().Name);
  672. try
  673. {
  674. part.Dispose();
  675. }
  676. catch (Exception ex)
  677. {
  678. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  679. }
  680. }
  681. }
  682. }
  683. /// <summary>
  684. /// Restarts this instance.
  685. /// </summary>
  686. public abstract Task Restart();
  687. /// <summary>
  688. /// Gets or sets a value indicating whether this instance can self update.
  689. /// </summary>
  690. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  691. public virtual bool CanSelfUpdate
  692. {
  693. get
  694. {
  695. return false;
  696. }
  697. }
  698. /// <summary>
  699. /// Checks for update.
  700. /// </summary>
  701. /// <param name="cancellationToken">The cancellation token.</param>
  702. /// <param name="progress">The progress.</param>
  703. /// <returns>Task{CheckForUpdateResult}.</returns>
  704. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  705. IProgress<double> progress);
  706. /// <summary>
  707. /// Updates the application.
  708. /// </summary>
  709. /// <param name="package">The package that contains the update</param>
  710. /// <param name="cancellationToken">The cancellation token.</param>
  711. /// <param name="progress">The progress.</param>
  712. /// <returns>Task.</returns>
  713. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  714. IProgress<double> progress);
  715. /// <summary>
  716. /// Shuts down.
  717. /// </summary>
  718. public abstract Task Shutdown();
  719. /// <summary>
  720. /// Called when [application updated].
  721. /// </summary>
  722. /// <param name="package">The package.</param>
  723. protected void OnApplicationUpdated(PackageVersionInfo package)
  724. {
  725. Logger.Info("Application has been updated to version {0}", package.versionStr);
  726. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  727. {
  728. Argument = package
  729. }, Logger);
  730. NotifyPendingRestart();
  731. }
  732. }
  733. }