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

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

ChromiumProcess.cs

Source:ChromiumProcess.cs Github

copy

Full Screen

...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");203 }204 if (options.Headless)205 {206 chromeArguments.AddRange(new[]{207 "--headless",208 "--hide-scrollbars",209 "--mute-audio"210 });211 if (BrowserFetcher.GetCurrentPlatform() == Platform.Win32)212 {213 chromeArguments.Add("--disable-gpu");214 }215 }216 if (options.Args.All(arg => arg.StartsWith("-", StringComparison.Ordinal)))217 {218 chromeArguments.Add("about:blank");219 }220 chromeArguments.AddRange(options.Args);221 return chromeArguments.ToArray();222 }223 private static void SetEnvVariables(IDictionary<string, string> environment, IDictionary<string, string> customEnv, IDictionary realEnv)224 {225 foreach (DictionaryEntry item in realEnv)226 {227 environment[item.Key.ToString()] = item.Value.ToString();228 }229 if (customEnv != null)230 {231 foreach (var item in customEnv)232 {233 environment[item.Key] = item.Value;234 }235 }236 }237 #endregion238 #region State machine239 /// <summary>240 /// Represents state machine for Chromium process instances. The happy path runs along the241 /// following state transitions: <see cref="Initial"/>242 /// -> <see cref="Starting"/>243 /// -> <see cref="Started"/>244 /// -> <see cref="Exiting"/>245 /// -> <see cref="Exited"/>.246 /// -> <see cref="Disposed"/>.247 /// </summary>248 /// <remarks>249 /// <para>250 /// This state machine implements the following state transitions:251 /// <code>252 /// State Event Target State Action253 /// ======== =================== ============ ==========================================================254 /// Initial --StartAsync------> Starting Start process and wait for endpoint255 /// Initial --ExitAsync-------> Exited Cleanup temp user data256 /// Initial --KillAsync-------> Exited Cleanup temp user data257 /// Initial --Dispose---------> Disposed Cleanup temp user data258 /// Starting --StartAsync------> Starting -259 /// Starting --ExitAsync-------> Exiting Wait for process exit260 /// Starting --KillAsync-------> Killing Kill process261 /// Starting --Dispose---------> Disposed Kill process; Cleanup temp user data; throw ObjectDisposedException on outstanding async operations;262 /// Starting --endpoint ready--> Started Complete StartAsync successfully; Log process start263 /// Starting --process exit----> Exited Complete StartAsync with exception; Cleanup temp user data264 /// Started --StartAsync------> Started -265 /// Started --EnsureExitAsync-> Exiting Start exit timer; Log process exit266 /// Started --KillAsync-------> Killing Kill process; Log process exit267 /// Started --Dispose---------> Disposed Kill process; Log process exit; Cleanup temp user data; throw ObjectDisposedException on outstanding async operations;268 /// Started --process exit----> Exited Log process exit; Cleanup temp user data269 /// Exiting --StartAsync------> Exiting - (StartAsync throws InvalidOperationException)270 /// Exiting --ExitAsync-------> Exiting -271 /// Exiting --KillAsync-------> Killing Kill process272 /// Exiting --Dispose---------> Disposed Kill process; Cleanup temp user data; throw ObjectDisposedException on outstanding async operations;273 /// Exiting --exit timeout----> Killing Kill process274 /// Exiting --process exit----> Exited Cleanup temp user data; complete outstanding async operations;275 /// Killing --StartAsync------> Killing - (StartAsync throws InvalidOperationException)276 /// Killing --KillAsync-------> Killing -277 /// Killing --Dispose---------> Disposed Cleanup temp user data; throw ObjectDisposedException on outstanding async operations;278 /// Killing --process exit----> Exited Cleanup temp user data; complete outstanding async operations;279 /// Exited --StartAsync------> Killing - (StartAsync throws InvalidOperationException)280 /// Exited --KillAsync-------> Exited -281 /// Exited --Dispose---------> Disposed -282 /// Disposed --StartAsync------> Disposed -283 /// Disposed --KillAsync-------> Disposed -284 /// Disposed --Dispose---------> Disposed -285 /// </code>286 /// </para>287 /// </remarks>288 private abstract class State289 {290 #region Predefined states291 public static readonly State Initial = new InitialState();292 private static readonly StartingState Starting = new StartingState();293 private static readonly StartedState Started = new StartedState();294 private static readonly ExitingState Exiting = new ExitingState();295 private static readonly KillingState Killing = new KillingState();296 private static readonly ExitedState Exited = new ExitedState();297 private static readonly DisposedState Disposed = new DisposedState();298 #endregion299 #region Properties300 public bool IsExiting => this == Killing || this == Exiting;301 public bool IsExited => this == Exited || this == Disposed;302 #endregion303 #region Methods304 /// <summary>305 /// Attempts thread-safe transitions from a given state to this state.306 /// </summary>307 /// <param name="p">The Chromium process</param>308 /// <param name="fromState">The state from which state transition takes place</param>309 /// <returns>Returns <c>true</c> if transition is successful, or <c>false</c> if transition310 /// cannot be made because current state does not equal <paramref name="fromState"/>.</returns>311 protected bool TryEnter(ChromiumProcess p, State fromState)312 {313 if (Interlocked.CompareExchange(ref p._currentState, this, fromState) == fromState)314 {315 fromState.Leave(p);316 return true;317 }318 return false;319 }320 /// <summary>321 /// Notifies that state machine is about to transition to another state.322 /// </summary>323 /// <param name="p">The Chromium process</param>324 protected virtual void Leave(ChromiumProcess p)325 { }326 /// <summary>327 /// Handles process start request.328 /// </summary>329 /// <param name="p">The Chromium process</param>330 /// <returns></returns>331 public virtual Task StartAsync(ChromiumProcess p) => Task.FromException(InvalidOperation("start"));332 /// <summary>333 /// Handles process exit request.334 /// </summary>335 /// <param name="p">The Chromium process</param>336 /// <param name="timeout">The maximum waiting time for a graceful process exit.</param>337 /// <returns></returns>338 public virtual Task ExitAsync(ChromiumProcess p, TimeSpan timeout) => Task.FromException(InvalidOperation("exit"));339 /// <summary>340 /// Handles process kill request.341 /// </summary>342 /// <param name="p">The Chromium process</param>343 /// <returns></returns>344 public virtual Task KillAsync(ChromiumProcess p) => Task.FromException(InvalidOperation("kill"));345 /// <summary>346 /// Handles wait for process exit request.347 /// </summary>348 /// <param name="p">The Chromium process</param>349 /// <returns></returns>350 public virtual Task WaitForExitAsync(ChromiumProcess p) => p._exitCompletionSource.Task;351 /// <summary>352 /// Handles disposal of process and temporary user directory353 /// </summary>354 /// <param name="p"></param>355 public virtual void Dispose(ChromiumProcess p) => Disposed.EnterFrom(p, this);356 public override string ToString()357 {358 var name = GetType().Name;359 return name.Substring(0, name.Length - "State".Length);360 }361 private Exception InvalidOperation(string operationName)362 => new InvalidOperationException($"Cannot {operationName} in state {this}");363 /// <summary>364 /// Kills process if it is still alive.365 /// </summary>366 /// <param name="p"></param>367 private static void Kill(ChromiumProcess p)368 {369 try370 {371 if (!p.Process.HasExited)372 {373 p.Process.Kill();374 }375 }376 catch (InvalidOperationException)377 {378 // Ignore379 }380 }381 #endregion382 #region Concrete state classes383 private class InitialState : State384 {385 public override Task StartAsync(ChromiumProcess p) => Starting.EnterFromAsync(p, this);386 public override Task ExitAsync(ChromiumProcess p, TimeSpan timeout)387 {388 Exited.EnterFrom(p, this);389 return Task.CompletedTask;390 }391 public override Task KillAsync(ChromiumProcess p)392 {393 Exited.EnterFrom(p, this);394 return Task.CompletedTask;395 }396 public override Task WaitForExitAsync(ChromiumProcess p) => Task.FromException(InvalidOperation("wait for exit"));397 }398 private class StartingState : State399 {400 public Task EnterFromAsync(ChromiumProcess p, State fromState)401 {402 if (!TryEnter(p, fromState))403 {404 // Delegate StartAsync to current state, because it has already changed since405 // transition to this state was initiated.406 return p._currentState.StartAsync(p);407 }408 return StartCoreAsync(p);409 }410 public override Task StartAsync(ChromiumProcess p) => p._startCompletionSource.Task;411 public override Task ExitAsync(ChromiumProcess p, TimeSpan timeout) => Exiting.EnterFromAsync(p, this, timeout);412 public override Task KillAsync(ChromiumProcess p) => Killing.EnterFromAsync(p, this);413 public override void Dispose(ChromiumProcess p)414 {415 p._startCompletionSource.TrySetException(new ObjectDisposedException(p.ToString()));416 base.Dispose(p);417 }418 private async Task StartCoreAsync(ChromiumProcess p)419 {420 var output = new StringBuilder();421 void OnProcessDataReceivedWhileStarting(object sender, DataReceivedEventArgs e)422 {423 if (e.Data != null)424 {425 output.AppendLine(e.Data);426 var match = Regex.Match(e.Data, "^DevTools listening on (ws:\\/\\/.*)");427 if (match.Success)428 {429 p._startCompletionSource.SetResult(match.Groups[1].Value);430 }431 }432 }433 void OnProcessExitedWhileStarting(object sender, EventArgs e)434 {435 p._startCompletionSource.SetException(new ChromiumProcessException($"Failed to launch Chromium! {output}"));436 }437 void OnProcessExited(object sender, EventArgs e)438 {439 Exited.EnterFrom(p, p._currentState);440 }441 p.Process.ErrorDataReceived += OnProcessDataReceivedWhileStarting;442 p.Process.Exited += OnProcessExitedWhileStarting;443 p.Process.Exited += OnProcessExited;444 CancellationTokenSource cts = null;445 try446 {447 p.Process.Start();448 await Started.EnterFromAsync(p, this).ConfigureAwait(false);449 p.Process.BeginErrorReadLine();450 var timeout = p._options.Timeout;451 if (timeout > 0)452 {453 cts = new CancellationTokenSource(timeout);454 cts.Token.Register(() => p._startCompletionSource.TrySetException(455 new ChromiumProcessException($"Timed out after {timeout} ms while trying to connect to Chromium!")));456 }457 try458 {459 await p._startCompletionSource.Task.ConfigureAwait(false);460 await Started.EnterFromAsync(p, this).ConfigureAwait(false);461 }462 catch463 {464 await Killing.EnterFromAsync(p, this).ConfigureAwait(false);465 throw;466 }467 }468 finally469 {470 cts?.Dispose();471 p.Process.Exited -= OnProcessExitedWhileStarting;472 p.Process.ErrorDataReceived -= OnProcessDataReceivedWhileStarting;473 }474 }475 }476 private class StartedState : State477 {478 public Task EnterFromAsync(ChromiumProcess p, State fromState)479 {480 if (TryEnter(p, fromState))481 {482 // Process has not exited or been killed since transition to this state was initiated483 LogProcessCount(p, Interlocked.Increment(ref _processCount));484 }485 return Task.CompletedTask;486 }487 protected override void Leave(ChromiumProcess p)488 => LogProcessCount(p, Interlocked.Decrement(ref _processCount));489 public override Task StartAsync(ChromiumProcess p) => Task.CompletedTask;490 public override Task ExitAsync(ChromiumProcess p, TimeSpan timeout) => Exiting.EnterFromAsync(p, this, timeout);491 public override Task KillAsync(ChromiumProcess p) => Killing.EnterFromAsync(p, this);492 private static void LogProcessCount(ChromiumProcess p, int processCount)493 {494 try495 {496 p._logger?.LogInformation("Process Count: {ProcessCount}", processCount);497 }498 catch499 {500 // Prevent logging exception from causing havoc501 }502 }503 }504 private class ExitingState : State505 {506 public Task EnterFromAsync(ChromiumProcess p, State fromState, TimeSpan timeout)507 {508 return !TryEnter(p, fromState) ? p._currentState.ExitAsync(p, timeout) : ExitAsync(p, timeout);509 }510 public override async Task ExitAsync(ChromiumProcess p, TimeSpan timeout)511 {512 var timeoutTask = Task.Delay(timeout);513 var waitForExitTask = WaitForExitAsync(p);514 var completedTask = await Task.WhenAny(waitForExitTask, timeoutTask).ConfigureAwait(false);515 if (completedTask == timeoutTask)516 {517 await Killing.EnterFromAsync(p, this).ConfigureAwait(false);518 await waitForExitTask.ConfigureAwait(false);519 }520 }521 public override Task KillAsync(ChromiumProcess p) => Killing.EnterFromAsync(p, this);522 }523 private class KillingState : State524 {525 public Task EnterFromAsync(ChromiumProcess p, State fromState)526 {527 if (!TryEnter(p, fromState))528 {529 // Delegate KillAsync to current state, because it has already changed since530 // transition to this state was initiated.531 return p._currentState.KillAsync(p);532 }533 try534 {535 if (!p.Process.HasExited)536 {537 p.Process.Kill();538 }539 }540 catch (InvalidOperationException)541 {542 // Ignore543 }544 return WaitForExitAsync(p);545 }546 public override Task ExitAsync(ChromiumProcess p, TimeSpan timeout) => WaitForExitAsync(p);547 public override Task KillAsync(ChromiumProcess p) => WaitForExitAsync(p);548 }549 private class ExitedState : State550 {551 public void EnterFrom(ChromiumProcess p, State fromState)552 {553 while (!TryEnter(p, fromState))554 {555 // Current state has changed since transition to this state was requested.556 // Therefore retry transition to this state from the current state. This ensures557 // that Leave() operation of current state is properly called.558 fromState = p._currentState;559 if (fromState == this)560 {561 return;562 }563 }564 p._exitCompletionSource.TrySetResult(true);565 p._tempUserDataDir?.Dispose();566 }567 public override Task ExitAsync(ChromiumProcess p, TimeSpan timeout) => Task.CompletedTask;568 public override Task KillAsync(ChromiumProcess p) => Task.CompletedTask;569 public override Task WaitForExitAsync(ChromiumProcess p) => Task.CompletedTask;570 }571 private class DisposedState : State572 {573 public void EnterFrom(ChromiumProcess p, State fromState)574 {575 if (!TryEnter(p, fromState))576 {577 // Delegate Dispose to current state, because it has already changed since578 // transition to this state was initiated.579 p._currentState.Dispose(p);580 }581 else if (fromState != Exited)582 {583 Kill(p);584 p._exitCompletionSource.TrySetException(new ObjectDisposedException(p.ToString()));585 p._tempUserDataDir?.Dispose();586 }587 }588 public override Task StartAsync(ChromiumProcess p) => throw new ObjectDisposedException(p.ToString());589 public override Task ExitAsync(ChromiumProcess p, TimeSpan timeout) => throw new ObjectDisposedException(p.ToString());590 public override Task KillAsync(ChromiumProcess p) => throw new ObjectDisposedException(p.ToString());591 public override void Dispose(ChromiumProcess p)592 {593 // Nothing to do594 }595 }596 #endregion597 }598 #endregion599 }600}...

