How to use TempDirectory method of PuppeteerSharp.Helpers.TempDirectory class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Helpers.TempDirectory.TempDirectory

ChromiumProcess.cs

Source:ChromiumProcess.cs Github

copy

Full Screen

...45 private static int _processCount;46 #endregion47 #region Instance fields48 private readonly LaunchOptions _options;49 private readonly TempDirectory _tempUserDataDir;50 private readonly ILogger _logger;51 private readonly TaskCompletionSource<string> _startCompletionSource = new TaskCompletionSource<string>();52 private readonly TaskCompletionSource<bool> _exitCompletionSource = new TaskCompletionSource<bool>();53 private State _currentState = State.Initial;54 #endregion55 #region Constructor56 /// <summary>57 /// Creates a new <see cref="ChromiumProcess"/> instance.58 /// </summary>59 /// <param name="chromiumExecutable">Full path of Chromium executable.</param>60 /// <param name="options">Options for launching Chromium.</param>61 /// <param name="loggerFactory">Logger factory</param>62 public ChromiumProcess(string chromiumExecutable, LaunchOptions options, ILoggerFactory loggerFactory)63 {64 _options = options;65 _logger = options.LogProcess66 ? loggerFactory.CreateLogger<ChromiumProcess>()67 : null;68 List<string> chromiumArgs;69 (chromiumArgs, _tempUserDataDir) = PrepareChromiumArgs(options);70 Process = new Process71 {72 EnableRaisingEvents = true73 };74 Process.StartInfo.UseShellExecute = false;75 Process.StartInfo.FileName = chromiumExecutable;76 Process.StartInfo.Arguments = string.Join(" ", chromiumArgs);77 Process.StartInfo.RedirectStandardError = true;78 SetEnvVariables(Process.StartInfo.Environment, options.Env, Environment.GetEnvironmentVariables());79 if (options.DumpIO)80 {81 Process.ErrorDataReceived += (sender, e) => Console.Error.WriteLine(e.Data);82 }83 }84 #endregion85 #region Dispose86 /// <summary>87 /// Finalizer.88 /// </summary>89 ~ChromiumProcess()90 {91 Dispose(false);92 }93 /// <inheritdoc />94 public void Dispose()95 {96 GC.SuppressFinalize(this);97 Dispose(true);98 }99 /// <summary>100 /// Disposes Chromium process and any temporary user directory.101 /// </summary>102 /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>103 protected virtual void Dispose(bool disposing) => _currentState.Dispose(this);104 #endregion105 #region Properties106 /// <summary>107 /// Gets Chromium process details.108 /// </summary>109 public Process Process { get; }110 /// <summary>111 /// Gets Chromium endpoint.112 /// </summary>113 public string EndPoint => _startCompletionSource.Task.IsCompleted114 ? _startCompletionSource.Task.Result115 : null;116 /// <summary>117 /// Indicates whether Chromium process is exiting. 118 /// </summary>119 public bool IsExiting => _currentState.IsExiting;120 /// <summary>121 /// Indicates whether Chromium process has exited. 122 /// </summary>123 public bool HasExited => _currentState.IsExited;124 #endregion125 #region Public methods126 /// <summary>127 /// Asynchronously starts Chromium process.128 /// </summary>129 /// <returns></returns>130 public Task StartAsync() => _currentState.StartAsync(this);131 /// <summary>132 /// Asynchronously waits for graceful Chromium process exit within a given timeout period.133 /// Kills the Chromium process if it has not exited within this period.134 /// </summary>135 /// <param name="timeout">The maximum waiting time for a graceful process exit.</param>136 /// <returns></returns>137 public Task EnsureExitAsync(TimeSpan? timeout) => timeout.HasValue138 ? _currentState.ExitAsync(this, timeout.Value)139 : _currentState.KillAsync(this);140 /// <summary>141 /// Asynchronously kills Chromium process.142 /// </summary>143 /// <returns></returns>144 public Task KillAsync() => _currentState.KillAsync(this);145 /// <summary>146 /// Waits for Chromium process exit within a given timeout.147 /// </summary>148 /// <param name="timeout">The maximum wait period.</param>149 /// <returns><c>true</c> if Chromium process has exited within the given <paramref name="timeout"/>,150 /// or <c>false</c> otherwise.</returns>151 public async Task<bool> WaitForExitAsync(TimeSpan? timeout)152 {153 if (timeout.HasValue)154 {155 var completedTask = await Task.WhenAny(_exitCompletionSource.Task, Task.Delay(timeout.Value)).ConfigureAwait(false);156 return completedTask == _exitCompletionSource.Task;157 }158 await _exitCompletionSource.Task.ConfigureAwait(false);159 return true;160 }161 /// <inheritdoc />162 public override string ToString() => $"Chromium process; EndPoint={EndPoint}; State={_currentState}";163 #endregion164 #region Private methods165 private static (List<string> chromiumArgs, TempDirectory tempUserDataDir) PrepareChromiumArgs(LaunchOptions options)166 {167 var chromiumArgs = new List<string>();168 if (!options.IgnoreDefaultArgs)169 {170 chromiumArgs.AddRange(GetDefaultArgs(options));171 }172 else if (options.IgnoredDefaultArgs?.Length > 0)173 {174 chromiumArgs.AddRange(GetDefaultArgs(options).Except(options.IgnoredDefaultArgs));175 }176 else177 {178 chromiumArgs.AddRange(options.Args);179 }180 TempDirectory tempUserDataDir = null;181 if (!chromiumArgs.Any(argument => argument.StartsWith("--remote-debugging-", StringComparison.Ordinal)))182 {183 chromiumArgs.Add("--remote-debugging-port=0");184 }185 var userDataDirOption = chromiumArgs.FirstOrDefault(i => i.StartsWith(UserDataDirArgument, StringComparison.Ordinal));186 if (string.IsNullOrEmpty(userDataDirOption))187 {188 tempUserDataDir = new TempDirectory();189 chromiumArgs.Add($"{UserDataDirArgument}={tempUserDataDir.Path.Quote()}");190 }191 return (chromiumArgs, tempUserDataDir);192 }193 internal static string[] GetDefaultArgs(LaunchOptions options)194 {195 var chromeArguments = new List<string>(DefaultArgs);196 if (!string.IsNullOrEmpty(options.UserDataDir))197 {198 chromeArguments.Add($"{UserDataDirArgument}={options.UserDataDir.Quote()}");199 }200 if (options.Devtools)201 {202 chromeArguments.Add("--auto-open-devtools-for-tabs");...

