How to use Close method of PuppeteerSharp.Connection class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Connection.Close

run.csx

Source:run.csx Github

copy

Full Screen

...565 }566 finally567 {568 if (outFs != null)569 outFs.Close();570 }571}572573private static void DigiSignPdf(byte[] source,574 Stream destinationStream,575 IDictionary<string, string> data,576 Stream privateKeyStream,577 string keyPassword,578 string digestAlgorithm,579 string reason,580 string location,581 string contact,582 bool signPdf,583 string pdfpassword,584 bool isVisibleSignature)585{586 // reader and stamper587 PdfReader reader = new PdfReader(source);588 PdfStamper stamper = null;589 if (signPdf)590 {591 stamper = PdfStamper.CreateSignature(reader, destinationStream, '\0');592 }593 else594 {595 stamper = new PdfStamper(reader, destinationStream);596 }597 // password protection598 if (pdfpassword != null)599 {600 byte[] pwd = Encoding.UTF8.GetBytes(pdfpassword);601 stamper.SetEncryption(pwd, pwd, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);602 }603604 // This is used when filling-in the PDF template with the information from the request605 if (data != null)606 {607 AcroFields pdfFormFields = stamper.AcroFields;608 foreach (KeyValuePair<string, string> dic in data)609 {610 AcroFields.Item afld = pdfFormFields.GetFieldItem(dic.Key);611 if (afld != null)612 {613 pdfFormFields.SetField(dic.Key, dic.Value);614 }615 stamper.FormFlattening = true; // Make the PDF read-only616 }617 }618619 if (signPdf)620 {621 Pkcs12Store pk12 = new Pkcs12Store(privateKeyStream, keyPassword.ToCharArray());622 privateKeyStream.Dispose();623624 //then Iterate throught certificate entries to find the private key entry625 string alias = null;626 foreach (string tAlias in pk12.Aliases)627 {628 if (pk12.IsKeyEntry(tAlias))629 {630 alias = tAlias;631 break;632 }633 }634 var pk = pk12.GetKey(alias).Key;635636 // appearance637 PdfSignatureAppearance appearance = stamper.SignatureAppearance;638 //appearance.Image = new iTextSharp.text.pdf.PdfImage();639 appearance.Reason = reason;640 appearance.Location = location;641 appearance.Contact = contact;642 if (isVisibleSignature)643 {644 appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20, 10, 170, 60), reader.NumberOfPages, null);645 }646 // digital signature647648 appearance.SetCrypto(pk, new Org.BouncyCastle.X509.X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, PdfSignatureAppearance.WINCER_SIGNED);649 }650 stamper.Close();651 reader.Close();652}653654public class ParamInfo655{656 public string name { get; set; }657 public string value { get; set; }658 public string orig_value { get; set; }659 public bool isSetting { get; set; }660 public int source { get; set; }661} ...

Full Screen

Full Screen

Connection.cs

Source:Connection.cs Github

copy

Full Screen

...22 Url = url;23 Delay = delay;24 Transport = transport;25 Transport.MessageReceived += Transport_MessageReceived;26 Transport.Closed += Transport_Closed;27 _callbacks = new ConcurrentDictionary<int, MessageTask>();28 _sessions = new ConcurrentDictionary<string, CDPSession>();29 _asyncSessions = new AsyncDictionaryHelper<string, CDPSession>(_sessions, "Session {0} not found");30 }31 #region Private Members32 private int _lastId;33 private readonly ConcurrentDictionary<int, MessageTask> _callbacks;34 private readonly ConcurrentDictionary<string, CDPSession> _sessions;35 private readonly AsyncDictionaryHelper<string, CDPSession> _asyncSessions;36 #endregion37 #region Properties38 /// <summary>39 /// Gets the WebSocket URL.40 /// </summary>41 /// <value>The URL.</value>42 public string Url { get; }43 /// <summary>44 /// Gets the sleep time when a message is received.45 /// </summary>46 /// <value>The delay.</value>47 public int Delay { get; }48 /// <summary>49 /// Gets the Connection transport.50 /// </summary>51 /// <value>Connection transport.</value>52 public IConnectionTransport Transport { get; }53 /// <summary>54 /// Occurs when the connection is closed.55 /// </summary>56 public event EventHandler Disconnected;57 /// <summary>58 /// Occurs when a message from chromium is received.59 /// </summary>60 public event EventHandler<MessageEventArgs> MessageReceived;61 /// <summary>62 /// Gets or sets a value indicating whether this <see cref="Connection"/> is closed.63 /// </summary>64 /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>65 public bool IsClosed { get; internal set; }66 /// <summary>67 /// Connection close reason.68 /// </summary>69 public string CloseReason { get; private set; }70 #endregion71 #region Public Methods72 internal int GetMessageID() => Interlocked.Increment(ref _lastId);73 internal Task RawSendASync(int id, string method, object args, string sessionId = null)74 {75 return Transport.SendAsync(JsonConvert.SerializeObject(76 new ConnectionRequest77 {78 Id = id,79 Method = method,80 Params = args,81 SessionId = sessionId82 },83 JsonHelper.DefaultJsonSerializerSettings));84 }85 internal async Task<JObject> SendAsync(string method, object args = null, bool waitForCallback = true)86 {87 if (IsClosed)88 {89 throw new TargetClosedException($"Protocol error({method}): Target closed.", CloseReason);90 }91 var id = GetMessageID();92 MessageTask callback = null;93 if (waitForCallback)94 {95 callback = new MessageTask96 {97 TaskWrapper = new TaskCompletionSource<JObject>(),98 Method = method99 };100 _callbacks[id] = callback;101 }102 await RawSendASync(id, method, args).ConfigureAwait(false);103 return waitForCallback ? await callback.TaskWrapper.Task.ConfigureAwait(false) : null;104 }105 internal async Task<T> SendAsync<T>(string method, object args = null)106 {107 var response = await SendAsync(method, args).ConfigureAwait(false);108 return response.ToObject<T>(true);109 }110 internal async Task<CDPSession> CreateSessionAsync(TargetInfo targetInfo)111 {112 var sessionId = (await SendAsync<TargetAttachToTargetResponse>("Target.attachToTarget", new TargetAttachToTargetRequest113 {114 TargetId = targetInfo.TargetId,115 Flatten = true116 }).ConfigureAwait(false)).SessionId;117 return await GetSessionAsync(sessionId).ConfigureAwait(false);118 }119 internal bool HasPendingCallbacks() => _callbacks.Count != 0;120 #endregion121 internal void Close(string closeReason)122 {123 if (IsClosed)124 {125 return;126 }127 IsClosed = true;128 CloseReason = closeReason;129 Transport.StopReading();130 Disconnected?.Invoke(this, new EventArgs());131 foreach (var session in _sessions.Values.ToArray())132 {133 session.Close(closeReason);134 }135 _sessions.Clear();136 foreach (var response in _callbacks.Values.ToArray())137 {138 response.TaskWrapper.TrySetException(new TargetClosedException(139 $"Protocol error({response.Method}): Target closed.",140 closeReason));141 }142 _callbacks.Clear();143 }144 internal static Connection FromSession(CDPSession session) => session.Connection;145 internal CDPSession GetSession(string sessionId) => _sessions.GetValueOrDefault(sessionId);146 internal Task<CDPSession> GetSessionAsync(string sessionId) => _asyncSessions.GetItemAsync(sessionId);147 #region Private Methods148 private async void Transport_MessageReceived(object sender, MessageReceivedEventArgs e)149 => await _callbackQueue.Enqueue(() => ProcessMessage(e)).ConfigureAwait(false);150 private async Task ProcessMessage(MessageReceivedEventArgs e)151 {152 try153 {154 var response = e.Message;155 ConnectionResponse obj = null;156 if (response.Length > 0 && Delay > 0)157 {158 await Task.Delay(Delay).ConfigureAwait(false);159 }160 try161 {162 obj = JsonConvert.DeserializeObject<ConnectionResponse>(response, JsonHelper.DefaultJsonSerializerSettings);163 }164 catch (JsonException)165 {166 return;167 }168 ProcessIncomingMessage(obj);169 }170 catch (Exception ex)171 {172 var message = $"Connection failed to process {e.Message}. {ex.Message}. {ex.StackTrace}";173 Close(message);174 }175 }176 private void ProcessIncomingMessage(ConnectionResponse obj)177 {178 var method = obj.Method;179 var param = obj.Params?.ToObject<ConnectionResponseParams>();180 if (method == "Target.attachedToTarget")181 {182 var sessionId = param.SessionId;183 var session = new CDPSession(this, param.TargetInfo.Type, sessionId);184 _asyncSessions.AddItem(sessionId, session);185 }186 else if (method == "Target.detachedFromTarget")187 {188 var sessionId = param.SessionId;189 if (_sessions.TryRemove(sessionId, out var session) && !session.IsClosed)190 {191 session.Close("Target.detachedFromTarget");192 }193 }194 if (!string.IsNullOrEmpty(obj.SessionId))195 {196 var session = GetSession(obj.SessionId);197 session.OnMessage(obj);198 }199 else if (obj.Id.HasValue)200 {201 // If we get the object we are waiting for we return if202 // if not we add this to the list, sooner or later some one will come for it 203 if (_callbacks.TryRemove(obj.Id.Value, out var callback))204 {205 if (obj.Error != null)206 {207 callback.TaskWrapper.TrySetException(new MessageException(callback, obj.Error));208 }209 else210 {211 callback.TaskWrapper.TrySetResult(obj.Result);212 }213 }214 }215 else216 {217 MessageReceived?.Invoke(this, new MessageEventArgs218 {219 MessageID = method,220 MessageData = obj.Params221 });222 }223 }224 private void Transport_Closed(object sender, TransportClosedEventArgs e) => Close(e.CloseReason);225 #endregion226 #region Static Methods227 /// <summary>228 /// Gets default web socket factory implementation.229 /// </summary>230 [Obsolete("Use " + nameof(WebSocketTransport) + "." + nameof(WebSocketTransport.DefaultWebSocketFactory) + " instead")]231 public static readonly WebSocketFactory DefaultWebSocketFactory = WebSocketTransport.DefaultWebSocketFactory;232 internal static async Task<Connection> Create(string url, IConnectionOptions connectionOptions, CancellationToken cancellationToken = default)233 {234#pragma warning disable 618235 var transport = connectionOptions.Transport;236#pragma warning restore 618237 if (transport == null)238 {239 var transportFactory = connectionOptions.TransportFactory ?? WebSocketTransport.DefaultTransportFactory;240 transport = await transportFactory(new Uri(url), connectionOptions, cancellationToken).ConfigureAwait(false);241 }242 return new Connection(url, connectionOptions.SlowMo, transport);243 }244 /// <inheritdoc />245 public void Dispose()246 {247 Dispose(true);248 GC.SuppressFinalize(this);249 }250 /// <summary>251 /// Releases all resource used by the <see cref="Connection"/> object.252 /// It will raise the <see cref="Disconnected"/> event and dispose <see cref="Transport"/>.253 /// </summary>254 /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="Connection"/>. The255 /// <see cref="Dispose()"/> method leaves the <see cref="Connection"/> in an unusable state.256 /// After calling <see cref="Dispose()"/>, you must release all references to the257 /// <see cref="Connection"/> so the garbage collector can reclaim the memory that the258 /// <see cref="Connection"/> was occupying.</remarks>259 /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>260 protected virtual void Dispose(bool disposing)261 {262 Close("Connection disposed");263 Transport.Dispose();264 }265 #endregion266 }267}...

