BaseApplicationHost.cs 31 KB

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