MainStartup.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. using MediaBrowser.Common.Implementations.Logging;
  2. using MediaBrowser.Model.Logging;
  3. using MediaBrowser.Server.Implementations;
  4. using MediaBrowser.Server.Startup.Common;
  5. using MediaBrowser.Server.Startup.Common.Browser;
  6. using MediaBrowser.ServerApplication.Native;
  7. using MediaBrowser.ServerApplication.Splash;
  8. using MediaBrowser.ServerApplication.Updates;
  9. using Microsoft.Win32;
  10. using System;
  11. using System.Configuration.Install;
  12. using System.Diagnostics;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Management;
  16. using System.Runtime.InteropServices;
  17. using System.ServiceProcess;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Windows.Forms;
  21. using CommonIO.Windows;
  22. using Emby.Drawing.ImageMagick;
  23. using ImageMagickSharp;
  24. using MediaBrowser.Common.Net;
  25. using MediaBrowser.Server.Implementations.Logging;
  26. namespace MediaBrowser.ServerApplication
  27. {
  28. public class MainStartup
  29. {
  30. private static ApplicationHost _appHost;
  31. private static ILogger _logger;
  32. private static bool _isRunningAsService = false;
  33. private static bool _canRestartService = false;
  34. private static bool _appHostDisposed;
  35. [DllImport("kernel32.dll", SetLastError = true)]
  36. static extern bool SetDllDirectory(string lpPathName);
  37. /// <summary>
  38. /// Defines the entry point of the application.
  39. /// </summary>
  40. public static void Main()
  41. {
  42. var options = new StartupOptions();
  43. _isRunningAsService = options.ContainsOption("-service");
  44. _canRestartService = CanRestartWindowsService();
  45. var currentProcess = Process.GetCurrentProcess();
  46. var applicationPath = currentProcess.MainModule.FileName;
  47. var architecturePath = Path.Combine(Path.GetDirectoryName(applicationPath), Environment.Is64BitProcess ? "x64" : "x86");
  48. Wand.SetMagickCoderModulePath(architecturePath);
  49. var success = SetDllDirectory(architecturePath);
  50. var appPaths = CreateApplicationPaths(applicationPath, _isRunningAsService);
  51. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  52. logManager.ReloadLogger(LogSeverity.Debug);
  53. logManager.AddConsoleOutput();
  54. var logger = _logger = logManager.GetLogger("Main");
  55. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  56. // Install directly
  57. if (options.ContainsOption("-installservice"))
  58. {
  59. logger.Info("Performing service installation");
  60. InstallService(applicationPath, logger);
  61. return;
  62. }
  63. // Restart with admin rights, then install
  64. if (options.ContainsOption("-installserviceasadmin"))
  65. {
  66. logger.Info("Performing service installation");
  67. RunServiceInstallation(applicationPath);
  68. return;
  69. }
  70. // Uninstall directly
  71. if (options.ContainsOption("-uninstallservice"))
  72. {
  73. logger.Info("Performing service uninstallation");
  74. UninstallService(applicationPath, logger);
  75. return;
  76. }
  77. // Restart with admin rights, then uninstall
  78. if (options.ContainsOption("-uninstallserviceasadmin"))
  79. {
  80. logger.Info("Performing service uninstallation");
  81. RunServiceUninstallation(applicationPath);
  82. return;
  83. }
  84. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  85. RunServiceInstallationIfNeeded(applicationPath);
  86. if (IsAlreadyRunning(applicationPath, currentProcess))
  87. {
  88. logger.Info("Shutting down because another instance of Emby Server is already running.");
  89. return;
  90. }
  91. if (PerformUpdateIfNeeded(appPaths, logger))
  92. {
  93. logger.Info("Exiting to perform application update.");
  94. return;
  95. }
  96. try
  97. {
  98. RunApplication(appPaths, logManager, _isRunningAsService, options);
  99. }
  100. finally
  101. {
  102. OnServiceShutdown();
  103. }
  104. }
  105. /// <summary>
  106. /// Determines whether [is already running] [the specified current process].
  107. /// </summary>
  108. /// <param name="applicationPath">The application path.</param>
  109. /// <param name="currentProcess">The current process.</param>
  110. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  111. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  112. {
  113. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  114. {
  115. try
  116. {
  117. if (currentProcess.Id == i.Id)
  118. {
  119. return false;
  120. }
  121. }
  122. catch (Exception)
  123. {
  124. return false;
  125. }
  126. try
  127. {
  128. //_logger.Info("Module: {0}", i.MainModule.FileName);
  129. if (string.Equals(applicationPath, i.MainModule.FileName, StringComparison.OrdinalIgnoreCase))
  130. {
  131. return true;
  132. }
  133. return false;
  134. }
  135. catch (Exception)
  136. {
  137. return false;
  138. }
  139. });
  140. if (duplicate != null)
  141. {
  142. _logger.Info("Found a duplicate process. Giving it time to exit.");
  143. if (!duplicate.WaitForExit(15000))
  144. {
  145. _logger.Info("The duplicate process did not exit.");
  146. return true;
  147. }
  148. }
  149. if (!_isRunningAsService)
  150. {
  151. return IsAlreadyRunningAsService(applicationPath);
  152. }
  153. return false;
  154. }
  155. private static bool IsAlreadyRunningAsService(string applicationPath)
  156. {
  157. var serviceName = BackgroundService.GetExistingServiceName();
  158. WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE State = 'Running' AND Name = '{0}'", serviceName));
  159. ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
  160. ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
  161. foreach (ManagementObject managementObject in managementObjectCollection)
  162. {
  163. var obj = managementObject.GetPropertyValue("PathName");
  164. if (obj == null)
  165. {
  166. continue;
  167. }
  168. var path = obj.ToString();
  169. _logger.Info("Service path: {0}", path);
  170. // Need to use indexOf instead of equality because the path will have the full service command line
  171. if (path.IndexOf(applicationPath, StringComparison.OrdinalIgnoreCase) != -1)
  172. {
  173. _logger.Info("The windows service is already running");
  174. MessageBox.Show("Emby Server is already running as a Windows Service. Only one instance is allowed at a time. To run as a tray icon, shut down the Windows Service.");
  175. return true;
  176. }
  177. }
  178. return false;
  179. }
  180. /// <summary>
  181. /// Creates the application paths.
  182. /// </summary>
  183. /// <param name="applicationPath">The application path.</param>
  184. /// <param name="runAsService">if set to <c>true</c> [run as service].</param>
  185. /// <returns>ServerApplicationPaths.</returns>
  186. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
  187. {
  188. var resourcesPath = Path.GetDirectoryName(applicationPath);
  189. if (runAsService)
  190. {
  191. var systemPath = Path.GetDirectoryName(applicationPath);
  192. var programDataPath = Path.GetDirectoryName(systemPath);
  193. return new ServerApplicationPaths(programDataPath, applicationPath, resourcesPath);
  194. }
  195. return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), applicationPath, resourcesPath);
  196. }
  197. /// <summary>
  198. /// Gets a value indicating whether this instance can self restart.
  199. /// </summary>
  200. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  201. public static bool CanSelfRestart
  202. {
  203. get
  204. {
  205. if (_isRunningAsService)
  206. {
  207. return _canRestartService;
  208. }
  209. else
  210. {
  211. return true;
  212. }
  213. }
  214. }
  215. /// <summary>
  216. /// Gets a value indicating whether this instance can self update.
  217. /// </summary>
  218. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  219. public static bool CanSelfUpdate
  220. {
  221. get
  222. {
  223. if (_isRunningAsService)
  224. {
  225. return _canRestartService;
  226. }
  227. else
  228. {
  229. return true;
  230. }
  231. }
  232. }
  233. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  234. /// <summary>
  235. /// Runs the application.
  236. /// </summary>
  237. /// <param name="appPaths">The app paths.</param>
  238. /// <param name="logManager">The log manager.</param>
  239. /// <param name="runService">if set to <c>true</c> [run service].</param>
  240. /// <param name="options">The options.</param>
  241. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
  242. {
  243. var fileSystem = new WindowsFileSystem(new PatternsLogger(logManager.GetLogger("FileSystem")));
  244. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  245. //fileSystem.AddShortcutHandler(new LnkShortcutHandler(fileSystem));
  246. var nativeApp = new WindowsApp(fileSystem, _logger)
  247. {
  248. IsRunningAsService = runService
  249. };
  250. _appHost = new ApplicationHost(appPaths,
  251. logManager,
  252. options,
  253. fileSystem,
  254. "emby.windows.zip",
  255. nativeApp);
  256. var initProgress = new Progress<double>();
  257. if (!runService)
  258. {
  259. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  260. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  261. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  262. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  263. }
  264. var task = _appHost.Init(initProgress);
  265. Task.WaitAll(task);
  266. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  267. if (runService)
  268. {
  269. StartService(logManager);
  270. }
  271. else
  272. {
  273. Task.WaitAll(task);
  274. task = InstallVcredist2013IfNeeded(_appHost, _logger);
  275. Task.WaitAll(task);
  276. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  277. SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  278. HideSplashScreen();
  279. ShowTrayIcon();
  280. task = ApplicationTaskCompletionSource.Task;
  281. Task.WaitAll(task);
  282. }
  283. }
  284. private static ServerNotifyIcon _serverNotifyIcon;
  285. private static TaskScheduler _mainTaskScheduler;
  286. private static void ShowTrayIcon()
  287. {
  288. //Application.EnableVisualStyles();
  289. //Application.SetCompatibleTextRenderingDefault(false);
  290. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  291. _mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  292. Application.Run();
  293. }
  294. private static SplashForm _splash;
  295. private static Thread _splashThread;
  296. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  297. {
  298. var thread = new Thread(() =>
  299. {
  300. _splash = new SplashForm(appVersion, progress);
  301. _splash.ShowDialog();
  302. });
  303. thread.SetApartmentState(ApartmentState.STA);
  304. thread.IsBackground = true;
  305. thread.Start();
  306. _splashThread = thread;
  307. }
  308. private static void HideSplashScreen()
  309. {
  310. if (_splash != null)
  311. {
  312. Action act = () =>
  313. {
  314. _splash.Close();
  315. _splashThread = null;
  316. };
  317. _splash.Invoke(act);
  318. }
  319. }
  320. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  321. {
  322. if (e.Reason == SessionSwitchReason.SessionLogon)
  323. {
  324. BrowserLauncher.OpenDashboard(_appHost);
  325. }
  326. }
  327. public static void Invoke(Action action)
  328. {
  329. if (_isRunningAsService)
  330. {
  331. action();
  332. }
  333. else
  334. {
  335. Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current);
  336. }
  337. }
  338. /// <summary>
  339. /// Starts the service.
  340. /// </summary>
  341. private static void StartService(ILogManager logManager)
  342. {
  343. var service = new BackgroundService(logManager.GetLogger("Service"));
  344. service.Disposed += service_Disposed;
  345. ServiceBase.Run(service);
  346. }
  347. /// <summary>
  348. /// Handles the Disposed event of the service control.
  349. /// </summary>
  350. /// <param name="sender">The source of the event.</param>
  351. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  352. static void service_Disposed(object sender, EventArgs e)
  353. {
  354. ApplicationTaskCompletionSource.SetResult(true);
  355. OnServiceShutdown();
  356. }
  357. private static void OnServiceShutdown()
  358. {
  359. _logger.Info("Shutting down");
  360. DisposeAppHost();
  361. }
  362. /// <summary>
  363. /// Installs the service.
  364. /// </summary>
  365. private static void InstallService(string applicationPath, ILogger logger)
  366. {
  367. try
  368. {
  369. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  370. logger.Info("Service installation succeeded");
  371. }
  372. catch (Exception ex)
  373. {
  374. logger.ErrorException("Uninstall failed", ex);
  375. }
  376. }
  377. /// <summary>
  378. /// Uninstalls the service.
  379. /// </summary>
  380. private static void UninstallService(string applicationPath, ILogger logger)
  381. {
  382. try
  383. {
  384. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  385. logger.Info("Service uninstallation succeeded");
  386. }
  387. catch (Exception ex)
  388. {
  389. logger.ErrorException("Uninstall failed", ex);
  390. }
  391. }
  392. private static void RunServiceInstallationIfNeeded(string applicationPath)
  393. {
  394. var serviceName = BackgroundService.GetExistingServiceName();
  395. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
  396. if (ctl == null)
  397. {
  398. RunServiceInstallation(applicationPath);
  399. }
  400. }
  401. /// <summary>
  402. /// Runs the service installation.
  403. /// </summary>
  404. private static void RunServiceInstallation(string applicationPath)
  405. {
  406. var startInfo = new ProcessStartInfo
  407. {
  408. FileName = applicationPath,
  409. Arguments = "-installservice",
  410. CreateNoWindow = true,
  411. WindowStyle = ProcessWindowStyle.Hidden,
  412. Verb = "runas",
  413. ErrorDialog = false
  414. };
  415. using (var process = Process.Start(startInfo))
  416. {
  417. process.WaitForExit();
  418. }
  419. }
  420. /// <summary>
  421. /// Runs the service uninstallation.
  422. /// </summary>
  423. private static void RunServiceUninstallation(string applicationPath)
  424. {
  425. var startInfo = new ProcessStartInfo
  426. {
  427. FileName = applicationPath,
  428. Arguments = "-uninstallservice",
  429. CreateNoWindow = true,
  430. WindowStyle = ProcessWindowStyle.Hidden,
  431. Verb = "runas",
  432. ErrorDialog = false
  433. };
  434. using (var process = Process.Start(startInfo))
  435. {
  436. process.WaitForExit();
  437. }
  438. }
  439. /// <summary>
  440. /// Handles the SessionEnding event of the SystemEvents control.
  441. /// </summary>
  442. /// <param name="sender">The source of the event.</param>
  443. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  444. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  445. {
  446. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  447. {
  448. Shutdown();
  449. }
  450. }
  451. /// <summary>
  452. /// Handles the UnhandledException event of the CurrentDomain control.
  453. /// </summary>
  454. /// <param name="sender">The source of the event.</param>
  455. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  456. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  457. {
  458. var exception = (Exception)e.ExceptionObject;
  459. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  460. if (!_isRunningAsService)
  461. {
  462. MessageBox.Show("Unhandled exception: " + exception.Message);
  463. }
  464. if (!Debugger.IsAttached)
  465. {
  466. Environment.Exit(Marshal.GetHRForException(exception));
  467. }
  468. }
  469. /// <summary>
  470. /// Performs the update if needed.
  471. /// </summary>
  472. /// <param name="appPaths">The app paths.</param>
  473. /// <param name="logger">The logger.</param>
  474. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  475. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  476. {
  477. // Look for the existence of an update archive
  478. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  479. if (File.Exists(updateArchive))
  480. {
  481. logger.Info("An update is available from {0}", updateArchive);
  482. // Update is there - execute update
  483. try
  484. {
  485. var serviceName = _isRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
  486. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  487. // And just let the app exit so it can update
  488. return true;
  489. }
  490. catch (Exception e)
  491. {
  492. logger.ErrorException("Error starting updater.", e);
  493. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  494. }
  495. }
  496. return false;
  497. }
  498. public static void Shutdown()
  499. {
  500. if (_isRunningAsService)
  501. {
  502. ShutdownWindowsService();
  503. }
  504. else
  505. {
  506. DisposeAppHost();
  507. ShutdownWindowsApplication();
  508. }
  509. }
  510. public static void Restart()
  511. {
  512. DisposeAppHost();
  513. if (_isRunningAsService)
  514. {
  515. RestartWindowsService();
  516. }
  517. else
  518. {
  519. //_logger.Info("Hiding server notify icon");
  520. //_serverNotifyIcon.Visible = false;
  521. _logger.Info("Starting new instance");
  522. //Application.Restart();
  523. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  524. ShutdownWindowsApplication();
  525. }
  526. }
  527. private static void DisposeAppHost()
  528. {
  529. if (!_appHostDisposed)
  530. {
  531. _logger.Info("Disposing app host");
  532. _appHostDisposed = true;
  533. _appHost.Dispose();
  534. }
  535. }
  536. private static void ShutdownWindowsApplication()
  537. {
  538. //_logger.Info("Calling Application.Exit");
  539. //Application.Exit();
  540. _logger.Info("Calling Environment.Exit");
  541. Environment.Exit(0);
  542. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  543. ApplicationTaskCompletionSource.SetResult(true);
  544. }
  545. private static void ShutdownWindowsService()
  546. {
  547. _logger.Info("Stopping background service");
  548. var service = new ServiceController(BackgroundService.GetExistingServiceName());
  549. service.Refresh();
  550. if (service.Status == ServiceControllerStatus.Running)
  551. {
  552. service.Stop();
  553. }
  554. }
  555. private static void RestartWindowsService()
  556. {
  557. _logger.Info("Restarting background service");
  558. var startInfo = new ProcessStartInfo
  559. {
  560. FileName = "cmd.exe",
  561. CreateNoWindow = true,
  562. WindowStyle = ProcessWindowStyle.Hidden,
  563. Verb = "runas",
  564. ErrorDialog = false,
  565. Arguments = String.Format("/c sc stop {0} & sc start {0}", BackgroundService.GetExistingServiceName())
  566. };
  567. Process.Start(startInfo);
  568. }
  569. private static bool CanRestartWindowsService()
  570. {
  571. var startInfo = new ProcessStartInfo
  572. {
  573. FileName = "cmd.exe",
  574. CreateNoWindow = true,
  575. WindowStyle = ProcessWindowStyle.Hidden,
  576. Verb = "runas",
  577. ErrorDialog = false,
  578. Arguments = String.Format("/c sc query {0}", BackgroundService.GetExistingServiceName())
  579. };
  580. using (var process = Process.Start(startInfo))
  581. {
  582. process.WaitForExit();
  583. if (process.ExitCode == 0)
  584. {
  585. return true;
  586. }
  587. else
  588. {
  589. return false;
  590. }
  591. }
  592. }
  593. private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
  594. {
  595. // Reference
  596. // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
  597. try
  598. {
  599. var subkey = Environment.Is64BitProcess
  600. ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x64"
  601. : "SOFTWARE\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x86";
  602. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  603. .OpenSubKey(subkey))
  604. {
  605. if (ndpKey != null && ndpKey.GetValue("Version") != null)
  606. {
  607. var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
  608. if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase))
  609. {
  610. return;
  611. }
  612. }
  613. }
  614. }
  615. catch (Exception ex)
  616. {
  617. logger.ErrorException("Error getting .NET Framework version", ex);
  618. return;
  619. }
  620. try
  621. {
  622. await InstallVcredist2013().ConfigureAwait(false);
  623. }
  624. catch (Exception ex)
  625. {
  626. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  627. }
  628. }
  629. private async static Task InstallVcredist2013()
  630. {
  631. var httpClient = _appHost.HttpClient;
  632. var tmp = await httpClient.GetTempFile(new HttpRequestOptions
  633. {
  634. Url = GetVcredist2013Url(),
  635. Progress = new Progress<double>()
  636. }).ConfigureAwait(false);
  637. var exePath = Path.ChangeExtension(tmp, ".exe");
  638. File.Copy(tmp, exePath);
  639. var startInfo = new ProcessStartInfo
  640. {
  641. FileName = exePath,
  642. CreateNoWindow = true,
  643. WindowStyle = ProcessWindowStyle.Hidden,
  644. Verb = "runas",
  645. ErrorDialog = false
  646. };
  647. _logger.Info("Running {0}", startInfo.FileName);
  648. using (var process = Process.Start(startInfo))
  649. {
  650. process.WaitForExit();
  651. }
  652. }
  653. private static string GetVcredist2013Url()
  654. {
  655. if (Environment.Is64BitProcess)
  656. {
  657. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe";
  658. }
  659. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe
  660. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe";
  661. }
  662. /// <summary>
  663. /// Sets the error mode.
  664. /// </summary>
  665. /// <param name="uMode">The u mode.</param>
  666. /// <returns>ErrorModes.</returns>
  667. [DllImport("kernel32.dll")]
  668. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  669. /// <summary>
  670. /// Enum ErrorModes
  671. /// </summary>
  672. [Flags]
  673. public enum ErrorModes : uint
  674. {
  675. /// <summary>
  676. /// The SYSTE m_ DEFAULT
  677. /// </summary>
  678. SYSTEM_DEFAULT = 0x0,
  679. /// <summary>
  680. /// The SE m_ FAILCRITICALERRORS
  681. /// </summary>
  682. SEM_FAILCRITICALERRORS = 0x0001,
  683. /// <summary>
  684. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  685. /// </summary>
  686. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  687. /// <summary>
  688. /// The SE m_ NOGPFAULTERRORBOX
  689. /// </summary>
  690. SEM_NOGPFAULTERRORBOX = 0x0002,
  691. /// <summary>
  692. /// The SE m_ NOOPENFILEERRORBOX
  693. /// </summary>
  694. SEM_NOOPENFILEERRORBOX = 0x8000
  695. }
  696. }
  697. }