MainStartup.cs 29 KB

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