Full Screen

Full Screen

Launcher.cs

Source:Launcher.cs Github

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Threading.Tasks;4using PuppeteerSharp.Helpers;5using System.Linq;6using System.IO;7using System.Diagnostics;8using System.Text.RegularExpressions;9using System.Threading;10using System.Collections;11using Microsoft.Extensions.Logging;12namespace PuppeteerSharp13{14 /// <summary>15 /// Launcher controls the creation of Chromium processes or the connection remote ones.16 /// </summary>17 public class Launcher18 {19 #region Constants20 internal static readonly string[] DefaultArgs = {21 "--disable-background-networking",22 "--disable-background-timer-throttling",23 "--disable-client-side-phishing-detection",24 "--disable-default-apps",25 "--disable-extensions",26 "--disable-hang-monitor",27 "--disable-popup-blocking",28 "--disable-prompt-on-repost",29 "--disable-sync",30 "--disable-translate",31 "--metrics-recording-only",32 "--no-first-run",33 "--remote-debugging-port=0",34 "--safebrowsing-disable-auto-update"35 };36 internal static readonly string[] AutomationArgs = {37 "--enable-automation",38 "--password-store=basic",39 "--use-mock-keychain"40 };41 private const string UserDataDirArgument = "--user-data-dir";42 #endregion43 #region Private members44 private static int _processCount;45 private readonly ILoggerFactory _loggerFactory;46 private readonly ILogger _logger;47 private Process _chromeProcess;48 private string _temporaryUserDataDir;49 private Connection _connection;50 private Timer _timer;51 private LaunchOptions _options;52 private TaskCompletionSource<bool> _waitForChromeToClose;53 private bool _processLoaded;54 private bool _chromiumLaunched;55 #endregion56 #region Properties57 /// <summary>58 /// Gets or sets a value indicating whether the process created by the instance is closed.59 /// </summary>60 /// <value><c>true</c> if is the process is closed; otherwise, <c>false</c>.</value>61 public bool IsChromeClosed { get; internal set; }62 #endregion63 /// <summary>64 /// Initializes a new instance of the <see cref="Launcher"/> class.65 /// </summary>66 /// <param name="loggerFactory">Logger factory.</param>67 public Launcher(ILoggerFactory loggerFactory = null)68 {69 _loggerFactory = loggerFactory ?? new LoggerFactory();70 _logger = _loggerFactory.CreateLogger<Launcher>();71 _waitForChromeToClose = new TaskCompletionSource<bool>();72 }73 #region Public methods74 /// <summary>75 /// The method launches a browser instance with given arguments. The browser will be closed when the Browser is disposed.76 /// </summary>77 /// <param name="options">Options for launching Chrome</param>78 /// <param name="chromiumRevision">The revision of Chrome to launch.</param>79 /// <returns>A connected browser.</returns>80 /// <remarks>81 /// See <a href="https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/">this article</a>82 /// for a description of the differences between Chromium and Chrome.83 /// <a href="https://chromium.googlesource.com/chromium/src/+/lkcr/docs/chromium_browser_vs_google_chrome.md">This article</a> describes some differences for Linux users.84 /// </remarks>85 public async Task<Browser> LaunchAsync(LaunchOptions options, int chromiumRevision)86 {87 if (_chromiumLaunched)88 {89 throw new InvalidOperationException("Unable to create or connect to another chromium process");90 }91 _chromiumLaunched = true;92 var chromeArguments = InitChromeArgument(options);93 var chromeExecutable = options.ExecutablePath;94 if (string.IsNullOrEmpty(chromeExecutable))95 {96 var downloader = Downloader.CreateDefault();97 var revisionInfo = downloader.RevisionInfo(Downloader.CurrentPlatform, chromiumRevision);98 chromeExecutable = revisionInfo.ExecutablePath;99 }100 if (!File.Exists(chromeExecutable))101 {102 throw new FileNotFoundException("Failed to launch chrome! path to executable does not exist", chromeExecutable);103 }104 CreateChromeProcess(options, chromeArguments, chromeExecutable);105 try106 {107 var connectionDelay = options.SlowMo;108 var browserWSEndpoint = await WaitForEndpoint(_chromeProcess, options.Timeout, options.DumpIO);109 var keepAliveInterval = options.KeepAliveInterval;110 _connection = await Connection.Create(browserWSEndpoint, connectionDelay, keepAliveInterval, _loggerFactory);111 _processLoaded = true;112 if (options.LogProcess)113 {114 _logger.LogInformation("Process Count: {ProcessCount}", Interlocked.Increment(ref _processCount));115 }116 return await Browser.CreateAsync(_connection, options, _chromeProcess, KillChrome);117 }118 catch (Exception ex)119 {120 ForceKillChrome();121 throw new ChromeProcessException("Failed to create connection", ex);122 }123 }124 /// <summary>125 /// Attaches Puppeteer to an existing Chromium instance. The browser will be closed when the Browser is disposed.126 /// </summary>127 /// <param name="options">Options for connecting.</param>128 /// <returns>A connected browser.</returns>129 public async Task<Browser> ConnectAsync(ConnectOptions options)130 {131 try132 {133 if (_chromiumLaunched)134 {135 throw new InvalidOperationException("Unable to create or connect to another chromium process");136 }137 _chromiumLaunched = true;138 var connectionDelay = options.SlowMo;139 var keepAliveInterval = options.KeepAliveInterval;140 _connection = await Connection.Create(options.BrowserWSEndpoint, connectionDelay, keepAliveInterval, _loggerFactory);141 return await Browser.CreateAsync(_connection, options, null, () =>142 {143 var closeTask = _connection.SendAsync("Browser.close", null);144 return null;145 });146 }147 catch (Exception ex)148 {149 throw new Exception("Failed to create connection", ex);150 }151 }152 /// <summary>153 /// Tries the delete user data dir.154 /// </summary>155 /// <returns>The task.</returns>156 /// <param name="times">How many times it should try to delete the folder</param>157 /// <param name="delay">Time to wait between tries.</param>158 public async Task TryDeleteUserDataDir(int times = 10, TimeSpan? delay = null)159 {160 if (!IsChromeClosed)161 {162 throw new InvalidOperationException("Unable to delete user data dir, Chorme is still open");163 }164 if (times <= 0)165 {166 throw new ArgumentOutOfRangeException(nameof(times));167 }168 if (delay == null)169 {170 delay = new TimeSpan(0, 0, 0, 0, 100);171 }172 string folder = string.IsNullOrEmpty(_temporaryUserDataDir) ? _options.UserDataDir : _temporaryUserDataDir;173 int attempts = 0;174 while (true)175 {176 try177 {178 attempts++;179 Directory.Delete(folder, true);180 break;181 }182 catch (UnauthorizedAccessException)183 {184 if (attempts == times)185 {186 throw;187 }188 await Task.Delay(delay.Value);189 }190 }191 }192 /// <summary>193 /// Gets the executable path.194 /// </summary>195 /// <returns>The executable path.</returns>196 public static string GetExecutablePath()197 {198 var downloader = Downloader.CreateDefault();199 var revisionInfo = downloader.RevisionInfo(Downloader.CurrentPlatform, Downloader.DefaultRevision);200 return revisionInfo.ExecutablePath;201 }202 /// <summary>203 /// Gets a temporary directory using <see cref="Path.GetTempPath"/> and <see cref="Path.GetRandomFileName"/>.204 /// </summary>205 /// <returns>A temporary directory.</returns>206 public static string GetTemporaryDirectory()207 {208 string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());209 Directory.CreateDirectory(tempDirectory);210 return tempDirectory;211 }212 #endregion213 #region Private methods214 private void CreateChromeProcess(LaunchOptions options, List<string> chromeArguments, string chromeExecutable)215 {216 _chromeProcess = new Process();217 _chromeProcess.EnableRaisingEvents = true;218 _chromeProcess.StartInfo.UseShellExecute = false;219 _chromeProcess.StartInfo.FileName = chromeExecutable;220 _chromeProcess.StartInfo.Arguments = string.Join(" ", chromeArguments);221 SetEnvVariables(_chromeProcess.StartInfo.Environment, options.Env, Environment.GetEnvironmentVariables());222 if (!options.DumpIO)223 {224 _chromeProcess.StartInfo.RedirectStandardOutput = false;225 _chromeProcess.StartInfo.RedirectStandardError = false;226 }227 _chromeProcess.Exited += async (sender, e) =>228 {229 await AfterProcessExit();230 };231 }232 private List<string> InitChromeArgument(LaunchOptions options)233 {234 var chromeArguments = new List<string>(DefaultArgs);235 _options = options;236 if (options.AppMode)237 {238 options.Headless = false;239 }240 else241 {242 chromeArguments.AddRange(AutomationArgs);243 }244 var userDataDirOption = options.Args.FirstOrDefault(i => i.StartsWith(UserDataDirArgument, StringComparison.Ordinal));245 if (string.IsNullOrEmpty(userDataDirOption))246 {247 if (string.IsNullOrEmpty(options.UserDataDir))248 {249 _temporaryUserDataDir = GetTemporaryDirectory();250 chromeArguments.Add($"{UserDataDirArgument}={_temporaryUserDataDir}");251 }252 else253 {254 chromeArguments.Add($"{UserDataDirArgument}={options.UserDataDir}");255 }256 }257 else258 {259 _options.UserDataDir = userDataDirOption.Replace($"{UserDataDirArgument}=", string.Empty);260 }261 if (options.Devtools)262 {263 chromeArguments.Add("--auto-open-devtools-for-tabs");264 options.Headless = false;265 }266 if (options.Headless)267 {268 chromeArguments.AddRange(new[]{269 "--headless",270 "--disable-gpu",271 "--hide-scrollbars",272 "--mute-audio"273 });274 }275 if (options.Args.Any())276 {277 chromeArguments.AddRange(options.Args);278 }279 return chromeArguments;280 }281 private Task<string> WaitForEndpoint(Process chromeProcess, int timeout, bool dumpio)282 {283 var taskWrapper = new TaskCompletionSource<string>();284 var output = string.Empty;285 chromeProcess.StartInfo.RedirectStandardOutput = true;286 chromeProcess.StartInfo.RedirectStandardError = true;287 void exitedEvent(object sender, EventArgs e)288 {289 if (_options.LogProcess && !_processLoaded)290 {291 _logger.LogInformation("Process Count: {ProcessCount}", Interlocked.Increment(ref _processCount));292 }293 CleanUp();294 taskWrapper.SetException(new ChromeProcessException($"Failed to launch chrome! {output}"));295 }296 chromeProcess.ErrorDataReceived += (sender, e) =>297 {298 if (e.Data != null)299 {300 output += e.Data + "\n";301 var match = Regex.Match(e.Data, "^DevTools listening on (ws:\\/\\/.*)");302 if (!match.Success)303 {304 return;305 }306 CleanUp();307 chromeProcess.Exited -= exitedEvent;308 taskWrapper.SetResult(match.Groups[1].Value);309 //Restore defaults for Redirects310 if (!dumpio)311 {312 chromeProcess.StartInfo.RedirectStandardOutput = false;313 chromeProcess.StartInfo.RedirectStandardError = false;314 }315 }316 };317 chromeProcess.Exited += exitedEvent;318 if (timeout > 0)319 {320 //We have to declare timer before initializing it because if we don't do this 321 //we can't dispose it in the action created in the constructor322 _timer = new Timer((state) =>323 {324 taskWrapper.SetException(325 new ChromeProcessException($"Timed out after {timeout} ms while trying to connect to Chrome! "));326 _timer.Dispose();327 }, null, timeout, 0);328 }329 chromeProcess.Start();330 chromeProcess.BeginErrorReadLine();331 return taskWrapper.Task;332 }333 private void CleanUp()334 {335 _timer?.Dispose();336 _timer = null;337 _chromeProcess?.RemoveExitedEvent();338 }339 private async Task AfterProcessExit()340 {341 if (IsChromeClosed)342 {343 return;344 }345 if (_options.LogProcess)346 {347 _logger.LogInformation("Process Count: {ProcessCount}", Interlocked.Decrement(ref _processCount));348 }349 IsChromeClosed = true;350 if (_temporaryUserDataDir != null)351 {352 await TryDeleteUserDataDir();353 }354 if (_waitForChromeToClose.Task.Status != TaskStatus.RanToCompletion)355 {356 _waitForChromeToClose.SetResult(true);357 }358 }359 private async Task KillChrome()360 {361 if (!string.IsNullOrEmpty(_temporaryUserDataDir))362 {363 ForceKillChrome();364 }365 else if (_connection != null)366 {367 await _connection.SendAsync("Browser.close", null);368 }369 await _waitForChromeToClose.Task;370 }371 private void ForceKillChrome()372 {373 try374 {375 if (_chromeProcess.Id != 0 && !_chromeProcess.HasExited && Process.GetProcessById(_chromeProcess.Id) != null)376 {377 _chromeProcess.Kill();378 _chromeProcess.WaitForExit();379 }380 }381 catch (InvalidOperationException ex) when (ex.Message == "No process is associated with this object.")382 {383 // swallow384 }385 }386 private static void SetEnvVariables(IDictionary<string, string> environment, IDictionary<string, string> customEnv,387 IDictionary realEnv)388 {389 foreach (DictionaryEntry item in realEnv)390 {391 environment[item.Key.ToString()] = item.Value.ToString();392 }393 if (customEnv != null)394 {395 foreach (var item in customEnv)396 {397 environment[item.Key] = item.Value;398 }399 }400 }401 #endregion402 }403}...

Full Screen

Full Screen

PuppeteerLaunchTests.cs

Source:PuppeteerLaunchTests.cs Github

copy

Full Screen

...71 }72 [Fact]73 public async Task UserDataDirOption()74 {75 using (var userDataDir = new TempDirectory())76 {77 var options = TestConstants.DefaultBrowserOptions();78 options.UserDataDir = userDataDir.Path;79 var launcher = new Launcher(TestConstants.LoggerFactory);80 using (var browser = await launcher.LaunchAsync(options))81 {82 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);83 await browser.CloseAsync();84 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);85 }86 }87 }88 [Fact]89 public async Task UserDataDirArgument()90 {91 using (var userDataDir = new TempDirectory())92 {93 var launcher = new Launcher(TestConstants.LoggerFactory);94 var options = TestConstants.DefaultBrowserOptions();95 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();96 using (var browser = await launcher.LaunchAsync(options))97 {98 // Open a page to make sure its functional.99 await browser.NewPageAsync();100 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);101 await browser.CloseAsync();102 Assert.True(Directory.GetFiles(userDataDir.Path).Length > 0);103 }104 }105 }106 [Fact]107 public async Task UserDataDirOptionShouldRestoreState()108 {109 using (var userDataDir = new TempDirectory())110 {111 var launcher = new Launcher(TestConstants.LoggerFactory);112 var options = TestConstants.DefaultBrowserOptions();113 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();114 using (var browser = await launcher.LaunchAsync(options))115 {116 var page = await browser.NewPageAsync();117 await page.GoToAsync(TestConstants.EmptyPage);118 await page.EvaluateExpressionAsync("localStorage.hey = 'hello'");119 }120 using (var browser2 = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))121 {122 var page2 = await browser2.NewPageAsync();123 await page2.GoToAsync(TestConstants.EmptyPage);124 Assert.Equal("hello", await page2.EvaluateExpressionAsync<string>("localStorage.hey"));125 }126 }127 }128 [Fact(Skip = "This mysteriously fails on Windows on AppVeyor.")]129 public async Task UserDataDirOptionShouldRestoreCookies()130 {131 using (var userDataDir = new TempDirectory())132 {133 var launcher = new Launcher(TestConstants.LoggerFactory);134 var options = TestConstants.DefaultBrowserOptions();135 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();136 using (var browser = await launcher.LaunchAsync(options))137 {138 var page = await browser.NewPageAsync();139 await page.GoToAsync(TestConstants.EmptyPage);140 await page.EvaluateExpressionAsync(141 "document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");142 }143 await TestUtils.WaitForCookieInChromiumFileAsync(userDataDir.Path, "doSomethingOnlyOnce");144 using (var browser2 = await Puppeteer.LaunchAsync(options, TestConstants.LoggerFactory))145 {...

Full Screen

Full Screen

FirefoxLauncher.cs

Source:FirefoxLauncher.cs Github

copy

Full Screen

...31 Process.StartInfo.Arguments = string.Join(" ", firefoxArgs);32 }33 /// <inheritdoc />34 public override string ToString() => $"Firefox process; EndPoint={EndPoint}; State={CurrentState}";35 private static (List<string> FirefoxArgs, TempDirectory TempUserDataDirectory) PrepareFirefoxArgs(LaunchOptions options)36 {37 var firefoxArgs = new List<string>();38 if (!options.IgnoreDefaultArgs)39 {40 firefoxArgs.AddRange(GetDefaultArgs(options));41 }42 else if (options.IgnoredDefaultArgs?.Length > 0)43 {44 firefoxArgs.AddRange(GetDefaultArgs(options).Except(options.IgnoredDefaultArgs));45 }46 else47 {48 firefoxArgs.AddRange(options.Args);49 }50 if (!firefoxArgs.Any(a => a.StartsWith("-remote-debugging", StringComparison.OrdinalIgnoreCase)))51 {52 firefoxArgs.Add("--remote-debugging-port=0");53 }54 TempDirectory tempUserDataDirectory = null;55 if (!firefoxArgs.Contains("-profile") && !firefoxArgs.Contains("--profile"))56 {57 tempUserDataDirectory = new TempDirectory();58 CreateProfile(tempUserDataDirectory);59 firefoxArgs.Add("--profile");60 firefoxArgs.Add($"{tempUserDataDirectory.Path.Quote()}");61 }62 return (firefoxArgs, tempUserDataDirectory);63 }64 private static void CreateProfile(TempDirectory tempUserDataDirectory)65 {66 var userJS = new List<string>();67 const string server = "dummy.test";68 var defaultPreferences = new Dictionary<string, object>69 {70 // Make sure Shield doesn"t hit the network.71 ["app.normandy.api_url"] = string.Empty,72 // Disable Firefox old build background check73 ["app.update.checkInstallTime"] = false,74 // Disable automatically upgrading Firefox75 ["app.update.disabledForTesting"] = true,76 // Increase the APZ content response timeout to 1 minute77 ["apz.content_response_timeout"] = 60000,78 // Prevent various error message on the console...

Full Screen

Full Screen

HeadfulTests.cs

Source:HeadfulTests.cs Github

copy

Full Screen

...52 }53 [Fact]54 public async Task HeadlessShouldBeAbleToReadCookiesWrittenByHeadful()55 {56 using (var userDataDir = new TempDirectory())57 {58 var launcher = new Launcher(TestConstants.LoggerFactory);59 var options = TestConstants.DefaultBrowserOptions();60 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();61 options.Headless = false;62 using (var browser = await launcher.LaunchAsync(options))63 using (var page = await browser.NewPageAsync())64 {65 await page.GoToAsync(TestConstants.EmptyPage);66 await page.EvaluateExpressionAsync(67 "document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");68 }69 await TestUtils.WaitForCookieInChromiumFileAsync(userDataDir.Path, "foo");70 options.Headless = true;...

Full Screen

Full Screen

LauncherBase.cs

Source:LauncherBase.cs Github

copy

Full Screen

...69 /// <summary>70 /// Indicates whether Base process has exited.71 /// </summary>72 public bool HasExited => _stateManager.CurrentState.IsExited;73 internal TempDirectory TempUserDataDir { get; set; }74 /// <summary>75 /// Gets Base process current state.76 /// </summary>77 internal State CurrentState => _stateManager.CurrentState;78 /// <inheritdoc />79 public void Dispose()80 {81 Dispose(true);82 GC.SuppressFinalize(this);83 }84 /// <summary>85 /// Disposes Base process and any temporary user directory.86 /// </summary>87 /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>...

Full Screen

Full Screen

ChromiumLauncher.cs

Source:ChromiumLauncher.cs Github

copy

Full Screen

...48 /// <param name="loggerFactory">Logger factory</param>49 public ChromiumLauncher(string executable, LaunchOptions options)50 : base(executable, options)51 {52 PrepareChromiumArgs(options, out List<string> chromiumArgs, out TempDirectory TempUserDataDir);53 Process.StartInfo.Arguments = string.Join(" ", chromiumArgs);54 }55 #endregion56 #region Public methods57 /// <inheritdoc />58 public override string ToString() => $"Chromium process; EndPoint={EndPoint}; State={CurrentState}";59 #endregion60 #region Private methods61 private static void PrepareChromiumArgs(LaunchOptions options, out List<string> chromiumArgs, out TempDirectory tempUserDataDirectory)62 {63 chromiumArgs = new List<string>();64 if (!options.IgnoreDefaultArgs)65 {66 chromiumArgs.AddRange(GetDefaultArgs(options));67 }68 else if (options.IgnoredDefaultArgs?.Length > 0)69 {70 chromiumArgs.AddRange(GetDefaultArgs(options).Except(options.IgnoredDefaultArgs));71 }72 else73 {74 chromiumArgs.AddRange(options.Args);75 }76 tempUserDataDirectory = null;77 if (!chromiumArgs.Any(argument => argument.StartsWith("--remote-debugging-", StringComparison.Ordinal)))78 {79 chromiumArgs.Add("--remote-debugging-port=0");80 }81 string userDataDirOption = chromiumArgs.FirstOrDefault(i => i.StartsWith(UserDataDirArgument, StringComparison.Ordinal));82 if (string.IsNullOrEmpty(userDataDirOption))83 {84 tempUserDataDirectory = new TempDirectory();85 chromiumArgs.Add($"{UserDataDirArgument}={tempUserDataDirectory.Path.Quote()}");86 }87 }88 internal static string[] GetDefaultArgs(LaunchOptions options)89 {90 var chromiumArguments = new List<string>(DefaultArgs);91 if (!string.IsNullOrEmpty(options.UserDataDir))92 {93 chromiumArguments.Add($"{UserDataDirArgument}={options.UserDataDir.Quote()}");94 }95 if (options.Devtools)96 {97 chromiumArguments.Add("--auto-open-devtools-for-tabs");98 }...

Full Screen

Full Screen

TempDirectory.cs

Source:TempDirectory.cs Github

copy

Full Screen

...7{8 /// <summary>9 /// Represents a directory that is deleted on disposal.10 /// </summary>11 internal class TempDirectory : IDisposable12 {13 private Task _deleteTask;14 public TempDirectory()15 : this(PathHelper.Combine(PathHelper.GetTempPath(), PathHelper.GetRandomFileName()))16 { }17 public TempDirectory(string path)18 {19 if (string.IsNullOrEmpty(path))20 {21 throw new ArgumentException("Path must be specified", nameof(path));22 }23 Directory.CreateDirectory(path);24 this.Path = path;25 }26 ~TempDirectory()27 {28 Dispose(false);29 }30 public string Path { get; }31 public void Dispose()32 {33 GC.SuppressFinalize(this);34 Dispose(true);35 }36 protected void Dispose(bool disposing)37 {38 if (_deleteTask == null)39 {40 _ = DeleteAsync();...

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using PuppeteerSharp.Helpers;3using System;4using System.IO;5using System.Threading.Tasks;6{7 {8 static async Task Main(string[] args)9 {10 var tempDirectory = new TempDirectory();11 {12 Args = new[] { "--no-sandbox" },13 };14 using (var browser = await Puppeteer.LaunchAsync(options))15 {16 var page = await browser.NewPageAsync();17 await page.ScreenshotAsync(Path.Combine(tempDirectory.Path, "screenshot.png"));18 }19 }20 }21}22using PuppeteerSharp;23using PuppeteerSharp.Helpers;24using System;25using System.IO;26using System.Threading.Tasks;27{28 {29 static async Task Main(string[] args)30 {31 var tempDirectory = new TempDirectory();32 {33 Args = new[] { "--no-sandbox" },34 };35 using (var browser = await Puppeteer.LaunchAsync(options))36 {37 var page = await browser.NewPageAsync();38 await page.ScreenshotAsync(Path.Combine(tempDirectory.Path, "screenshot.png"));39 }40 }41 }42}43using PuppeteerSharp;44using PuppeteerSharp.Helpers;45using System;46using System.IO;47using System.Threading.Tasks;48{49 {50 static async Task Main(string[] args)51 {52 var tempDirectory = new TempDirectory();53 {54 Args = new[] { "--no-sandbox" },55 };56 using (var browser = await Puppeteer.LaunchAsync(options))57 {58 var page = await browser.NewPageAsync();

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Helpers;2using System;3using System.IO;4{5 {6 public TempDirectory()7 {8 DirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());9 Directory.CreateDirectory(DirectoryPath);10 }11 public string DirectoryPath { get; }12 public void Dispose()13 {14 Directory.Delete(DirectoryPath, true);15 }16 }17}18using PuppeteerSharp.Helpers;19using System;20using System.IO;21{22 {23 public TempDirectory()24 {25 DirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());26 Directory.CreateDirectory(DirectoryPath);27 }28 public string DirectoryPath { get; }29 public void Dispose()30 {31 Directory.Delete(DirectoryPath, true);32 }33 }34}35using PuppeteerSharp.Helpers;36using System;37using System.IO;38{39 {40 public TempDirectory()41 {42 DirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());43 Directory.CreateDirectory(DirectoryPath);44 }45 public string DirectoryPath { get; }46 public void Dispose()47 {48 Directory.Delete(DirectoryPath, true);49 }50 }51}52using PuppeteerSharp.Helpers;53using System;54using System.IO;55{56 {57 public TempDirectory()58 {59 DirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());60 Directory.CreateDirectory(DirectoryPath);61 }62 public string DirectoryPath { get; }63 public void Dispose()64 {65 Directory.Delete(DirectoryPath, true);66 }67 }68}69using PuppeteerSharp.Helpers;70using System;71using System.IO;72{73 {74 public TempDirectory()75 {

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Helpers;2using System;3using System.IO;4{5 {6 public TempDirectory()7 {8 DirectoryPath = Path.Combine(Path.GetTempPath(), "puppeteer-sharp-" + Guid.NewGuid());9 Directory.CreateDirectory(DirectoryPath);10 }11 public string DirectoryPath { get; }12 public void Dispose()13 {14 {15 Directory.Delete(DirectoryPath, true);16 }17 catch (Exception)18 {19 }20 }21 }22}23using PuppeteerSharp.Helpers;24using System;25using System.IO;26using System.Threading.Tasks;27{28 {29 public TempDirectory()30 {31 DirectoryPath = Path.Combine(Path.GetTempPath(), "puppeteer-sharp-" + Guid.NewGuid());32 Directory.CreateDirectory(DirectoryPath);33 }34 public string DirectoryPath { get; }35 public void Dispose()36 {37 {38 Directory.Delete(DirectoryPath, true);39 }40 catch (Exception)41 {42 }43 }44 }45}46using PuppeteerSharp.Helpers;47using System;48using System.IO;49using System.Threading.Tasks;50{51 {52 public TempDirectory()53 {54 DirectoryPath = Path.Combine(Path.GetTempPath(), "puppeteer-sharp-" + Guid.NewGuid());55 Directory.CreateDirectory(DirectoryPath);56 }57 public string DirectoryPath { get; }58 public void Dispose()59 {60 {61 Directory.Delete(DirectoryPath, true);62 }63 catch (Exception)64 {65 }66 }67 }68}69using PuppeteerSharp.Helpers;70using System;71using System.IO;72using System.Threading.Tasks;73{

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Helpers;2using System;3using System.IO;4{5 {6 public TempDirectory()7 {8 Path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());9 Directory.CreateDirectory(Path);10 }11 public string Path { get; }12 public void Dispose()13 {14 Directory.Delete(Path, true);15 }16 }17}18using PuppeteerSharp.Helpers;19using System;20using System.IO;21{22 {23 public TempDirectory()24 {25 Path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());26 Directory.CreateDirectory(Path);27 }28 public string Path { get; }29 public void Dispose()30 {31 Directory.Delete(Path, true);32 }33 }34}35using PuppeteerSharp.Helpers;36using System;37using System.IO;38{39 {40 public TempDirectory()41 {42 Path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());43 Directory.CreateDirectory(Path);44 }45 public string Path { get; }46 public void Dispose()47 {48 Directory.Delete(Path, true);49 }50 }51}52using PuppeteerSharp.Helpers;53using System;54using System.IO;55{56 {57 public TempDirectory()58 {59 Path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());60 Directory.CreateDirectory(Path);61 }62 public string Path { get; }63 public void Dispose()64 {65 Directory.Delete(Path, true);66 }67 }68}69using PuppeteerSharp.Helpers;70using System;71using System.IO;72{73 {74 public TempDirectory()75 {76 Path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());77 Directory.CreateDirectory(Path);78 }

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var tempDirectory = new TempDirectory();9 {10 {11 };12 var browser = await Puppeteer.LaunchAsync(options);13 var page = await browser.NewPageAsync();14 Console.WriteLine("Press any key to exit.");15 Console.ReadKey();16 await browser.CloseAsync();17 }18 {19 tempDirectory.Dispose();20 }21 }22 }23}

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1var tempDir = new TempDirectory();2var tempDirPath = tempDir.Path;3var tempDir = new TempDirectory();4var tempFile = tempDir.CreateTempFile();5var tempDir = new TempDirectory();6var tempFile = tempDir.CreateTempFile("test");7var tempDir = new TempDirectory();8var tempFile = tempDir.CreateTempFile("test", ".txt");9var tempDir = new TempDirectory();10tempDir.Delete();11var tempDir = new TempDirectory();12tempDir.Delete(true);13var tempDir = new TempDirectory();14tempDir.Dispose();15var tempDir = new TempDirectory();16tempDir.Dispose(true);17var tempDir = TempDirectory.GetTempDirectory();18var tempDir = TempDirectory.GetTempDirectory("test");19var tempDir = TempDirectory.GetTempDirectory("test", ".txt");20var tempDir = TempDirectory.GetTempDirectory("test", ".txt", true);21var tempDir = TempDirectory.GetTempDirectory("test", ".txt", true, true);22var tempDir = TempDirectory.GetTempDirectory("test", ".txt", true, true, true);23var tempDir = TempDirectory.GetTempDirectory("test", ".txt", true, true, true, true);

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Helpers;2using System;3{4 {5 static void Main(string[] args)6 {7 var tempDir = TempDirectory.Create();8 Console.WriteLine("Temporary directory created: {0}", tempDir);9 }10 }11}

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using PuppeteerSharp.Helpers;4{5 {6 public string Path { get; }7 public TempDirectory()8 {9 Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());10 Directory.CreateDirectory(Path);11 }12 public void Dispose()13 {14 Directory.Delete(Path, true);15 }16 }17}18using System;19using System.IO;20using PuppeteerSharp.Helpers;21{22 {23 public string Path { get; }24 public TempDirectory()25 {26 Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());27 Directory.CreateDirectory(Path);28 }29 public void Dispose()30 {31 Directory.Delete(Path, true);32 }33 }34}35using System;36using System.IO;37using PuppeteerSharp.Helpers;38{39 {40 public string Path { get; }41 public TempDirectory()42 {43 Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());44 Directory.CreateDirectory(Path);45 }46 public void Dispose()47 {48 Directory.Delete(Path, true);49 }50 }51}52using System;53using System.IO;54using PuppeteerSharp.Helpers;55{56 {57 public string Path { get; }58 public TempDirectory()59 {60 Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());61 Directory.CreateDirectory(Path);62 }63 public void Dispose()64 {65 Directory.Delete(Path, true);66 }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in TempDirectory

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful