MainStartup.cs 29 KB

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