MainStartup.cs 26 KB

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