Full Screen

Full Screen

CDPSession.cs

Source:CDPSession.cs Github

copy

Full Screen

...72 /// <summary>73 /// Gets or sets a value indicating whether this <see cref="CDPSession"/> is closed.74 /// </summary>75 /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>76 public bool IsClosed { get; internal set; }77 /// <summary>78 /// Connection close reason.79 /// </summary>80 public string CloseReason { get; private set; }81 /// <summary>82 /// Gets the logger factory.83 /// </summary>84 /// <value>The logger factory.</value>85 #endregion86 #region Public Methods87 internal void Send(string method, object args = null)88 => _ = SendAsync(method, args, false);89 /// <summary>90 /// Protocol methods can be called with this method.91 /// </summary>92 /// <param name="method">The method name</param>93 /// <param name="args">The method args</param>94 /// <typeparam name="T">Return type.</typeparam>95 /// <returns>The task.</returns>96 public async Task<T> SendAsync<T>(string method, object args = null)97 {98 var content = await SendAsync(method, args).ConfigureAwait(false);99 return content.ToObject<T>(true);100 }101 /// <summary>102 /// Protocol methods can be called with this method.103 /// </summary>104 /// <param name="method">The method name</param>105 /// <param name="args">The method args</param>106 /// <param name="waitForCallback">107 /// If <c>true</c> the method will return a task to be completed when the message is confirmed by Chromium.108 /// If <c>false</c> the task will be considered complete after sending the message to Chromium.109 /// </param>110 /// <returns>The task.</returns>111 /// <exception cref="PuppeteerSharp.PuppeteerException"></exception>112 public async Task<JObject> SendAsync(string method, object args = null, bool waitForCallback = true)113 {114 if (Connection == null)115 {116 throw new PuppeteerException(117 $"Protocol error ({method}): Session closed. " +118 $"Most likely the {TargetType} has been closed." +119 $"Close reason: {CloseReason}");120 }121 var id = Connection.GetMessageID();122 MessageTask callback = null;123 if (waitForCallback)124 {125 callback = new MessageTask126 {127 TaskWrapper = new TaskCompletionSource<JObject>(),128 Method = method129 };130 _callbacks[id] = callback;131 }132 try133 {134 await Connection.RawSendASync(id, method, args, SessionId).ConfigureAwait(false);135 }136 catch (Exception ex)137 {138 if (waitForCallback && _callbacks.TryRemove(id, out _))139 {140 callback.TaskWrapper.TrySetException(new MessageException(ex.Message, ex));141 }142 }143 return waitForCallback ? await callback.TaskWrapper.Task.ConfigureAwait(false) : null;144 }145 /// <summary>146 /// Detaches session from target. Once detached, session won't emit any events and can't be used to send messages.147 /// </summary>148 /// <returns></returns>149 /// <exception cref="T:PuppeteerSharp.PuppeteerException"></exception>150 public Task DetachAsync()151 {152 if (Connection == null)153 {154 throw new PuppeteerException($"Session already detached.Most likely the {TargetType} has been closed.");155 }156 return Connection.SendAsync("Target.detachFromTarget", new TargetDetachFromTargetRequest157 {158 SessionId = SessionId159 });160 }161 internal bool HasPendingCallbacks() => _callbacks.Count != 0;162 #endregion163 #region Private Methods164 internal void OnMessage(ConnectionResponse obj)165 {166 var id = obj.Id;167 if (id.HasValue && _callbacks.TryRemove(id.Value, out var callback))168 {169 if (obj.Error != null)170 {171 callback.TaskWrapper.TrySetException(new MessageException(callback, obj.Error));172 }173 else174 {175 callback.TaskWrapper.TrySetResult(obj.Result);176 }177 }178 else179 {180 var method = obj.Method;181 var param = obj.Params?.ToObject<ConnectionResponseParams>();182 MessageReceived?.Invoke(this, new MessageEventArgs183 {184 MessageID = method,185 MessageData = obj.Params186 });187 }188 }189 internal void Close(string closeReason)190 {191 if (IsClosed)192 {193 return;194 }195 CloseReason = closeReason;196 IsClosed = true;197 foreach (var callback in _callbacks.Values.ToArray())198 {199 callback.TaskWrapper.TrySetException(new TargetClosedException(200 $"Protocol error({callback.Method}): Target closed.",201 closeReason));202 }203 _callbacks.Clear();204 Disconnected?.Invoke(this, EventArgs.Empty);205 Connection = null;206 }207 #endregion208 }209}...

