MainStartup.cs 27 KB

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