MainStartup.cs 29 KB

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