Full Screen

Full Screen

WebSocketTransport.cs

Source:WebSocketTransport.cs Github

copy

Full Screen

...73 #region Properties74 /// <summary>75 /// Gets a value indicating whether this <see cref="PuppeteerSharp.Transport.IConnectionTransport"/> is closed.76 /// </summary>77 public bool IsClosed { get; private set; }78 /// <summary>79 /// Occurs when the transport is closed.80 /// </summary>81 public event EventHandler<TransportClosedEventArgs> Closed;82 /// <summary>83 /// Occurs when a message is received.84 /// </summary>85 public event EventHandler<MessageReceivedEventArgs> MessageReceived;86 #endregion87 #region Public methods88 /// <summary>89 /// Sends a message using the transport.90 /// </summary>91 /// <returns>The task.</returns>92 /// <param name="message">Message to send.</param>93 public Task SendAsync(string message)94 {95 var encoded = Encoding.UTF8.GetBytes(message);96 var buffer = new ArraySegment<byte>(encoded, 0, encoded.Length);97 Task SendCoreAsync() => _client.SendAsync(buffer, WebSocketMessageType.Text, true, default);98 return _queueRequests ? _socketQueue.Enqueue(SendCoreAsync) : SendCoreAsync();99 }100 /// <summary>101 /// Stops reading incoming data.102 /// </summary>103 public void StopReading()104 {105 var readerCts = Interlocked.CompareExchange(ref _readerCancellationSource, null, _readerCancellationSource);106 if (readerCts != null)107 {108 // Asynchronous read operations may still be in progress, so cancel it first and then dispose109 // the associated CancellationTokenSource.110 readerCts.Cancel();111 readerCts.Dispose();112 }113 }114 /// <inheritdoc/>115 public void Dispose()116 {117 Dispose(true);118 GC.SuppressFinalize(this);119 }120 /// <summary>121 /// Close the WebSocketTransport122 /// </summary>123 /// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>124 protected virtual void Dispose(bool disposing)125 {126 // Make sure any outstanding asynchronous read operation is cancelled.127 StopReading();128 _client?.Dispose();129 }130 #endregion131 #region Private methods132 /// <summary>133 /// Starts listening the socket134 /// </summary>135 /// <returns>The start.</returns>136 private async Task<object> GetResponseAsync(CancellationToken cancellationToken)137 {138 var buffer = new byte[2048];139 while (!IsClosed)140 {141 var endOfMessage = false;142 var response = new StringBuilder();143 while (!endOfMessage)144 {145 WebSocketReceiveResult result;146 try147 {148 result = await _client.ReceiveAsync(149 new ArraySegment<byte>(buffer),150 cancellationToken).ConfigureAwait(false);151 }152 catch (OperationCanceledException)153 {154 return null;155 }156 catch (Exception ex)157 {158 OnClose(ex.Message);159 return null;160 }161 endOfMessage = result.EndOfMessage;162 if (result.MessageType == WebSocketMessageType.Text)163 {164 response.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));165 }166 else if (result.MessageType == WebSocketMessageType.Close)167 {168 OnClose("WebSocket closed");169 return null;170 }171 }172 MessageReceived?.Invoke(this, new MessageReceivedEventArgs(response.ToString()));173 }174 return null;175 }176 private void OnClose(string closeReason)177 {178 if (!IsClosed)179 {180 IsClosed = true;181 StopReading();182 Closed?.Invoke(this, new TransportClosedEventArgs(closeReason));183 }184 }185 #endregion186 }187}...

