BaseApplicationHost.cs 31 KB

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