MainStartup.cs 29 KB

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