Full Screen

Full Screen

PuppeteerEngine.cs

Source:PuppeteerEngine.cs Github

copy

Full Screen

...95 }96 }97 public async Task<IWebBrowser> GetBrowser()98 {99 if (_browser != null && !_browser.IsClosed)100 return _browserWrapper;101 if (_remoteBrowserAddress == null)102 return await StartLocalBrowser();103 else104 return await ConnectToRemoteBrowser();105 }106 /// <summary>107 /// Initialize locally running browser108 /// </summary>109 /// <returns></returns>110 private async Task<IWebBrowser> StartLocalBrowser()111 {112 try113 {114 _logger.Debug("Downloading browser");115 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);116 _logger.Debug("Launching browser");117 _browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new LaunchOptions118 {119 //Devtools = true,120 Headless = _headless,121 UserDataDir = Path.Combine(Environment.CurrentDirectory, "chromedata"),122 DefaultViewport = null,123 //Headless mode changes user agent so we need to force it to use "real" user agent124 Args = new[] { "--user-agent=\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.0 Safari/537.36\"" }125 });126 _logger.Debug("Opening new page");127 Page descriptionPage = await _browser.NewPageAsync();128 await descriptionPage.SetContentAsync("<h1>This is a browser of patreon downloader</h1>");129 _logger.Debug("Creating IWebBrowser");130 _browserWrapper = new WebBrowser(_browser);131 return _browserWrapper;132 }133 catch (PuppeteerSharp.PuppeteerException ex)134 {135 _logger.Fatal($"Browser communication error. Exception: {ex}");136 return null;137 }138 }139 /// <summary>140 /// Initialize connection to remote browser141 /// </summary>142 /// <returns></returns>143 private async Task<IWebBrowser> ConnectToRemoteBrowser()144 {145 try146 {147 _logger.Debug("Connecting to remote browser");148 _browser = await PuppeteerSharp.Puppeteer.ConnectAsync(new ConnectOptions()149 {150 BrowserURL = _remoteBrowserAddress.ToString()151 });152 _logger.Debug("Opening new page");153 Page descriptionPage = await _browser.NewPageAsync();154 await descriptionPage.SetContentAsync("<h1>This is a browser of patreon downloader</h1>");155 _logger.Debug("Creating IWebBrowser");156 _browserWrapper = new WebBrowser(_browser);157 return _browserWrapper;158 }159 catch (PuppeteerSharp.PuppeteerException ex)160 {161 _logger.Fatal($"Browser communication error. Exception: {ex}");162 return null;163 }164 }165 public async Task CloseBrowser()166 {167 if (_remoteBrowserAddress != null)168 return;169 if (_browser != null && !_browser.IsClosed)170 {171 await _browser.CloseAsync();172 _browser.Dispose();173 _browser = null;174 }175 }176 public void Dispose()177 {178 if (_remoteBrowserAddress != null)179 return;180 _logger.Debug("Disposing puppeteer engine");181 _browser?.Dispose();182 }183 }184}...

