MainStartup.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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.Text;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using System.Windows.Forms;
  22. using CommonIO.Windows;
  23. using ImageMagickSharp;
  24. using MediaBrowser.Common.Net;
  25. using MediaBrowser.Server.Implementations.Logging;
  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(20000))
  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(new PatternsLogger(logManager.GetLogger("FileSystem")));
  268. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  269. //fileSystem.AddShortcutHandler(new LnkShortcutHandler(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. "emby.windows.zip",
  279. nativeApp);
  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. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  301. 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. }