BaseApplicationHost.cs 31 KB

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