Full Screen

Full Screen

BrowserTypeLaunchTests.cs

Source:BrowserTypeLaunchTests.cs Github

copy

Full Screen

...30 ///<playwright-file>browsertype-launch.spec.ts</playwright-file>31 public class BrowserTypeLaunchTests : PlaywrightTestEx32 {33 [PlaywrightTest("browsertype-launch.spec.ts", "should reject all promises when browser is closed")]34 public async Task ShouldRejectAllPromisesWhenBrowserIsClosed()35 {36 await using var browser = await BrowserType.LaunchAsync();37 var page = await (await browser.NewContextAsync()).NewPageAsync();38 var neverResolves = page.EvaluateHandleAsync("() => new Promise(r => {})");39 await browser.CloseAsync();40 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => neverResolves);41 // WebKit under task-set -c 1 is giving browser, rest are giving target.42 StringAssert.Contains(" closed", exception.Message);43 }44 [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should throw if page argument is passed")]45 [Skip(SkipAttribute.Targets.Firefox)]46 public Task ShouldThrowIfPageArgumentIsPassed()47 {48 var args = new[] { Server.EmptyPage };49 return PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => BrowserType.LaunchAsync(new() { Args = args }));50 }51 [PlaywrightTest("browsertype-launch.spec.ts", "should reject if launched browser fails immediately")]52 public async Task ShouldRejectIfLaunchedBrowserFailsImmediately()53 {54 await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => BrowserType.LaunchAsync(new() { ExecutablePath = TestUtils.GetAsset("dummy_bad_browser_executable.js") }));55 }56 [PlaywrightTest("browsertype-launch.spec.ts", "should reject if executable path is invalid")]57 public async Task ShouldRejectIfExecutablePathIsInvalid()58 {59 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => BrowserType.LaunchAsync(new() { ExecutablePath = "random-invalid-path" }));60 StringAssert.Contains("Failed to launch", exception.Message);61 }62 [PlaywrightTest("browsertype-launch.spec.ts", "should fire close event for all contexts")]63 public async Task ShouldFireCloseEventForAllContexts()64 {65 await using var browser = await BrowserType.LaunchAsync();66 var context = await browser.NewContextAsync();67 var closeTask = new TaskCompletionSource<bool>();68 context.Close += (_, _) => closeTask.TrySetResult(true);69 await TaskUtils.WhenAll(browser.CloseAsync(), closeTask.Task);70 }71 [PlaywrightTest("browsertype-launch.spec.ts", "should be callable twice")]72 public async Task ShouldBeCallableTwice()73 {74 await using var browser = await BrowserType.LaunchAsync();75 await TaskUtils.WhenAll(browser.CloseAsync(), browser.CloseAsync());76 await browser.CloseAsync();77 }78 /// <summary>79 /// PuppeteerSharp test. It's not in upstream80 /// </summary>81 public async Task ShouldWorkWithEnvironmentVariables()82 {83 var env = new Dictionary<string, string>84 {85 ["Foo"] = "Var"86 };87 await using var browser = await BrowserType.LaunchAsync(new() { Env = env });88 }89 /// <summary>90 /// PuppeteerSharp test. It's not in upstream...

