BaseApplicationHost.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Implementations.Archiving;
  4. using MediaBrowser.Common.Implementations.Devices;
  5. using MediaBrowser.Common.Implementations.IO;
  6. using MediaBrowser.Common.Implementations.ScheduledTasks;
  7. using MediaBrowser.Common.Implementations.Security;
  8. using MediaBrowser.Common.Implementations.Serialization;
  9. using MediaBrowser.Common.Implementations.Updates;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Common.Plugins;
  12. using MediaBrowser.Common.Progress;
  13. using MediaBrowser.Common.ScheduledTasks;
  14. using MediaBrowser.Common.Security;
  15. using MediaBrowser.Common.Updates;
  16. using MediaBrowser.Model.Events;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Model.Serialization;
  20. using MediaBrowser.Model.Updates;
  21. using ServiceStack;
  22. using SimpleInjector;
  23. using System;
  24. using System.Collections.Generic;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Net;
  28. using System.Reflection;
  29. using System.Text;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. using CommonIO;
  33. using MediaBrowser.Common.IO;
  34. namespace MediaBrowser.Common.Implementations
  35. {
  36. /// <summary>
  37. /// Class BaseApplicationHost
  38. /// </summary>
  39. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  40. public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationHost, IDependencyContainer
  41. where TApplicationPathsType : class, IApplicationPaths
  42. {
  43. /// <summary>
  44. /// Occurs when [has pending restart changed].
  45. /// </summary>
  46. public event EventHandler HasPendingRestartChanged;
  47. /// <summary>
  48. /// Occurs when [application updated].
  49. /// </summary>
  50. public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
  51. /// <summary>
  52. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  53. /// </summary>
  54. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  55. public bool HasPendingRestart { get; private set; }
  56. /// <summary>
  57. /// Gets or sets the logger.
  58. /// </summary>
  59. /// <value>The logger.</value>
  60. protected ILogger Logger { get; private set; }
  61. /// <summary>
  62. /// Gets or sets the plugins.
  63. /// </summary>
  64. /// <value>The plugins.</value>
  65. public IEnumerable<IPlugin> Plugins { get; protected set; }
  66. /// <summary>
  67. /// Gets or sets the log manager.
  68. /// </summary>
  69. /// <value>The log manager.</value>
  70. public ILogManager LogManager { get; protected set; }
  71. /// <summary>
  72. /// Gets the application paths.
  73. /// </summary>
  74. /// <value>The application paths.</value>
  75. protected TApplicationPathsType ApplicationPaths { get; private set; }
  76. /// <summary>
  77. /// The container
  78. /// </summary>
  79. protected readonly Container Container = new Container();
  80. /// <summary>
  81. /// The json serializer
  82. /// </summary>
  83. public IJsonSerializer JsonSerializer { get; private set; }
  84. /// <summary>
  85. /// The _XML serializer
  86. /// </summary>
  87. protected readonly IXmlSerializer XmlSerializer;
  88. /// <summary>
  89. /// Gets assemblies that failed to load
  90. /// </summary>
  91. /// <value>The failed assemblies.</value>
  92. public List<string> FailedAssemblies { get; protected set; }
  93. /// <summary>
  94. /// Gets all concrete types.
  95. /// </summary>
  96. /// <value>All concrete types.</value>
  97. public Type[] AllConcreteTypes { get; protected set; }
  98. /// <summary>
  99. /// The disposable parts
  100. /// </summary>
  101. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  102. /// <summary>
  103. /// Gets a value indicating whether this instance is first run.
  104. /// </summary>
  105. /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
  106. public bool IsFirstRun { get; private set; }
  107. /// <summary>
  108. /// Gets the kernel.
  109. /// </summary>
  110. /// <value>The kernel.</value>
  111. protected ITaskManager TaskManager { get; private set; }
  112. /// <summary>
  113. /// Gets the security manager.
  114. /// </summary>
  115. /// <value>The security manager.</value>
  116. protected ISecurityManager SecurityManager { get; private set; }
  117. /// <summary>
  118. /// Gets the HTTP client.
  119. /// </summary>
  120. /// <value>The HTTP client.</value>
  121. public IHttpClient HttpClient { get; private set; }
  122. /// <summary>
  123. /// Gets the network manager.
  124. /// </summary>
  125. /// <value>The network manager.</value>
  126. protected INetworkManager NetworkManager { get; private set; }
  127. /// <summary>
  128. /// Gets the configuration manager.
  129. /// </summary>
  130. /// <value>The configuration manager.</value>
  131. protected IConfigurationManager ConfigurationManager { get; private set; }
  132. /// <summary>
  133. /// Gets or sets the installation manager.
  134. /// </summary>
  135. /// <value>The installation manager.</value>
  136. protected IInstallationManager InstallationManager { get; private set; }
  137. protected IFileSystem FileSystemManager { get; private set; }
  138. /// <summary>
  139. /// Gets or sets the zip client.
  140. /// </summary>
  141. /// <value>The zip client.</value>
  142. protected IZipClient ZipClient { get; private set; }
  143. protected IIsoManager IsoManager { get; private set; }
  144. /// <summary>
  145. /// Gets the name.
  146. /// </summary>
  147. /// <value>The name.</value>
  148. public abstract string Name { get; }
  149. /// <summary>
  150. /// Gets a value indicating whether this instance is running as service.
  151. /// </summary>
  152. /// <value><c>true</c> if this instance is running as service; otherwise, <c>false</c>.</value>
  153. public abstract bool IsRunningAsService { get; }
  154. private DeviceId _deviceId;
  155. public string SystemId
  156. {
  157. get
  158. {
  159. if (_deviceId == null)
  160. {
  161. _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager);
  162. }
  163. return _deviceId.Value;
  164. }
  165. }
  166. public virtual string OperatingSystemDisplayName
  167. {
  168. get { return Environment.OSVersion.VersionString; }
  169. }
  170. public IMemoryStreamProvider MemoryStreamProvider { get; set; }
  171. /// <summary>
  172. /// Initializes a new instance of the <see cref="BaseApplicationHost{TApplicationPathsType}"/> class.
  173. /// </summary>
  174. protected BaseApplicationHost(TApplicationPathsType applicationPaths,
  175. ILogManager logManager,
  176. IFileSystem fileSystem)
  177. {
  178. XmlSerializer = new XmlSerializer (fileSystem, logManager.GetLogger("XmlSerializer"));
  179. FailedAssemblies = new List<string>();
  180. ApplicationPaths = applicationPaths;
  181. LogManager = logManager;
  182. FileSystemManager = fileSystem;
  183. ConfigurationManager = GetConfigurationManager();
  184. // Initialize this early in case the -v command line option is used
  185. Logger = LogManager.GetLogger("App");
  186. }
  187. /// <summary>
  188. /// Inits this instance.
  189. /// </summary>
  190. /// <returns>Task.</returns>
  191. public virtual async Task Init(IProgress<double> progress)
  192. {
  193. try
  194. {
  195. // https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.WebHost.IntegrationTests/Web.config#L4
  196. Licensing.RegisterLicense("1001-e1JlZjoxMDAxLE5hbWU6VGVzdCBCdXNpbmVzcyxUeXBlOkJ1c2luZXNzLEhhc2g6UHVNTVRPclhvT2ZIbjQ5MG5LZE1mUTd5RUMzQnBucTFEbTE3TDczVEF4QUNMT1FhNXJMOWkzVjFGL2ZkVTE3Q2pDNENqTkQyUktRWmhvUVBhYTBiekJGUUZ3ZE5aZHFDYm9hL3lydGlwUHI5K1JsaTBYbzNsUC85cjVJNHE5QVhldDN6QkE4aTlvdldrdTgyTk1relY2eis2dFFqTThYN2lmc0JveHgycFdjPSxFeHBpcnk6MjAxMy0wMS0wMX0=");
  197. }
  198. catch
  199. {
  200. // Failing under mono
  201. }
  202. progress.Report(1);
  203. JsonSerializer = CreateJsonSerializer();
  204. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  205. {
  206. MemoryStreamProvider = new RecyclableMemoryStreamProvider();
  207. }
  208. else
  209. {
  210. MemoryStreamProvider = new MemoryStreamProvider();
  211. }
  212. OnLoggerLoaded(true);
  213. LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
  214. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  215. progress.Report(2);
  216. LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
  217. ? LogSeverity.Debug
  218. : LogSeverity.Info;
  219. progress.Report(3);
  220. DiscoverTypes();
  221. progress.Report(14);
  222. SetHttpLimit();
  223. progress.Report(15);
  224. var innerProgress = new ActionableProgress<double>();
  225. innerProgress.RegisterAction(p => progress.Report(.8 * p + 15));
  226. await RegisterResources(innerProgress).ConfigureAwait(false);
  227. FindParts();
  228. progress.Report(95);
  229. await InstallIsoMounters(CancellationToken.None).ConfigureAwait(false);
  230. progress.Report(100);
  231. }
  232. protected virtual void OnLoggerLoaded(bool isFirstLoad)
  233. {
  234. Logger.Info("Application version: {0}", ApplicationVersion);
  235. if (!isFirstLoad)
  236. {
  237. LogEnvironmentInfo(Logger, ApplicationPaths, false);
  238. }
  239. // Put the app config in the log for troubleshooting purposes
  240. Logger.LogMultiline("Application configuration:", LogSeverity.Info, new StringBuilder(JsonSerializer.SerializeToString(ConfigurationManager.CommonConfiguration)));
  241. if (Plugins != null)
  242. {
  243. var pluginBuilder = new StringBuilder();
  244. foreach (var plugin in Plugins)
  245. {
  246. pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
  247. }
  248. Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder);
  249. }
  250. }
  251. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, bool isStartup)
  252. {
  253. logger.LogMultiline("Emby", LogSeverity.Info, GetBaseExceptionMessage(appPaths));
  254. }
  255. protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths)
  256. {
  257. var builder = new StringBuilder();
  258. builder.AppendLine(string.Format("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs())));
  259. builder.AppendLine(string.Format("Operating system: {0}", Environment.OSVersion));
  260. builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount));
  261. builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem));
  262. builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess));
  263. builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath));
  264. Type type = Type.GetType("Mono.Runtime");
  265. if (type != null)
  266. {
  267. MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
  268. if (displayName != null)
  269. {
  270. builder.AppendLine("Mono: " + displayName.Invoke(null, null));
  271. }
  272. }
  273. builder.AppendLine(string.Format("Application Path: {0}", appPaths.ApplicationPath));
  274. return builder;
  275. }
  276. protected virtual IJsonSerializer CreateJsonSerializer()
  277. {
  278. return new JsonSerializer(FileSystemManager, LogManager.GetLogger("JsonSerializer"));
  279. }
  280. private void SetHttpLimit()
  281. {
  282. try
  283. {
  284. // Increase the max http request limit
  285. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  286. }
  287. catch (Exception ex)
  288. {
  289. Logger.ErrorException("Error setting http limit", ex);
  290. }
  291. }
  292. /// <summary>
  293. /// Installs the iso mounters.
  294. /// </summary>
  295. /// <param name="cancellationToken">The cancellation token.</param>
  296. /// <returns>Task.</returns>
  297. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  298. {
  299. var list = new List<IIsoMounter>();
  300. foreach (var isoMounter in GetExports<IIsoMounter>())
  301. {
  302. try
  303. {
  304. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  305. {
  306. Logger.Info("Installing {0}", isoMounter.Name);
  307. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  308. }
  309. list.Add(isoMounter);
  310. }
  311. catch (Exception ex)
  312. {
  313. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  314. }
  315. }
  316. IsoManager.AddParts(list);
  317. }
  318. /// <summary>
  319. /// Runs the startup tasks.
  320. /// </summary>
  321. /// <returns>Task.</returns>
  322. public virtual Task RunStartupTasks()
  323. {
  324. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  325. ConfigureAutorun ();
  326. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  327. return Task.FromResult (true);
  328. }
  329. /// <summary>
  330. /// Configures the autorun.
  331. /// </summary>
  332. private void ConfigureAutorun()
  333. {
  334. try
  335. {
  336. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  337. }
  338. catch (Exception ex)
  339. {
  340. Logger.ErrorException("Error configuring autorun", ex);
  341. }
  342. }
  343. /// <summary>
  344. /// Gets the composable part assemblies.
  345. /// </summary>
  346. /// <returns>IEnumerable{Assembly}.</returns>
  347. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  348. /// <summary>
  349. /// Gets the configuration manager.
  350. /// </summary>
  351. /// <returns>IConfigurationManager.</returns>
  352. protected abstract IConfigurationManager GetConfigurationManager();
  353. /// <summary>
  354. /// Finds the parts.
  355. /// </summary>
  356. protected virtual void FindParts()
  357. {
  358. RegisterModules();
  359. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  360. Plugins = GetExports<IPlugin>();
  361. }
  362. /// <summary>
  363. /// Discovers the types.
  364. /// </summary>
  365. protected void DiscoverTypes()
  366. {
  367. FailedAssemblies.Clear();
  368. var assemblies = GetComposablePartAssemblies().ToList();
  369. foreach (var assembly in assemblies)
  370. {
  371. Logger.Info("Loading {0}", assembly.FullName);
  372. }
  373. AllConcreteTypes = assemblies
  374. .SelectMany(GetTypes)
  375. .Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType)
  376. .ToArray();
  377. }
  378. /// <summary>
  379. /// Registers resources that classes will depend on
  380. /// </summary>
  381. /// <returns>Task.</returns>
  382. protected virtual Task RegisterResources(IProgress<double> progress)
  383. {
  384. RegisterSingleInstance(ConfigurationManager);
  385. RegisterSingleInstance<IApplicationHost>(this);
  386. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  387. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager);
  388. RegisterSingleInstance(JsonSerializer);
  389. RegisterSingleInstance(XmlSerializer);
  390. RegisterSingleInstance(MemoryStreamProvider);
  391. RegisterSingleInstance(LogManager);
  392. RegisterSingleInstance(Logger);
  393. RegisterSingleInstance(TaskManager);
  394. RegisterSingleInstance(FileSystemManager);
  395. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, MemoryStreamProvider);
  396. RegisterSingleInstance(HttpClient);
  397. NetworkManager = CreateNetworkManager(LogManager.GetLogger("NetworkManager"));
  398. RegisterSingleInstance(NetworkManager);
  399. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager);
  400. RegisterSingleInstance(SecurityManager);
  401. InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager);
  402. RegisterSingleInstance(InstallationManager);
  403. ZipClient = new ZipClient(FileSystemManager);
  404. RegisterSingleInstance(ZipClient);
  405. IsoManager = new IsoManager();
  406. RegisterSingleInstance(IsoManager);
  407. return Task.FromResult (true);
  408. }
  409. private void RegisterModules()
  410. {
  411. var moduleTypes = GetExportTypes<IDependencyModule>();
  412. foreach (var type in moduleTypes)
  413. {
  414. try
  415. {
  416. var instance = Activator.CreateInstance(type) as IDependencyModule;
  417. if (instance != null)
  418. instance.BindDependencies(this);
  419. }
  420. catch (Exception ex)
  421. {
  422. Logger.ErrorException("Error setting up dependency bindings for " + type.Name, ex);
  423. }
  424. }
  425. }
  426. /// <summary>
  427. /// Gets a list of types within an assembly
  428. /// 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
  429. /// </summary>
  430. /// <param name="assembly">The assembly.</param>
  431. /// <returns>IEnumerable{Type}.</returns>
  432. /// <exception cref="System.ArgumentNullException">assembly</exception>
  433. protected IEnumerable<Type> GetTypes(Assembly assembly)
  434. {
  435. if (assembly == null)
  436. {
  437. throw new ArgumentNullException("assembly");
  438. }
  439. try
  440. {
  441. return assembly.GetTypes();
  442. }
  443. catch (ReflectionTypeLoadException ex)
  444. {
  445. if (ex.LoaderExceptions != null)
  446. {
  447. foreach (var loaderException in ex.LoaderExceptions)
  448. {
  449. Logger.Error("LoaderException: " + loaderException.Message);
  450. }
  451. }
  452. // If it fails we can still get a list of the Types it was able to resolve
  453. return ex.Types.Where(t => t != null);
  454. }
  455. }
  456. protected abstract INetworkManager CreateNetworkManager(ILogger logger);
  457. /// <summary>
  458. /// Creates an instance of type and resolves all constructor dependancies
  459. /// </summary>
  460. /// <param name="type">The type.</param>
  461. /// <returns>System.Object.</returns>
  462. public object CreateInstance(Type type)
  463. {
  464. try
  465. {
  466. return Container.GetInstance(type);
  467. }
  468. catch (Exception ex)
  469. {
  470. Logger.ErrorException("Error creating {0}", ex, type.Name);
  471. throw;
  472. }
  473. }
  474. /// <summary>
  475. /// Creates the instance safe.
  476. /// </summary>
  477. /// <param name="type">The type.</param>
  478. /// <returns>System.Object.</returns>
  479. protected object CreateInstanceSafe(Type type)
  480. {
  481. try
  482. {
  483. return Container.GetInstance(type);
  484. }
  485. catch (Exception ex)
  486. {
  487. Logger.ErrorException("Error creating {0}", ex, type.Name);
  488. // Don't blow up in release mode
  489. return null;
  490. }
  491. }
  492. void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
  493. {
  494. RegisterSingleInstance(obj, manageLifetime);
  495. }
  496. /// <summary>
  497. /// Registers the specified obj.
  498. /// </summary>
  499. /// <typeparam name="T"></typeparam>
  500. /// <param name="obj">The obj.</param>
  501. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  502. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  503. where T : class
  504. {
  505. Container.RegisterSingleton(obj);
  506. if (manageLifetime)
  507. {
  508. var disposable = obj as IDisposable;
  509. if (disposable != null)
  510. {
  511. DisposableParts.Add(disposable);
  512. }
  513. }
  514. }
  515. void IDependencyContainer.RegisterSingleInstance<T>(Func<T> func)
  516. {
  517. RegisterSingleInstance(func);
  518. }
  519. /// <summary>
  520. /// Registers the single instance.
  521. /// </summary>
  522. /// <typeparam name="T"></typeparam>
  523. /// <param name="func">The func.</param>
  524. protected void RegisterSingleInstance<T>(Func<T> func)
  525. where T : class
  526. {
  527. Container.RegisterSingleton(func);
  528. }
  529. void IDependencyContainer.Register(Type typeInterface, Type typeImplementation)
  530. {
  531. Container.Register(typeInterface, typeImplementation);
  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.AsParallel().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;
  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. var changed = !HasPendingRestart;
  643. HasPendingRestart = true;
  644. if (changed)
  645. {
  646. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  647. }
  648. }
  649. /// <summary>
  650. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  651. /// </summary>
  652. public void Dispose()
  653. {
  654. Dispose(true);
  655. }
  656. /// <summary>
  657. /// Releases unmanaged and - optionally - managed resources.
  658. /// </summary>
  659. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  660. protected virtual void Dispose(bool dispose)
  661. {
  662. if (dispose)
  663. {
  664. var type = GetType();
  665. Logger.Info("Disposing " + type.Name);
  666. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  667. DisposableParts.Clear();
  668. foreach (var part in parts)
  669. {
  670. Logger.Info("Disposing " + part.GetType().Name);
  671. try
  672. {
  673. part.Dispose();
  674. }
  675. catch (Exception ex)
  676. {
  677. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  678. }
  679. }
  680. }
  681. }
  682. /// <summary>
  683. /// Restarts this instance.
  684. /// </summary>
  685. public abstract Task Restart();
  686. /// <summary>
  687. /// Gets or sets a value indicating whether this instance can self update.
  688. /// </summary>
  689. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  690. public abstract bool CanSelfUpdate { get; }
  691. /// <summary>
  692. /// Checks for update.
  693. /// </summary>
  694. /// <param name="cancellationToken">The cancellation token.</param>
  695. /// <param name="progress">The progress.</param>
  696. /// <returns>Task{CheckForUpdateResult}.</returns>
  697. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  698. IProgress<double> progress);
  699. /// <summary>
  700. /// Updates the application.
  701. /// </summary>
  702. /// <param name="package">The package that contains the update</param>
  703. /// <param name="cancellationToken">The cancellation token.</param>
  704. /// <param name="progress">The progress.</param>
  705. /// <returns>Task.</returns>
  706. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  707. IProgress<double> progress);
  708. /// <summary>
  709. /// Shuts down.
  710. /// </summary>
  711. public abstract Task Shutdown();
  712. /// <summary>
  713. /// Called when [application updated].
  714. /// </summary>
  715. /// <param name="package">The package.</param>
  716. protected void OnApplicationUpdated(PackageVersionInfo package)
  717. {
  718. Logger.Info("Application has been updated to version {0}", package.versionStr);
  719. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  720. {
  721. Argument = package
  722. }, Logger);
  723. NotifyPendingRestart();
  724. }
  725. }
  726. }