MainStartup.cs 29 KB

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