Full Screen

Full Screen

GeneratePdf.cs

Source:GeneratePdf.cs Github

copy

Full Screen

...42 await Task.WhenAll(43 page.WaitForNavigationAsync(), 44 page.ClickAsync("#submit-button"));45 var stream = await page.PdfStreamAsync();46 await browser.CloseAsync();47 string storageConnectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");48 BlobContainerClient container = new BlobContainerClient(storageConnectionString, "invoices");49 container.CreateIfNotExists(Azure.Storage.Blobs.Models.PublicAccessType.None);50 var blockBlobClient = container.GetBlobClient(orderId.ToString() + ".pdf");51 blockBlobClient.Upload(stream, new BlobHttpHeaders { ContentType = "application/pdf" });52 53 string sasUri = blockBlobClient.GenerateSasUri(permissions: Azure.Storage.Sas.BlobSasPermissions.Read, expiresOn: DateTime.Now.AddYears(1)).AbsoluteUri;54 var sqlConnectionString = Environment.GetEnvironmentVariable("DefaultConnection");55 using (var connection = new SqlConnection(sqlConnectionString))56 {57 string sql = "Update Orders Set Processed = -1, InvoiceURL = @InvoiceURL where OrderId = @OrderId";58 var affectedRows = connection.Execute(sql,new {OrderId = orderId, InvoiceURL = sasUri});59 }60 }...

