MainStartup.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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. "emby.windows.zip",
  278. nativeApp);
  279. var initProgress = new Progress<double>();
  280. if (!runService)
  281. {
  282. if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
  283. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  284. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  285. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  286. }
  287. var task = _appHost.Init(initProgress);
  288. Task.WaitAll(task);
  289. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  290. if (runService)
  291. {
  292. StartService(logManager);
  293. }
  294. else
  295. {
  296. Task.WaitAll(task);
  297. task = InstallVcredist2013IfNeeded(_appHost, _logger);
  298. Task.WaitAll(task);
  299. Microsoft.Win32.SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  300. Microsoft.Win32.SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  301. HideSplashScreen();
  302. ShowTrayIcon();
  303. task = ApplicationTaskCompletionSource.Task;
  304. Task.WaitAll(task);
  305. }
  306. }
  307. private static ServerNotifyIcon _serverNotifyIcon;
  308. private static TaskScheduler _mainTaskScheduler;
  309. private static void ShowTrayIcon()
  310. {
  311. //Application.EnableVisualStyles();
  312. //Application.SetCompatibleTextRenderingDefault(false);
  313. _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
  314. _mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  315. Application.Run();
  316. }
  317. internal static SplashForm _splash;
  318. private static Thread _splashThread;
  319. private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
  320. {
  321. var thread = new Thread(() =>
  322. {
  323. _splash = new SplashForm(appVersion, progress);
  324. _splash.ShowDialog();
  325. });
  326. thread.SetApartmentState(ApartmentState.STA);
  327. thread.IsBackground = true;
  328. thread.Start();
  329. _splashThread = thread;
  330. }
  331. private static void HideSplashScreen()
  332. {
  333. if (_splash != null)
  334. {
  335. Action act = () =>
  336. {
  337. _splash.Close();
  338. _splashThread = null;
  339. };
  340. _splash.Invoke(act);
  341. }
  342. }
  343. static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
  344. {
  345. if (e.Reason == SessionSwitchReason.SessionLogon)
  346. {
  347. BrowserLauncher.OpenDashboard(_appHost);
  348. }
  349. }
  350. public static void Invoke(Action action)
  351. {
  352. if (_isRunningAsService)
  353. {
  354. action();
  355. }
  356. else
  357. {
  358. Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current);
  359. }
  360. }
  361. /// <summary>
  362. /// Starts the service.
  363. /// </summary>
  364. private static void StartService(ILogManager logManager)
  365. {
  366. var service = new BackgroundService(logManager.GetLogger("Service"));
  367. service.Disposed += service_Disposed;
  368. ServiceBase.Run(service);
  369. }
  370. /// <summary>
  371. /// Handles the Disposed event of the service control.
  372. /// </summary>
  373. /// <param name="sender">The source of the event.</param>
  374. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  375. static void service_Disposed(object sender, EventArgs e)
  376. {
  377. ApplicationTaskCompletionSource.SetResult(true);
  378. OnServiceShutdown();
  379. }
  380. private static void OnServiceShutdown()
  381. {
  382. _logger.Info("Shutting down");
  383. DisposeAppHost();
  384. }
  385. /// <summary>
  386. /// Installs the service.
  387. /// </summary>
  388. private static void InstallService(string applicationPath, ILogger logger)
  389. {
  390. try
  391. {
  392. ManagedInstallerClass.InstallHelper(new[] { applicationPath });
  393. logger.Info("Service installation succeeded");
  394. }
  395. catch (Exception ex)
  396. {
  397. logger.ErrorException("Uninstall failed", ex);
  398. }
  399. }
  400. /// <summary>
  401. /// Uninstalls the service.
  402. /// </summary>
  403. private static void UninstallService(string applicationPath, ILogger logger)
  404. {
  405. try
  406. {
  407. ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
  408. logger.Info("Service uninstallation succeeded");
  409. }
  410. catch (Exception ex)
  411. {
  412. logger.ErrorException("Uninstall failed", ex);
  413. }
  414. }
  415. private static void RunServiceInstallationIfNeeded(string applicationPath)
  416. {
  417. var serviceName = BackgroundService.GetExistingServiceName();
  418. var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
  419. if (ctl == null)
  420. {
  421. RunServiceInstallation(applicationPath);
  422. }
  423. }
  424. /// <summary>
  425. /// Runs the service installation.
  426. /// </summary>
  427. private static void RunServiceInstallation(string applicationPath)
  428. {
  429. var startInfo = new ProcessStartInfo
  430. {
  431. FileName = applicationPath,
  432. Arguments = "-installservice",
  433. CreateNoWindow = true,
  434. WindowStyle = ProcessWindowStyle.Hidden,
  435. Verb = "runas",
  436. ErrorDialog = false
  437. };
  438. using (var process = Process.Start(startInfo))
  439. {
  440. process.WaitForExit();
  441. }
  442. }
  443. /// <summary>
  444. /// Runs the service uninstallation.
  445. /// </summary>
  446. private static void RunServiceUninstallation(string applicationPath)
  447. {
  448. var startInfo = new ProcessStartInfo
  449. {
  450. FileName = applicationPath,
  451. Arguments = "-uninstallservice",
  452. CreateNoWindow = true,
  453. WindowStyle = ProcessWindowStyle.Hidden,
  454. Verb = "runas",
  455. ErrorDialog = false
  456. };
  457. using (var process = Process.Start(startInfo))
  458. {
  459. process.WaitForExit();
  460. }
  461. }
  462. /// <summary>
  463. /// Handles the SessionEnding event of the SystemEvents control.
  464. /// </summary>
  465. /// <param name="sender">The source of the event.</param>
  466. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  467. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  468. {
  469. if (e.Reason == SessionEndReasons.SystemShutdown || !_isRunningAsService)
  470. {
  471. Shutdown();
  472. }
  473. }
  474. /// <summary>
  475. /// Handles the UnhandledException event of the CurrentDomain control.
  476. /// </summary>
  477. /// <param name="sender">The source of the event.</param>
  478. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  479. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  480. {
  481. var exception = (Exception)e.ExceptionObject;
  482. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  483. if (!_isRunningAsService)
  484. {
  485. MessageBox.Show("Unhandled exception: " + exception.Message);
  486. }
  487. if (!Debugger.IsAttached)
  488. {
  489. Environment.Exit(Marshal.GetHRForException(exception));
  490. }
  491. }
  492. /// <summary>
  493. /// Performs the update if needed.
  494. /// </summary>
  495. /// <param name="appPaths">The app paths.</param>
  496. /// <param name="logger">The logger.</param>
  497. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  498. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  499. {
  500. // Look for the existence of an update archive
  501. var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
  502. if (File.Exists(updateArchive))
  503. {
  504. logger.Info("An update is available from {0}", updateArchive);
  505. // Update is there - execute update
  506. try
  507. {
  508. var serviceName = _isRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
  509. new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
  510. // And just let the app exit so it can update
  511. return true;
  512. }
  513. catch (Exception e)
  514. {
  515. logger.ErrorException("Error starting updater.", e);
  516. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  517. }
  518. }
  519. return false;
  520. }
  521. public static void Shutdown()
  522. {
  523. if (_isRunningAsService)
  524. {
  525. ShutdownWindowsService();
  526. }
  527. else
  528. {
  529. DisposeAppHost();
  530. ShutdownWindowsApplication();
  531. }
  532. }
  533. public static void Restart()
  534. {
  535. DisposeAppHost();
  536. if (_isRunningAsService)
  537. {
  538. RestartWindowsService();
  539. }
  540. else
  541. {
  542. //_logger.Info("Hiding server notify icon");
  543. //_serverNotifyIcon.Visible = false;
  544. _logger.Info("Starting new instance");
  545. //Application.Restart();
  546. Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath);
  547. ShutdownWindowsApplication();
  548. }
  549. }
  550. private static void DisposeAppHost()
  551. {
  552. if (!_appHostDisposed)
  553. {
  554. _logger.Info("Disposing app host");
  555. _appHostDisposed = true;
  556. _appHost.Dispose();
  557. }
  558. }
  559. private static void ShutdownWindowsApplication()
  560. {
  561. if (_serverNotifyIcon != null)
  562. {
  563. _serverNotifyIcon.Dispose();
  564. _serverNotifyIcon = null;
  565. }
  566. //_logger.Info("Calling Application.Exit");
  567. //Application.Exit();
  568. _logger.Info("Calling Environment.Exit");
  569. Environment.Exit(0);
  570. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  571. ApplicationTaskCompletionSource.SetResult(true);
  572. }
  573. private static void ShutdownWindowsService()
  574. {
  575. _logger.Info("Stopping background service");
  576. var service = new ServiceController(BackgroundService.GetExistingServiceName());
  577. service.Refresh();
  578. if (service.Status == ServiceControllerStatus.Running)
  579. {
  580. service.Stop();
  581. }
  582. }
  583. private static void RestartWindowsService()
  584. {
  585. _logger.Info("Restarting background service");
  586. var startInfo = new ProcessStartInfo
  587. {
  588. FileName = "cmd.exe",
  589. CreateNoWindow = true,
  590. WindowStyle = ProcessWindowStyle.Hidden,
  591. Verb = "runas",
  592. ErrorDialog = false,
  593. Arguments = String.Format("/c sc stop {0} & sc start {0} & sc start {0}", BackgroundService.GetExistingServiceName())
  594. };
  595. Process.Start(startInfo);
  596. }
  597. private static bool CanRestartWindowsService()
  598. {
  599. var startInfo = new ProcessStartInfo
  600. {
  601. FileName = "cmd.exe",
  602. CreateNoWindow = true,
  603. WindowStyle = ProcessWindowStyle.Hidden,
  604. Verb = "runas",
  605. ErrorDialog = false,
  606. Arguments = String.Format("/c sc query {0}", BackgroundService.GetExistingServiceName())
  607. };
  608. using (var process = Process.Start(startInfo))
  609. {
  610. process.WaitForExit();
  611. if (process.ExitCode == 0)
  612. {
  613. return true;
  614. }
  615. else
  616. {
  617. return false;
  618. }
  619. }
  620. }
  621. private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
  622. {
  623. // Reference
  624. // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
  625. try
  626. {
  627. var subkey = Environment.Is64BitProcess
  628. ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x64"
  629. : "SOFTWARE\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x86";
  630. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
  631. .OpenSubKey(subkey))
  632. {
  633. if (ndpKey != null && ndpKey.GetValue("Version") != null)
  634. {
  635. var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
  636. if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase))
  637. {
  638. return;
  639. }
  640. }
  641. }
  642. }
  643. catch (Exception ex)
  644. {
  645. logger.ErrorException("Error getting .NET Framework version", ex);
  646. return;
  647. }
  648. try
  649. {
  650. await InstallVcredist2013().ConfigureAwait(false);
  651. }
  652. catch (Exception ex)
  653. {
  654. logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
  655. }
  656. }
  657. private async static Task InstallVcredist2013()
  658. {
  659. var httpClient = _appHost.HttpClient;
  660. var tmp = await httpClient.GetTempFile(new HttpRequestOptions
  661. {
  662. Url = GetVcredist2013Url(),
  663. Progress = new Progress<double>()
  664. }).ConfigureAwait(false);
  665. var exePath = Path.ChangeExtension(tmp, ".exe");
  666. File.Copy(tmp, exePath);
  667. var startInfo = new ProcessStartInfo
  668. {
  669. FileName = exePath,
  670. CreateNoWindow = true,
  671. WindowStyle = ProcessWindowStyle.Hidden,
  672. Verb = "runas",
  673. ErrorDialog = false
  674. };
  675. _logger.Info("Running {0}", startInfo.FileName);
  676. using (var process = Process.Start(startInfo))
  677. {
  678. process.WaitForExit();
  679. }
  680. }
  681. private static string GetVcredist2013Url()
  682. {
  683. if (Environment.Is64BitProcess)
  684. {
  685. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe";
  686. }
  687. // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe
  688. return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe";
  689. }
  690. /// <summary>
  691. /// Sets the error mode.
  692. /// </summary>
  693. /// <param name="uMode">The u mode.</param>
  694. /// <returns>ErrorModes.</returns>
  695. [DllImport("kernel32.dll")]
  696. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  697. /// <summary>
  698. /// Enum ErrorModes
  699. /// </summary>
  700. [Flags]
  701. public enum ErrorModes : uint
  702. {
  703. /// <summary>
  704. /// The SYSTE m_ DEFAULT
  705. /// </summary>
  706. SYSTEM_DEFAULT = 0x0,
  707. /// <summary>
  708. /// The SE m_ FAILCRITICALERRORS
  709. /// </summary>
  710. SEM_FAILCRITICALERRORS = 0x0001,
  711. /// <summary>
  712. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  713. /// </summary>
  714. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  715. /// <summary>
  716. /// The SE m_ NOGPFAULTERRORBOX
  717. /// </summary>
  718. SEM_NOGPFAULTERRORBOX = 0x0002,
  719. /// <summary>
  720. /// The SE m_ NOOPENFILEERRORBOX
  721. /// </summary>
  722. SEM_NOOPENFILEERRORBOX = 0x8000
  723. }
  724. }
  725. }