MainStartup.cs 26 KB

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