Full Screen

Full Screen

RanksImageService.cs

Source:RanksImageService.cs Github

copy

Full Screen

...55 return null;56 }57 finally58 {59 await browser.CloseAsync();60 await browser.DisposeAsync();61 }62 }63 }64}...

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static async Task Main(string[] args)8 {9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 await browser.CloseAsync();15 }16 }17}

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static void Main(string[] args)8 {9 MainAsync(args).Wait();10 }11 static async Task MainAsync(string[] args)12 {13 var browser = await Puppeteer.LaunchAsync(new LaunchOptions14 {15 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"16 });17 var page = await browser.NewPageAsync();18 await page.ScreenshotAsync("google.png");19 await browser.CloseAsync();20 }21 }22}

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {9 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",10 Args = new string[] { "--remote-debugging-port=9222" }11 };12 var browser = await Puppeteer.LaunchAsync(options);13 var pages = await browser.PagesAsync();14 var page = pages[0];15 await browser.CloseAsync();16 Console.WriteLine("Press any key to exit.");17 Console.ReadKey();18 }19 }20}21public void Close()22using PuppeteerSharp;23using System;24using System.Threading.Tasks;25{26 {27 static async Task Main(string[] args)28 {29 {30 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",31 Args = new string[] { "--remote-debugging-port=9222" }32 };33 var browser = await Puppeteer.LaunchAsync(options);34 var pages = await browser.PagesAsync();35 var page = pages[0];36 browser.Close();37 Console.WriteLine("Press any key to exit.");38 Console.ReadKey();39 }40 }41}42public Task CloseAsync()

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.IO;5using System.Net;6using System.Net.Sockets;7{8 {9 static void Main(string[] args)10 {11 MainAsync().GetAwaiter().GetResult();12 }13 static async Task MainAsync()14 {15 {16 };17 var browser = await Puppeteer.LaunchAsync(options);18 var page = await browser.NewPageAsync();19 await page.ScreenshotAsync("google.png");20 await browser.CloseAsync();21 }22 }23}

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1connection.Close();2connection.Dispose();3await connection.CloseAsync();4await connection.DisposeAsync();5connection.Close();6connection.Dispose();

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful