MainStartup.cs 28 KB

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