How to use TempDirectory class of PuppeteerSharp.Helpers package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Helpers.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

...69 [PuppeteerTest("headful.spec.ts", "HEADFUL", "headless should be able to read cookies written by headful")]70 [PuppeteerFact(Skip = "Puppeteer ignores this in windows we do not have a platform filter yet")]71 public async Task HeadlessShouldBeAbleToReadCookiesWrittenByHeadful()72 {73 using (var userDataDir = new TempDirectory())74 {75 var launcher = new Launcher(TestConstants.LoggerFactory);76 var options = TestConstants.DefaultBrowserOptions();77 options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();78 options.Headless = false;79 await using (var browser = await launcher.LaunchAsync(options))80 await using (var page = await browser.NewPageAsync())81 {82 await page.GoToAsync(TestConstants.EmptyPage);83 await page.EvaluateExpressionAsync(84 "document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");85 }86 await TestUtils.WaitForCookieInChromiumFileAsync(userDataDir.Path, "foo");87 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.Helpers;2using System;3using System.IO;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 var tempDirectory = new TempDirectory();10 var options = new LaunchOptions { Headless = true, UserDataDir = tempDirectory.Path };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync(Path.Combine(tempDirectory.Path, "google.png"));15 }16 }17 }18}19var options = new LaunchOptions { Headless = true, UserDataDir = "C:\\Users\\me\\Desktop\\Temp" };20var options = new LaunchOptions { Headless = true, UserDataDir = "C:\\Users\\me\\Desktop\\Temp\\1" };21var options = new LaunchOptions { Headless = true, UserDataDir = "C:\\Users\\me\\Desktop\\Temp\\2" };22var options = new LaunchOptions { Headless = true, UserDataDir = "C:\\Users\\me\\Desktop\\Temp\\3" };23var options = new LaunchOptions { Headless = true, UserDataDir = "C:\\Users\\me\\Desktop\\Temp\\4" };24var options = new LaunchOptions { Headless = true, UserDataDir = "C:\\Users\\me\\Desktop\\Temp\\5" };25var options = new LaunchOptions { Headless = true,

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1var tempDir = new TempDirectory();2{3 Args = new string[] { "--no-sandbox" },4 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",5};6var browser = await Puppeteer.LaunchAsync(options);7var page = await browser.NewPageAsync();8await page.ScreenshotAsync("google.png");9await browser.CloseAsync();10tempDir.Dispose();11var tempDir = new TempDirectory();12{13 Args = new string[] { "--no-sandbox" },14 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",15};16var browser = await Puppeteer.LaunchAsync(options);17var page = await browser.NewPageAsync();18await page.ScreenshotAsync("google.png");19await browser.CloseAsync();20tempDir.Dispose();21var tempDir = new TempDirectory();22{23 Args = new string[] { "--no-sandbox" },24 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",25};26var browser = await Puppeteer.LaunchAsync(options);27var page = await browser.NewPageAsync();28await page.ScreenshotAsync("google.png");29await browser.CloseAsync();30tempDir.Dispose();31var tempDir = new TempDirectory();32{33 Args = new string[] { "--no-sandbox" },34 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1var tempDir = new TempDirectory();2var options = new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } };3var browser = await Puppeteer.LaunchAsync(options);4var page = await browser.NewPageAsync();5await page.ScreenshotAsync(Path.Combine(tempDir.Path, "google.png"));6await browser.CloseAsync();7tempDir.Dispose();8var tempDir = new TempDirectory();9var options = new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } };10var browser = await Puppeteer.LaunchAsync(options);11var page = await browser.NewPageAsync();12await page.ScreenshotAsync(Path.Combine(tempDir.Path, "google.png"));13await browser.CloseAsync();14tempDir.Dispose();15var tempDir = new TempDirectory();16var options = new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } };17var browser = await Puppeteer.LaunchAsync(options);18var page = await browser.NewPageAsync();19await page.ScreenshotAsync(Path.Combine(tempDir.Path, "google.png"));20await browser.CloseAsync();21tempDir.Dispose();22var tempDir = new TempDirectory();23var options = new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } };24var browser = await Puppeteer.LaunchAsync(options);25var page = await browser.NewPageAsync();26await page.ScreenshotAsync(Path.Combine(tempDir.Path, "google.png"));27await browser.CloseAsync();28tempDir.Dispose();29var tempDir = new TempDirectory();30var options = new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } };31var browser = await Puppeteer.LaunchAsync(options);32var page = await browser.NewPageAsync();

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1var tempDirectory = new TempDirectory();2var browser = await Puppeteer.LaunchAsync(new LaunchOptions3{4 Args = new string[] { $"--user-data-dir={tempDirectory.Path}" }5});6var tempDirectory = new TempDirectory();7var browser = await Puppeteer.LaunchAsync(new LaunchOptions8{9 Args = new string[] { $"--user-data-dir={tempDirectory.Path}" }10});11var firstFive = mylist.Take(5);12var firstItem = mylist.FirstOrDefault();13The type 'System.Linq.Enumerable+WhereSelectArrayIterator' cannot be used as type parameter 'TSource' in the generic type or method 'System.Linq.Enumerable.FirstOrDefault<TSource>(System.Collections

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp.Helpers;4{5 {6 static void Main(string[] args)7 {8 var task = MainAsync(args);9 task.Wait();10 }11 static async Task MainAsync(string[] args)12 {13 var tempDirectory = new TempDirectory();14 var browser = await Puppeteer.LaunchAsync(new LaunchOptions15 {16 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",17 Args = new string[] { "--remote-debugging-port=9222" },18 });19 var page = await browser.NewPageAsync();20 await page.ScreenshotAsync("screenshot.png");21 await browser.CloseAsync();22 tempDirectory.Dispose();23 }24 }25}

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Helpers;2using System;3using System.IO;4{5 {6 static void Main(string[] args)7 {8 var tempDirectory = new TempDirectory();9 var tempPath = tempDirectory.Path;10 Console.WriteLine($"Path of temp directory: {tempPath}");11 var tempFile = Path.Combine(tempPath, "temp.txt");12 File.WriteAllText(tempFile, "Hello World");13 Console.WriteLine($"Path of temp file: {tempFile}");14 Console.WriteLine($"Content of temp file: {File.ReadAllText(tempFile)}");15 tempDirectory.Dispose();16 Console.WriteLine($"Path of temp directory: {tempPath}");17 Console.WriteLine($"Path of temp file: {tempFile}");18 Console.ReadKey();19 }20 }21}

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1var tempDirectory = new TempDirectory();2{3 Args = new string[] { $"--user-data-dir={tempDirectory.Path}" }4};5var browser = await Puppeteer.LaunchAsync(options);6var page = await browser.NewPageAsync();7var tempDirectory = new TempDirectory();8{9 Args = new string[] { $"--user-data-dir={tempDirectory.Path}" }10};11var browser = await Puppeteer.LaunchAsync(options);12var page = await browser.NewPageAsync();13var tempDirectory = new TempDirectory();14{15 Args = new string[] { $"--user-data-dir={tempDirectory.Path}" }16};17var browser = await Puppeteer.LaunchAsync(options);18var page = await browser.NewPageAsync();19var tempDirectory = new TempDirectory();20{21 Args = new string[] { $"--user-data-dir={tempDirectory.Path}" }22};23var browser = await Puppeteer.LaunchAsync(options);24var page = await browser.NewPageAsync();25var tempDirectory = new TempDirectory();26{27 Args = new string[] { $"--user-data-dir={tempDirectory.Path}" }28};29var browser = await Puppeteer.LaunchAsync(options);30var page = await browser.NewPageAsync();31var tempDirectory = new TempDirectory();32{33 Args = new string[] { $"--user-data-dir={tempDirectory.Path}" }34};35var browser = await Puppeteer.LaunchAsync(options);36var page = await browser.NewPageAsync();

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1var tempDirectory = new TempDirectory();2string tempDirPath = tempDirectory.Path;3var tempDirectory = new TempDirectory();4string tempDirPath = tempDirectory.Path;5var tempDirectory = new TempDirectory();6string tempDirPath = tempDirectory.Path;7var tempDirectory = new TempDirectory();8string tempDirPath = tempDirectory.Path;9var tempDirectory = new TempDirectory();10string tempDirPath = tempDirectory.Path;11var tempDirectory = new TempDirectory();12string tempDirPath = tempDirectory.Path;13var tempDirectory = new TempDirectory();14string tempDirPath = tempDirectory.Path;15var tempDirectory = new TempDirectory();16string tempDirPath = tempDirectory.Path;17var tempDirectory = new TempDirectory();18string tempDirPath = tempDirectory.Path;19var tempDirectory = new TempDirectory();20string tempDirPath = tempDirectory.Path;21var tempDirectory = new TempDirectory();22string tempDirPath = tempDirectory.Path;23var tempDirectory = new TempDirectory();24string tempDirPath = tempDirectory.Path;25var tempDirectory = new TempDirectory();26string tempDirPath = tempDirectory.Path;

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Helpers;2using System;3using System.IO;4{5 {6 static void Main(string[] args)7 {8 var tempDir = new TempDirectory();9 var tempFile = Path.Combine(tempDir.Path, "temp.txt");10 File.WriteAllText(tempFile, "Hello world!");11 var text = File.ReadAllText(tempFile);12 Console.WriteLine(text);13 tempDir.Dispose();14 }15 }16}17using System;18using System.IO;19{20 {21 static void Main(string[] args)22 {23 var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());24 Directory.CreateDirectory(tempDir);25 var tempFile = Path.Combine(tempDir, "temp.txt");26 File.WriteAllText(tempFile, "Hello world!");27 var text = File.ReadAllText(tempFile);28 Console.WriteLine(text);29 Directory.Delete(tempDir, true);30 }31 }32}33using System;34using System.IO;35{36 {37 static void Main(string[] args)38 {39 var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());40 Directory.CreateDirectory(tempDir);41 var tempFile = Path.Combine(tempDir, "temp.txt");42 File.WriteAllText(tempFile, "Hello world!");43 var text = File.ReadAllText(tempFile);44 Console.WriteLine(text);45 Directory.Delete(tempDir, true);46 }47 }48}49using System;50using System.IO;51{52 {53 static void Main(string[] args)54 {55 var tempDir = Path.Combine(Path.GetTempPath(),

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 methods 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