2
0

BaseApplicationHost.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using Emby.Common.Implementations.Devices;
  4. using Emby.Common.Implementations.IO;
  5. using Emby.Common.Implementations.ScheduledTasks;
  6. using Emby.Common.Implementations.Serialization;
  7. using MediaBrowser.Common.Net;
  8. using MediaBrowser.Common.Plugins;
  9. using MediaBrowser.Common.Progress;
  10. using MediaBrowser.Common.Security;
  11. using MediaBrowser.Common.Updates;
  12. using MediaBrowser.Model.Events;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Model.Serialization;
  16. using MediaBrowser.Model.Updates;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Reflection;
  23. using System.Runtime.InteropServices;
  24. using System.Text;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. using MediaBrowser.Common.Extensions;
  28. using Emby.Common.Implementations.Cryptography;
  29. using Emby.Common.Implementations.Diagnostics;
  30. using Emby.Common.Implementations.Net;
  31. using Emby.Common.Implementations.EnvironmentInfo;
  32. using Emby.Common.Implementations.Threading;
  33. using MediaBrowser.Common;
  34. using MediaBrowser.Model.Cryptography;
  35. using MediaBrowser.Model.Diagnostics;
  36. using MediaBrowser.Model.Net;
  37. using MediaBrowser.Model.System;
  38. using MediaBrowser.Model.Tasks;
  39. using MediaBrowser.Model.Threading;
  40. namespace Emby.Common.Implementations
  41. {
  42. /// <summary>
  43. /// Class BaseApplicationHost
  44. /// </summary>
  45. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  46. public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationHost
  47. where TApplicationPathsType : class, IApplicationPaths
  48. {
  49. /// <summary>
  50. /// Occurs when [has pending restart changed].
  51. /// </summary>
  52. public event EventHandler HasPendingRestartChanged;
  53. /// <summary>
  54. /// Occurs when [application updated].
  55. /// </summary>
  56. public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
  57. /// <summary>
  58. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  59. /// </summary>
  60. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  61. public bool HasPendingRestart { get; private set; }
  62. /// <summary>
  63. /// Gets or sets the logger.
  64. /// </summary>
  65. /// <value>The logger.</value>
  66. protected ILogger Logger { get; private set; }
  67. /// <summary>
  68. /// Gets or sets the plugins.
  69. /// </summary>
  70. /// <value>The plugins.</value>
  71. public IPlugin[] Plugins { get; protected set; }
  72. /// <summary>
  73. /// Gets or sets the log manager.
  74. /// </summary>
  75. /// <value>The log manager.</value>
  76. public ILogManager LogManager { get; protected set; }
  77. /// <summary>
  78. /// Gets the application paths.
  79. /// </summary>
  80. /// <value>The application paths.</value>
  81. protected TApplicationPathsType ApplicationPaths { get; private set; }
  82. /// <summary>
  83. /// The json serializer
  84. /// </summary>
  85. public IJsonSerializer JsonSerializer { get; private set; }
  86. /// <summary>
  87. /// The _XML serializer
  88. /// </summary>
  89. protected readonly IXmlSerializer XmlSerializer;
  90. /// <summary>
  91. /// Gets assemblies that failed to load
  92. /// </summary>
  93. /// <value>The failed assemblies.</value>
  94. public List<string> FailedAssemblies { get; protected set; }
  95. /// <summary>
  96. /// Gets all concrete types.
  97. /// </summary>
  98. /// <value>All concrete types.</value>
  99. public Type[] AllConcreteTypes { get; protected set; }
  100. /// <summary>
  101. /// The disposable parts
  102. /// </summary>
  103. protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
  104. /// <summary>
  105. /// Gets a value indicating whether this instance is first run.
  106. /// </summary>
  107. /// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
  108. public bool IsFirstRun { get; private set; }
  109. /// <summary>
  110. /// Gets the kernel.
  111. /// </summary>
  112. /// <value>The kernel.</value>
  113. protected ITaskManager TaskManager { get; private set; }
  114. /// <summary>
  115. /// Gets the HTTP client.
  116. /// </summary>
  117. /// <value>The HTTP client.</value>
  118. public IHttpClient HttpClient { get; private set; }
  119. /// <summary>
  120. /// Gets the network manager.
  121. /// </summary>
  122. /// <value>The network manager.</value>
  123. protected INetworkManager NetworkManager { get; private set; }
  124. /// <summary>
  125. /// Gets the configuration manager.
  126. /// </summary>
  127. /// <value>The configuration manager.</value>
  128. protected IConfigurationManager ConfigurationManager { get; private set; }
  129. public IFileSystem FileSystemManager { get; private set; }
  130. protected IIsoManager IsoManager { get; private set; }
  131. protected IProcessFactory ProcessFactory { get; private set; }
  132. protected ITimerFactory TimerFactory { get; private set; }
  133. protected ISocketFactory SocketFactory { get; private set; }
  134. /// <summary>
  135. /// Gets the name.
  136. /// </summary>
  137. /// <value>The name.</value>
  138. public abstract string Name { get; }
  139. protected ICryptoProvider CryptographyProvider = new CryptographyProvider();
  140. protected IEnvironmentInfo EnvironmentInfo { get; private set; }
  141. private DeviceId _deviceId;
  142. public string SystemId
  143. {
  144. get
  145. {
  146. if (_deviceId == null)
  147. {
  148. _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager);
  149. }
  150. return _deviceId.Value;
  151. }
  152. }
  153. public PackageVersionClass SystemUpdateLevel
  154. {
  155. get
  156. {
  157. #if BETA
  158. return PackageVersionClass.Beta;
  159. #endif
  160. return PackageVersionClass.Release;
  161. }
  162. }
  163. public virtual string OperatingSystemDisplayName
  164. {
  165. get { return EnvironmentInfo.OperatingSystemName; }
  166. }
  167. /// <summary>
  168. /// The container
  169. /// </summary>
  170. protected readonly SimpleInjector.Container Container = new SimpleInjector.Container();
  171. protected ISystemEvents SystemEvents { get; private set; }
  172. protected IMemoryStreamFactory MemoryStreamFactory { get; private set; }
  173. /// <summary>
  174. /// Initializes a new instance of the <see cref="BaseApplicationHost{TApplicationPathsType}"/> class.
  175. /// </summary>
  176. protected BaseApplicationHost(TApplicationPathsType applicationPaths,
  177. ILogManager logManager,
  178. IFileSystem fileSystem,
  179. IEnvironmentInfo environmentInfo,
  180. ISystemEvents systemEvents,
  181. IMemoryStreamFactory memoryStreamFactory,
  182. INetworkManager networkManager)
  183. {
  184. NetworkManager = networkManager;
  185. EnvironmentInfo = environmentInfo;
  186. SystemEvents = systemEvents;
  187. MemoryStreamFactory = memoryStreamFactory;
  188. // hack alert, until common can target .net core
  189. BaseExtensions.CryptographyProvider = CryptographyProvider;
  190. XmlSerializer = new MyXmlSerializer(fileSystem, logManager.GetLogger("XmlSerializer"));
  191. FailedAssemblies = new List<string>();
  192. ApplicationPaths = applicationPaths;
  193. LogManager = logManager;
  194. FileSystemManager = fileSystem;
  195. ConfigurationManager = GetConfigurationManager();
  196. // Initialize this early in case the -v command line option is used
  197. Logger = LogManager.GetLogger("App");
  198. }
  199. /// <summary>
  200. /// Inits this instance.
  201. /// </summary>
  202. /// <returns>Task.</returns>
  203. public virtual async Task Init(IProgress<double> progress)
  204. {
  205. progress.Report(1);
  206. JsonSerializer = CreateJsonSerializer();
  207. OnLoggerLoaded(true);
  208. LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
  209. IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
  210. progress.Report(2);
  211. LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
  212. ? LogSeverity.Debug
  213. : LogSeverity.Info;
  214. progress.Report(3);
  215. DiscoverTypes();
  216. progress.Report(14);
  217. SetHttpLimit();
  218. progress.Report(15);
  219. var innerProgress = new ActionableProgress<double>();
  220. innerProgress.RegisterAction(p => progress.Report(.8 * p + 15));
  221. await RegisterResources(innerProgress).ConfigureAwait(false);
  222. FindParts();
  223. progress.Report(95);
  224. await InstallIsoMounters(CancellationToken.None).ConfigureAwait(false);
  225. progress.Report(100);
  226. }
  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("64-Bit OS: {0}", Environment.Is64BitOperatingSystem));
  256. builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess));
  257. Type type = Type.GetType("Mono.Runtime");
  258. if (type != null)
  259. {
  260. MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
  261. if (displayName != null)
  262. {
  263. builder.AppendLine("Mono: " + displayName.Invoke(null, null));
  264. }
  265. }
  266. builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount));
  267. builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath));
  268. builder.AppendLine(string.Format("Application directory: {0}", appPaths.ProgramSystemPath));
  269. return builder;
  270. }
  271. protected abstract IJsonSerializer CreateJsonSerializer();
  272. private void SetHttpLimit()
  273. {
  274. try
  275. {
  276. // Increase the max http request limit
  277. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  278. }
  279. catch (Exception ex)
  280. {
  281. Logger.ErrorException("Error setting http limit", ex);
  282. }
  283. }
  284. /// <summary>
  285. /// Installs the iso mounters.
  286. /// </summary>
  287. /// <param name="cancellationToken">The cancellation token.</param>
  288. /// <returns>Task.</returns>
  289. private async Task InstallIsoMounters(CancellationToken cancellationToken)
  290. {
  291. var list = new List<IIsoMounter>();
  292. foreach (var isoMounter in GetExports<IIsoMounter>())
  293. {
  294. try
  295. {
  296. if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
  297. {
  298. Logger.Info("Installing {0}", isoMounter.Name);
  299. await isoMounter.Install(cancellationToken).ConfigureAwait(false);
  300. }
  301. list.Add(isoMounter);
  302. }
  303. catch (Exception ex)
  304. {
  305. Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
  306. }
  307. }
  308. IsoManager.AddParts(list);
  309. }
  310. /// <summary>
  311. /// Runs the startup tasks.
  312. /// </summary>
  313. /// <returns>Task.</returns>
  314. public virtual Task RunStartupTasks()
  315. {
  316. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  317. ConfigureAutorun();
  318. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  319. return Task.FromResult(true);
  320. }
  321. /// <summary>
  322. /// Configures the autorun.
  323. /// </summary>
  324. private void ConfigureAutorun()
  325. {
  326. try
  327. {
  328. ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
  329. }
  330. catch (Exception ex)
  331. {
  332. Logger.ErrorException("Error configuring autorun", ex);
  333. }
  334. }
  335. /// <summary>
  336. /// Gets the composable part assemblies.
  337. /// </summary>
  338. /// <returns>IEnumerable{Assembly}.</returns>
  339. protected abstract IEnumerable<Assembly> GetComposablePartAssemblies();
  340. /// <summary>
  341. /// Gets the configuration manager.
  342. /// </summary>
  343. /// <returns>IConfigurationManager.</returns>
  344. protected abstract IConfigurationManager GetConfigurationManager();
  345. /// <summary>
  346. /// Finds the parts.
  347. /// </summary>
  348. protected virtual void FindParts()
  349. {
  350. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  351. Plugins = GetExports<IPlugin>().Select(LoadPlugin).Where(i => i != null).ToArray();
  352. }
  353. private IPlugin LoadPlugin(IPlugin plugin)
  354. {
  355. try
  356. {
  357. var assemblyPlugin = plugin as IPluginAssembly;
  358. if (assemblyPlugin != null)
  359. {
  360. var assembly = plugin.GetType().Assembly;
  361. var assemblyName = assembly.GetName();
  362. var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
  363. var assemblyId = new Guid(attribute.Value);
  364. var assemblyFileName = assemblyName.Name + ".dll";
  365. var assemblyFilePath = Path.Combine(ApplicationPaths.PluginsPath, assemblyFileName);
  366. assemblyPlugin.SetAttributes(assemblyFilePath, assemblyFileName, assemblyName.Version, assemblyId);
  367. }
  368. var isFirstRun = !File.Exists(plugin.ConfigurationFilePath);
  369. plugin.SetStartupInfo(isFirstRun, File.GetLastWriteTimeUtc, s => Directory.CreateDirectory(s));
  370. }
  371. catch (Exception ex)
  372. {
  373. Logger.ErrorException("Error loading plugin {0}", ex, plugin.GetType().FullName);
  374. return null;
  375. }
  376. return plugin;
  377. }
  378. /// <summary>
  379. /// Discovers the types.
  380. /// </summary>
  381. protected void DiscoverTypes()
  382. {
  383. FailedAssemblies.Clear();
  384. var assemblies = GetComposablePartAssemblies().ToList();
  385. foreach (var assembly in assemblies)
  386. {
  387. Logger.Info("Loading {0}", assembly.FullName);
  388. }
  389. AllConcreteTypes = assemblies
  390. .SelectMany(GetTypes)
  391. .Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType)
  392. .ToArray();
  393. }
  394. /// <summary>
  395. /// Registers resources that classes will depend on
  396. /// </summary>
  397. /// <returns>Task.</returns>
  398. protected virtual Task RegisterResources(IProgress<double> progress)
  399. {
  400. RegisterSingleInstance(ConfigurationManager);
  401. RegisterSingleInstance<IApplicationHost>(this);
  402. RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
  403. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager, SystemEvents);
  404. RegisterSingleInstance(JsonSerializer);
  405. RegisterSingleInstance(XmlSerializer);
  406. RegisterSingleInstance(MemoryStreamFactory);
  407. RegisterSingleInstance(SystemEvents);
  408. RegisterSingleInstance(LogManager);
  409. RegisterSingleInstance(Logger);
  410. RegisterSingleInstance(TaskManager);
  411. RegisterSingleInstance(EnvironmentInfo);
  412. RegisterSingleInstance(FileSystemManager);
  413. HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, MemoryStreamFactory, GetDefaultUserAgent);
  414. RegisterSingleInstance(HttpClient);
  415. RegisterSingleInstance(NetworkManager);
  416. IsoManager = new IsoManager();
  417. RegisterSingleInstance(IsoManager);
  418. ProcessFactory = new ProcessFactory();
  419. RegisterSingleInstance(ProcessFactory);
  420. TimerFactory = new TimerFactory();
  421. RegisterSingleInstance(TimerFactory);
  422. SocketFactory = new SocketFactory(LogManager.GetLogger("SocketFactory"));
  423. RegisterSingleInstance(SocketFactory);
  424. RegisterSingleInstance(CryptographyProvider);
  425. return Task.FromResult(true);
  426. }
  427. private string GetDefaultUserAgent()
  428. {
  429. var name = FormatAttribute(Name);
  430. return name + "/" + ApplicationVersion.ToString();
  431. }
  432. private string FormatAttribute(string str)
  433. {
  434. var arr = str.ToCharArray();
  435. arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
  436. || char.IsWhiteSpace(c))));
  437. var result = new string(arr);
  438. if (string.IsNullOrWhiteSpace(result))
  439. {
  440. result = "Emby";
  441. }
  442. return result;
  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 List<Type> GetTypes(Assembly assembly)
  452. {
  453. if (assembly == null)
  454. {
  455. return new List<Type>();
  456. }
  457. try
  458. {
  459. // This null checking really shouldn't be needed but adding it due to some
  460. // unhandled exceptions in mono 5.0 that are a little hard to hunt down
  461. var types = assembly.GetTypes() ?? new Type[] { };
  462. return types.Where(t => t != null).ToList();
  463. }
  464. catch (ReflectionTypeLoadException ex)
  465. {
  466. if (ex.LoaderExceptions != null)
  467. {
  468. foreach (var loaderException in ex.LoaderExceptions)
  469. {
  470. if (loaderException != null)
  471. {
  472. Logger.Error("LoaderException: " + loaderException.Message);
  473. }
  474. }
  475. }
  476. // If it fails we can still get a list of the Types it was able to resolve
  477. var types = ex.Types ?? new Type[] { };
  478. return types.Where(t => t != null).ToList();
  479. }
  480. catch (Exception ex)
  481. {
  482. Logger.ErrorException("Error loading types from assembly", ex);
  483. return new List<Type>();
  484. }
  485. }
  486. /// <summary>
  487. /// Creates an instance of type and resolves all constructor dependancies
  488. /// </summary>
  489. /// <param name="type">The type.</param>
  490. /// <returns>System.Object.</returns>
  491. public object CreateInstance(Type type)
  492. {
  493. try
  494. {
  495. return Container.GetInstance(type);
  496. }
  497. catch (Exception ex)
  498. {
  499. Logger.ErrorException("Error creating {0}", ex, type.FullName);
  500. throw;
  501. }
  502. }
  503. /// <summary>
  504. /// Creates the instance safe.
  505. /// </summary>
  506. /// <param name="type">The type.</param>
  507. /// <returns>System.Object.</returns>
  508. protected object CreateInstanceSafe(Type type)
  509. {
  510. try
  511. {
  512. return Container.GetInstance(type);
  513. }
  514. catch (Exception ex)
  515. {
  516. Logger.ErrorException("Error creating {0}", ex, type.FullName);
  517. // Don't blow up in release mode
  518. return null;
  519. }
  520. }
  521. /// <summary>
  522. /// Registers the specified obj.
  523. /// </summary>
  524. /// <typeparam name="T"></typeparam>
  525. /// <param name="obj">The obj.</param>
  526. /// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
  527. protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
  528. where T : class
  529. {
  530. Container.RegisterSingleton(obj);
  531. if (manageLifetime)
  532. {
  533. var disposable = obj as IDisposable;
  534. if (disposable != null)
  535. {
  536. DisposableParts.Add(disposable);
  537. }
  538. }
  539. }
  540. /// <summary>
  541. /// Registers the single instance.
  542. /// </summary>
  543. /// <typeparam name="T"></typeparam>
  544. /// <param name="func">The func.</param>
  545. protected void RegisterSingleInstance<T>(Func<T> func)
  546. where T : class
  547. {
  548. Container.RegisterSingleton(func);
  549. }
  550. /// <summary>
  551. /// Resolves this instance.
  552. /// </summary>
  553. /// <typeparam name="T"></typeparam>
  554. /// <returns>``0.</returns>
  555. public T Resolve<T>()
  556. {
  557. return (T)Container.GetRegistration(typeof(T), true).GetInstance();
  558. }
  559. /// <summary>
  560. /// Resolves this instance.
  561. /// </summary>
  562. /// <typeparam name="T"></typeparam>
  563. /// <returns>``0.</returns>
  564. public T TryResolve<T>()
  565. {
  566. var result = Container.GetRegistration(typeof(T), false);
  567. if (result == null)
  568. {
  569. return default(T);
  570. }
  571. return (T)result.GetInstance();
  572. }
  573. /// <summary>
  574. /// Loads the assembly.
  575. /// </summary>
  576. /// <param name="file">The file.</param>
  577. /// <returns>Assembly.</returns>
  578. protected Assembly LoadAssembly(string file)
  579. {
  580. try
  581. {
  582. return Assembly.Load(File.ReadAllBytes(file));
  583. }
  584. catch (Exception ex)
  585. {
  586. FailedAssemblies.Add(file);
  587. Logger.ErrorException("Error loading assembly {0}", ex, file);
  588. return null;
  589. }
  590. }
  591. /// <summary>
  592. /// Gets the export types.
  593. /// </summary>
  594. /// <typeparam name="T"></typeparam>
  595. /// <returns>IEnumerable{Type}.</returns>
  596. public IEnumerable<Type> GetExportTypes<T>()
  597. {
  598. var currentType = typeof(T);
  599. return AllConcreteTypes.Where(currentType.IsAssignableFrom);
  600. }
  601. /// <summary>
  602. /// Gets the exports.
  603. /// </summary>
  604. /// <typeparam name="T"></typeparam>
  605. /// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
  606. /// <returns>IEnumerable{``0}.</returns>
  607. public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
  608. {
  609. var parts = GetExportTypes<T>()
  610. .Select(CreateInstanceSafe)
  611. .Where(i => i != null)
  612. .Cast<T>()
  613. .ToList();
  614. if (manageLiftime)
  615. {
  616. lock (DisposableParts)
  617. {
  618. DisposableParts.AddRange(parts.OfType<IDisposable>());
  619. }
  620. }
  621. return parts;
  622. }
  623. /// <summary>
  624. /// Gets the application version.
  625. /// </summary>
  626. /// <value>The application version.</value>
  627. public abstract Version ApplicationVersion { get; }
  628. /// <summary>
  629. /// Handles the ConfigurationUpdated event of the ConfigurationManager control.
  630. /// </summary>
  631. /// <param name="sender">The source of the event.</param>
  632. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  633. /// <exception cref="System.NotImplementedException"></exception>
  634. protected virtual void OnConfigurationUpdated(object sender, EventArgs e)
  635. {
  636. ConfigureAutorun();
  637. }
  638. protected abstract void ConfigureAutoRunAtStartup(bool autorun);
  639. /// <summary>
  640. /// Removes the plugin.
  641. /// </summary>
  642. /// <param name="plugin">The plugin.</param>
  643. public void RemovePlugin(IPlugin plugin)
  644. {
  645. var list = Plugins.ToList();
  646. list.Remove(plugin);
  647. Plugins = list.ToArray();
  648. }
  649. /// <summary>
  650. /// Gets a value indicating whether this instance can self restart.
  651. /// </summary>
  652. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  653. public abstract bool CanSelfRestart { get; }
  654. /// <summary>
  655. /// Notifies that the kernel that a change has been made that requires a restart
  656. /// </summary>
  657. public void NotifyPendingRestart()
  658. {
  659. Logger.Info("App needs to be restarted.");
  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 virtual bool CanSelfUpdate
  709. {
  710. get
  711. {
  712. return false;
  713. }
  714. }
  715. /// <summary>
  716. /// Checks for update.
  717. /// </summary>
  718. /// <param name="cancellationToken">The cancellation token.</param>
  719. /// <param name="progress">The progress.</param>
  720. /// <returns>Task{CheckForUpdateResult}.</returns>
  721. public abstract Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken,
  722. IProgress<double> progress);
  723. /// <summary>
  724. /// Updates the application.
  725. /// </summary>
  726. /// <param name="package">The package that contains the update</param>
  727. /// <param name="cancellationToken">The cancellation token.</param>
  728. /// <param name="progress">The progress.</param>
  729. /// <returns>Task.</returns>
  730. public abstract Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken,
  731. IProgress<double> progress);
  732. /// <summary>
  733. /// Shuts down.
  734. /// </summary>
  735. public abstract Task Shutdown();
  736. /// <summary>
  737. /// Called when [application updated].
  738. /// </summary>
  739. /// <param name="package">The package.</param>
  740. protected void OnApplicationUpdated(PackageVersionInfo package)
  741. {
  742. Logger.Info("Application has been updated to version {0}", package.versionStr);
  743. EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
  744. {
  745. Argument = package
  746. }, Logger);
  747. NotifyPendingRestart();
  748. }
  749. }
  750. }