MainStartup.cs 28 KB

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