Full Screen

Full Screen

PuppeteerLaunchTests.cs

Source:PuppeteerLaunchTests.cs Github

copy

Full Screen

...189 }190 [Theory]191 [InlineData(false)]192 [InlineData(true)]193 public async Task ChromeShouldBeClosed(bool useDisposeAsync)194 {195 var options = TestConstants.DefaultBrowserOptions();196 var launcher = new Launcher(TestConstants.LoggerFactory);197 await using (var browser = await launcher.LaunchAsync(options))198 await using (var page = await browser.NewPageAsync())199 {200 var response = await page.GoToAsync(TestConstants.EmptyPage);201 Assert.Equal(HttpStatusCode.OK, response.Status);202 if (useDisposeAsync)203 {204 // emulates what would happen in a C#8 await using block205 await browser.DisposeAsync();206 }207 else208 {209 await browser.CloseAsync();210 }211 Assert.True(launcher.Process.HasExited);212 }213 }214 [PuppeteerFact]215 public async Task ChromeShouldBeClosedOnDispose()216 {217 var options = TestConstants.DefaultBrowserOptions();218 var launcher = new Launcher(TestConstants.LoggerFactory);219 await using (var browser = await launcher.LaunchAsync(options))220 await using (var page = await browser.NewPageAsync())221 {222 var response = await page.GoToAsync(TestConstants.EmptyPage);223 Assert.Equal(HttpStatusCode.OK, response.Status);224 }225 Assert.True(await launcher.Process.WaitForExitAsync(TimeSpan.FromSeconds(10)));226 Assert.True(launcher.Process.HasExited);227 }228 [PuppeteerFact]229 public async Task ShouldNotOpenTwoChromesUsingTheSameLauncher()...

Full Screen

Full Screen

Launcher.cs

Source:Launcher.cs Github

copy

Full Screen

...322 _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;...

Full Screen

Full Screen

LauncherBase.cs

Source:LauncherBase.cs Github

copy

Full Screen

...46 /// Finalizes an instance of the <see cref="LauncherBase"/> class.47 /// </summary>48 ~LauncherBase()49 {50 Dispose(false);51 }52 internal TaskCompletionSource<bool> ExitCompletionSource { get; } = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);53 internal TaskCompletionSource<string> StartCompletionSource { get; } = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);54 internal LaunchOptions Options { get; }55 /// <summary>56 /// Gets Base process details.57 /// </summary>58 public Process Process { get; }59 /// <summary>60 /// Gets Base endpoint.61 /// </summary>62 public string EndPoint => StartCompletionSource.Task.IsCompleted63 ? StartCompletionSource.Task.Result64 : null;65 /// <summary>66 /// Indicates whether Base process is exiting.67 /// </summary>68 public bool IsExiting => _stateManager.CurrentState.IsExiting;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>88 protected virtual void Dispose(bool disposing) => _stateManager.CurrentState.Dispose(this);89 /// <summary>90 /// Asynchronously starts Base process.91 /// </summary>92 /// <returns></returns>93 public Task StartAsync() => _stateManager.CurrentState.StartAsync(this);94 /// <summary>95 /// Asynchronously waits for graceful Base process exit within a given timeout period.96 /// Kills the Base process if it has not exited within this period.97 /// </summary>98 /// <param name="timeout">The maximum waiting time for a graceful process exit.</param>99 /// <returns></returns>100 public Task EnsureExitAsync(TimeSpan? timeout) => timeout.HasValue101 ? _stateManager.CurrentState.ExitAsync(this, timeout.Value)102 : _stateManager.CurrentState.KillAsync(this);...

Full Screen

Full Screen

TempDirectory.cs

Source:TempDirectory.cs Github

copy

Full Screen

...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();41 }42 }43 public override string ToString() => Path;44 public Task DeleteAsync(CancellationToken cancellationToken = default)45 => _deleteTask ?? (_deleteTask = DeleteAsync(Path, CancellationToken.None));46 private static async Task DeleteAsync(string path, CancellationToken cancellationToken = default)47 {48 const int minDelayInMsec = 200;49 const int maxDelayInMsec = 8000;50 var retryDelay = minDelayInMsec;...

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using PuppeteerSharp.Helpers;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 System;19using System.Threading.Tasks;20using PuppeteerSharp.Helpers;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 System;36using System.Threading.Tasks;37using PuppeteerSharp.Helpers;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 System;53using System.Threading.Tasks;54using PuppeteerSharp.Helpers;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 System;70using System.Threading.Tasks;71using PuppeteerSharp.Helpers;72{73 {74 public TempDirectory()75 {

Full Screen

Full Screen

Dispose

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(), Path.GetRandomFileName());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(), Path.GetRandomFileName());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(), Path.GetRandomFileName());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(), Path.GetRandomFileName());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(), Path.GetRandomFileName());77 Directory.CreateDirectory(Path);78 }79 public string Path { get;

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp.Helpers;5{6 {7 static async Task Main(string[] args)8 {9 using (var tempDirectory = new TempDirectory())10 {11 var browser = await Puppeteer.LaunchAsync(new LaunchOptions12 {13 Args = new[] { "--no-sandbox" },14 });15 var page = await browser.NewPageAsync();16 await page.ScreenshotAsync("google.png");17 await browser.CloseAsync();18 }19 }20 }21}22using System;23using System.IO;24using System.Threading.Tasks;25using PuppeteerSharp.Helpers;

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

1using (var tempDirectory = new TempDirectory())2{3 var browser = await Puppeteer.LaunchAsync(new LaunchOptions4 {5 {6 },7 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",8 });9 var page = await browser.NewPageAsync();10 await page.ScreenshotAsync("google.png");11}

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

1var tempDir = new TempDirectory();2var browser = await Puppeteer.LaunchAsync(new LaunchOptions3{4 {5 $"--user-data-dir={tempDir.Path}"6 }7});8var page = await browser.NewPageAsync();9await page.ScreenshotAsync("1.png");10await browser.CloseAsync();11tempDir.Dispose();12var tempDir = new TempDirectory();13var browser = await Puppeteer.LaunchAsync(new LaunchOptions14{15 {16 $"--user-data-dir={tempDir.Path}"17 }18});19var page = await browser.NewPageAsync();20await page.ScreenshotAsync("2.png");21await browser.CloseAsync();22tempDir.Dispose();23var tempDir = new TempDirectory();24var browser = await Puppeteer.LaunchAsync(new LaunchOptions25{26 {27 $"--user-data-dir={tempDir.Path}"28 }29});30var page = await browser.NewPageAsync();31await page.ScreenshotAsync("3.png");32await browser.CloseAsync();33tempDir.Dispose();34var tempDir = new TempDirectory();35var browser = await Puppeteer.LaunchAsync(new LaunchOptions36{37 {38 $"--user-data-dir={tempDir.Path}"39 }40});41var page = await browser.NewPageAsync();

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Helpers;2using System;3using System.IO;4using System.Threading.Tasks;5{6 {7 public TempDirectory()8 {9 Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());10 Directory.CreateDirectory(Path);11 }12 public string Path { get; }13 public void Dispose()14 {15 {16 Directory.Delete(Path, true);17 }18 catch (Exception)19 {20 }21 }22 }23}24using PuppeteerSharp.Helpers;25using System;26using System.IO;27using System.Threading.Tasks;28{29 {30 public TempDirectory()31 {32 Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());33 Directory.CreateDirectory(Path);34 }35 public string Path { get; }36 public void Dispose()37 {38 {39 Directory.Delete(Path, true);40 }41 catch (Exception)42 {43 }44 }45 }46}47using PuppeteerSharp.Helpers;48using System;49using System.IO;50using System.Threading.Tasks;51{52 {53 public TempDirectory()54 {55 Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());56 Directory.CreateDirectory(Path);57 }58 public string Path { get; }59 public void Dispose()60 {61 {62 Directory.Delete(Path, true);63 }64 catch (Exception)65 {66 }67 }68 }69}70using PuppeteerSharp.Helpers;71using System;72using System.IO;73using System.Threading.Tasks;74{75 {76 public TempDirectory()77 {78 Path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());79 Directory.CreateDirectory(Path);80 }81 public string Path { get; }82 public void Dispose()83 {84 {85 Directory.Delete(Path, true);86 }87 catch (Exception)88 {89 }90 }91 }92}93using PuppeteerSharp.Helpers;94using System;95using System.IO;96using System.Threading.Tasks;97{

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

Dispose

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;20{21 {22 public TempDirectory()23 {24 DirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());25 Directory.CreateDirectory(DirectoryPath);26 }27 public string DirectoryPath { get; }28 public void Dispose()29 {30 Directory.Delete(DirectoryPath, true);31 }32 }33}34using PuppeteerSharp.Helpers;35using System;36{37 {38 public TempDirectory()39 {40 DirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());41 Directory.CreateDirectory(DirectoryPath);42 }43 public string DirectoryPath { get; }44 public void Dispose()45 {46 Directory.Delete(DirectoryPath, true);47 }48 }49}50using PuppeteerSharp.Helpers;51using System;52{53 {54 public TempDirectory()55 {56 DirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());57 Directory.CreateDirectory(DirectoryPath);58 }59 public string DirectoryPath { get; }60 public void Dispose()61 {62 Directory.Delete(DirectoryPath, true);63 }64 }65}66using PuppeteerSharp.Helpers;67using System;68{69 {70 public TempDirectory()71 {72 DirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandom

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