BaseApplicationHost.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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. MemoryStreamProvider = new MemoryStreamProvider();
  205. OnLoggerLoaded(true);
  206. LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
  207. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  208. progress.Report(2);
  209. LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
  210. ? LogSeverity.Debug
  211. : LogSeverity.Info;
  212. progress.Report(3);
  213. DiscoverTypes();
  214. progress.Report(14);
  215. SetHttpLimit();
  216. progress.Report(15);
  217. var innerProgress = new ActionableProgress<double>();
  218. innerProgress.RegisterAction(p => progress.Report(.8 * p + 15));
  219. await RegisterResources(innerProgress).ConfigureAwait(false);
  220. FindParts();
  221. progress.Report(95);
  222. await InstallIsoMounters(CancellationToken.None).ConfigureAwait(false);
  223. progress.Report(100);
  224. }
  225. protected virtual void OnLoggerLoaded(bool isFirstLoad)
  226. {
  227. Logger.Info("Application version: {0}", ApplicationVersion);
  228. if (!isFirstLoad)
  229. {
  230. LogEnvironmentInfo(Logger, ApplicationPaths, false);
  231. }
  232. // Put the app config in the log for troubleshooting purposes
  233. Logger.LogMultiline("Application configuration:", LogSeverity.Info, new StringBuilder(JsonSerializer.SerializeToString(ConfigurationManager.CommonConfiguration)));
  234. if (Plugins != null)
  235. {
  236. var pluginBuilder = new StringBuilder();
  237. foreach (var plugin in Plugins)
  238. {
  239. pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
  240. }
  241. Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder);
  242. }
  243. }
  244. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, bool isStartup)
  245. {
  246. logger.LogMultiline("Emby", LogSeverity.Info, GetBaseExceptionMessage(appPaths));
  247. }
  248. protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths)
  249. {
  250. var builder = new StringBuilder();
  251. builder.AppendLine(string.Format("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs())));
  252. builder.AppendLine(string.Format("Operating system: {0}", Environment.OSVersion));
  253. builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount));
  254. builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem));
  255. builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess));
  256. builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath));
  257. Type type = Type.GetType("Mono.Runtime");
  258. if (type != null)
  259. {
  260. MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
  261. if (displayName != null)
  262. {
  263. builder.AppendLine("Mono: " + displayName.Invoke(null, null));
  264. }
  265. }
  266. builder.AppendLine(string.Format("Application Path: {0}", appPaths.ApplicationPath));
  267. return builder;
  268. }
  269. protected virtual IJsonSerializer CreateJsonSerializer()
  270. {
  271. return new JsonSerializer(FileSystemManager, LogManager.GetLogger("JsonSerializer"));
  272. }
  273. private void SetHttpLimit()
  274. {
  275. try
  276. {
  277. // Increase the max http request limit
  278. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  279. }
  280. catch (Exception ex)
  281. {
  282. Logger.ErrorException("Error setting http limit", ex);
  283. }
  284. }
  285. /// <summary>
  286. /// Installs the iso mounters.
  287. /// </summary>
  288. /// <param name="cancellationToken">The cancellation token.</param>
  289. /// <returns>Task.</returns>
  290. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  291. {
  292. var list = new List<IIsoMounter>();
  293. foreach (var isoMounter in GetExports<IIsoMounter>())
  294. {
  295. try
  296. {
  297. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  298. {
  299. Logger.Info("Installing {0}", isoMounter.Name);
  300. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  301. }
  302. list.Add(isoMounter);
  303. }
  304. catch (Exception ex)
  305. {
  306. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  307. }
  308. }
  309. IsoManager.AddParts(list);
  310. }
  311. /// <summary>
  312. /// Runs the startup tasks.
  313. /// </summary>
  314. /// <returns>Task.</returns>
  315. public virtual Task RunStartupTasks()
  316. {
  317. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  318. ConfigureAutorun ();
  319. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  320. return Task.FromResult (true);
  321. }
  322. /// <summary>
  323. /// Configures the autorun.
  324. /// </summary>
  325. private void ConfigureAutorun()
  326. {
  327. try
  328. {
  329. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  330. }
  331. catch (Exception ex)
  332. {
  333. Logger.ErrorException("Error configuring autorun", ex);
  334. }
  335. }
  336. /// <summary>
  337. /// Gets the composable part assemblies.
  338. /// </summary>
  339. /// <returns>IEnumerable{Assembly}.</returns>
  340. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  341. /// <summary>
  342. /// Gets the configuration manager.
  343. /// </summary>
  344. /// <returns>IConfigurationManager.</returns>
  345. protected abstract IConfigurationManager GetConfigurationManager();
  346. /// <summary>
  347. /// Finds the parts.
  348. /// </summary>
  349. protected virtual void FindParts()
  350. {
  351. RegisterModules();
  352. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  353. Plugins = GetExports<IPlugin>();
  354. }
  355. /// <summary>
  356. /// Discovers the types.
  357. /// </summary>
  358. protected void DiscoverTypes()
  359. {
  360. FailedAssemblies.Clear();
  361. var assemblies = GetComposablePartAssemblies().ToList();
  362. foreach (var assembly in assemblies)
  363. {
  364. Logger.Info("Loading {0}", assembly.FullName);
  365. }
  366. AllConcreteTypes = assemblies
  367. .SelectMany(GetTypes)
  368. .Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType)
  369. .ToArray();
  370. }
  371. /// <summary>
  372. /// Registers resources that classes will depend on
  373. /// </summary>
  374. /// <returns>Task.</returns>
  375. protected virtual Task RegisterResources(IProgress<double> progress)
  376. {
  377. RegisterSingleInstance(ConfigurationManager);
  378. RegisterSingleInstance<IApplicationHost>(this);
  379. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  380. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager);
  381. RegisterSingleInstance(JsonSerializer);
  382. RegisterSingleInstance(XmlSerializer);
  383. RegisterSingleInstance(MemoryStreamProvider);
  384. RegisterSingleInstance(LogManager);
  385. RegisterSingleInstance(Logger);
  386. RegisterSingleInstance(TaskManager);
  387. RegisterSingleInstance(FileSystemManager);
  388. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, MemoryStreamProvider);
  389. RegisterSingleInstance(HttpClient);
  390. NetworkManager = CreateNetworkManager(LogManager.GetLogger("NetworkManager"));
  391. RegisterSingleInstance(NetworkManager);
  392. SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager);
  393. RegisterSingleInstance(SecurityManager);
  394. InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager);
  395. RegisterSingleInstance(InstallationManager);
  396. ZipClient = new ZipClient(FileSystemManager);
  397. RegisterSingleInstance(ZipClient);
  398. IsoManager = new IsoManager();
  399. RegisterSingleInstance(IsoManager);
  400. return Task.FromResult (true);
  401. }
  402. private void RegisterModules()
  403. {
  404. var moduleTypes = GetExportTypes<IDependencyModule>();
  405. foreach (var type in moduleTypes)
  406. {
  407. try
  408. {
  409. var instance = Activator.CreateInstance(type) as IDependencyModule;
  410. if (instance != null)
  411. instance.BindDependencies(this);
  412. }
  413. catch (Exception ex)
  414. {
  415. Logger.ErrorException("Error setting up dependency bindings for " + type.Name, ex);
  416. }
  417. }
  418. }
  419. /// <summary>
  420. /// Gets a list of types within an assembly
  421. /// 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
  422. /// </summary>
  423. /// <param name="assembly">The assembly.</param>
  424. /// <returns>IEnumerable{Type}.</returns>
  425. /// <exception cref="System.ArgumentNullException">assembly</exception>
  426. protected IEnumerable<Type> GetTypes(Assembly assembly)
  427. {
  428. if (assembly == null)
  429. {
  430. throw new ArgumentNullException("assembly");
  431. }
  432. try
  433. {
  434. return assembly.GetTypes();
  435. }
  436. catch (ReflectionTypeLoadException ex)
  437. {
  438. if (ex.LoaderExceptions != null)
  439. {
  440. foreach (var loaderException in ex.LoaderExceptions)
  441. {
  442. Logger.Error("LoaderException: " + loaderException.Message);
  443. }
  444. }
  445. // If it fails we can still get a list of the Types it was able to resolve
  446. return ex.Types.Where(t => t != null);
  447. }
  448. }
  449. protected abstract INetworkManager CreateNetworkManager(ILogger logger);
  450. /// <summary>
  451. /// Creates an instance of type and resolves all constructor dependancies
  452. /// </summary>
  453. /// <param name="type">The type.</param>
  454. /// <returns>System.Object.</returns>
  455. public object CreateInstance(Type type)
  456. {
  457. try
  458. {
  459. return Container.GetInstance(type);
  460. }
  461. catch (Exception ex)
  462. {
  463. Logger.ErrorException("Error creating {0}", ex, type.Name);
  464. throw;
  465. }
  466. }
  467. /// <summary>
  468. /// Creates the instance safe.
  469. /// </summary>
  470. /// <param name="type">The type.</param>
  471. /// <returns>System.Object.</returns>
  472. protected object CreateInstanceSafe(Type type)
  473. {
  474. try
  475. {
  476. return Container.GetInstance(type);
  477. }
  478. catch (Exception ex)
  479. {
  480. Logger.ErrorException("Error creating {0}", ex, type.Name);
  481. // Don't blow up in release mode
  482. return null;
  483. }
  484. }
  485. void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
  486. {
  487. RegisterSingleInstance(obj, manageLifetime);
  488. }
  489. /// <summary>
  490. /// Registers the specified obj.
  491. /// </summary>
  492. /// <typeparam name="T"></typeparam>
  493. /// <param name="obj">The obj.</param>
  494. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  495. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  496. where T : class
  497. {
  498. Container.RegisterSingleton(obj);
  499. if (manageLifetime)
  500. {
  501. var disposable = obj as IDisposable;
  502. if (disposable != null)
  503. {
  504. DisposableParts.Add(disposable);
  505. }
  506. }
  507. }
  508. void IDependencyContainer.RegisterSingleInstance<T>(Func<T> func)
  509. {
  510. RegisterSingleInstance(func);
  511. }
  512. /// <summary>
  513. /// Registers the single instance.
  514. /// </summary>
  515. /// <typeparam name="T"></typeparam>
  516. /// <param name="func">The func.</param>
  517. protected void RegisterSingleInstance<T>(Func<T> func)
  518. where T : class
  519. {
  520. Container.RegisterSingleton(func);
  521. }
  522. void IDependencyContainer.Register(Type typeInterface, Type typeImplementation)
  523. {
  524. Container.Register(typeInterface, typeImplementation);
  525. }
  526. /// <summary>
  527. /// Resolves this instance.
  528. /// </summary>
  529. /// <typeparam name="T"></typeparam>
  530. /// <returns>``0.</returns>
  531. public T Resolve<T>()
  532. {
  533. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  534. }
  535. /// <summary>
  536. /// Resolves this instance.
  537. /// </summary>
  538. /// <typeparam name="T"></typeparam>
  539. /// <returns>``0.</returns>
  540. public T TryResolve<T>()
  541. {
  542. var result = Container.GetRegistration(typeof(T), false);
  543. if (result == null)
  544. {
  545. return default(T);
  546. }
  547. return (T)result.GetInstance();
  548. }
  549. /// <summary>
  550. /// Loads the assembly.
  551. /// </summary>
  552. /// <param name="file">The file.</param>
  553. /// <returns>Assembly.</returns>
  554. protected Assembly LoadAssembly(string file)
  555. {
  556. try
  557. {
  558. return Assembly.Load(File.ReadAllBytes(file));
  559. }
  560. catch (Exception ex)
  561. {
  562. FailedAssemblies.Add(file);
  563. Logger.ErrorException("Error loading assembly {0}", ex, file);
  564. return null;
  565. }
  566. }
  567. /// <summary>
  568. /// Gets the export types.
  569. /// </summary>
  570. /// <typeparam name="T"></typeparam>
  571. /// <returns>IEnumerable{Type}.</returns>
  572. public IEnumerable<Type> GetExportTypes<T>()
  573. {
  574. var currentType = typeof(T);
  575. return AllConcreteTypes.AsParallel().Where(currentType.IsAssignableFrom);
  576. }
  577. /// <summary>
  578. /// Gets the exports.
  579. /// </summary>
  580. /// <typeparam name="T"></typeparam>
  581. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  582. /// <returns>IEnumerable{``0}.</returns>
  583. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  584. {
  585. var parts = GetExportTypes<T>()
  586. .Select(CreateInstanceSafe)
  587. .Where(i => i != null)
  588. .Cast<T>()
  589. .ToList();
  590. if (manageLiftime)
  591. {
  592. lock (DisposableParts)
  593. {
  594. DisposableParts.AddRange(parts.OfType<IDisposable>());
  595. }
  596. }
  597. return parts;
  598. }
  599. /// <summary>
  600. /// Gets the application version.
  601. /// </summary>
  602. /// <value>The application version.</value>
  603. public abstract Version ApplicationVersion { get; }
  604. /// <summary>
  605. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  606. /// </summary>
  607. /// <param name="sender">The source of the event.</param>
  608. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  609. /// <exception cref="System.NotImplementedException"></exception>
  610. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  611. {
  612. ConfigureAutorun();
  613. }
  614. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  615. /// <summary>
  616. /// Removes the plugin.
  617. /// </summary>
  618. /// <param name="plugin">The plugin.</param>
  619. public void RemovePlugin(IPlugin plugin)
  620. {
  621. var list = Plugins.ToList();
  622. list.Remove(plugin);
  623. Plugins = list;
  624. }
  625. /// <summary>
  626. /// Gets a value indicating whether this instance can self restart.
  627. /// </summary>
  628. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  629. public abstract bool CanSelfRestart { get; }
  630. /// <summary>
  631. /// Notifies that the kernel that a change has been made that requires a restart
  632. /// </summary>
  633. public void NotifyPendingRestart()
  634. {
  635. var changed = !HasPendingRestart;
  636. HasPendingRestart = true;
  637. if (changed)
  638. {
  639. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  640. }
  641. }
  642. /// <summary>
  643. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  644. /// </summary>
  645. public void Dispose()
  646. {
  647. Dispose(true);
  648. }
  649. /// <summary>
  650. /// Releases unmanaged and - optionally - managed resources.
  651. /// </summary>
  652. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  653. protected virtual void Dispose(bool dispose)
  654. {
  655. if (dispose)
  656. {
  657. var type = GetType();
  658. Logger.Info("Disposing " + type.Name);
  659. var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  660. DisposableParts.Clear();
  661. foreach (var part in parts)
  662. {
  663. Logger.Info("Disposing " + part.GetType().Name);
  664. try
  665. {
  666. part.Dispose();
  667. }
  668. catch (Exception ex)
  669. {
  670. Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
  671. }
  672. }
  673. }
  674. }
  675. /// <summary>
  676. /// Restarts this instance.
  677. /// </summary>
  678. public abstract Task Restart();
  679. /// <summary>
  680. /// Gets or sets a value indicating whether this instance can self update.
  681. /// </summary>
  682. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  683. public abstract bool CanSelfUpdate { get; }
  684. /// <summary>
  685. /// Checks for update.
  686. /// </summary>
  687. /// <param name="cancellationToken">The cancellation token.</param>
  688. /// <param name="progress">The progress.</param>
  689. /// <returns>Task{CheckForUpdateResult}.</returns>
  690. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  691. IProgress<double> progress);
  692. /// <summary>
  693. /// Updates the application.
  694. /// </summary>
  695. /// <param name="package">The package that contains the update</param>
  696. /// <param name="cancellationToken">The cancellation token.</param>
  697. /// <param name="progress">The progress.</param>
  698. /// <returns>Task.</returns>
  699. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  700. IProgress<double> progress);
  701. /// <summary>
  702. /// Shuts down.
  703. /// </summary>
  704. public abstract Task Shutdown();
  705. /// <summary>
  706. /// Called when [application updated].
  707. /// </summary>
  708. /// <param name="package">The package.</param>
  709. protected void OnApplicationUpdated(PackageVersionInfo package)
  710. {
  711. Logger.Info("Application has been updated to version {0}", package.versionStr);
  712. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  713. {
  714. Argument = package
  715. }, Logger);
  716. NotifyPendingRestart();
  717. }
  718. }
  719. }