public async Task ShouldEmittedWhenBrowserGetsClosedDisconnectedOrUnderlyingWebsocketGetsClosed() { var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions(), TestConstants.ChromiumRevision, TestConstants.LoggerFactory); var connectOptions = new ConnectOptions { BrowserWSEndpoint = originalBrowser.WebSocketEndpoint }; var remoteBrowser1 = await Puppeteer.ConnectAsync(connectOptions, TestConstants.LoggerFactory); var remoteBrowser2 = await Puppeteer.ConnectAsync(connectOptions, TestConstants.LoggerFactory); var disconnectedOriginal = 0; var disconnectedRemote1 = 0; var disconnectedRemote2 = 0; originalBrowser.Disconnected += (sender, e) => ++ disconnectedOriginal; remoteBrowser1.Disconnected += (sender, e) => ++ disconnectedRemote1; remoteBrowser2.Disconnected += (sender, e) => ++ disconnectedRemote2; remoteBrowser2.Disconnect(); Assert.Equal(0, disconnectedOriginal); Assert.Equal(0, disconnectedRemote1); Assert.Equal(1, disconnectedRemote2); await originalBrowser.CloseAsync(); Assert.Equal(1, disconnectedOriginal); Assert.Equal(1, disconnectedRemote1); Assert.Equal(1, disconnectedRemote2); }
public async Task ShouldBeAbleToReconnectToADisconnectedBrowser() { var options = new ConnectOptions() { BrowserWSEndpoint = Browser.WebSocketEndpoint }; var url = TestConstants.ServerUrl + "/frames/nested-frames.html"; var page = await Browser.NewPageAsync(); await page.GoToAsync(url); Browser.Disconnect(); await using (var browser = await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory)) { var pages = (await browser.PagesAsync()).ToList(); var restoredPage = pages.FirstOrDefault(x => x.Url == url); Assert.NotNull(restoredPage); var frameDump = FrameUtils.DumpFrames(restoredPage.MainFrame); Assert.Equal(TestConstants.NestedFramesDumpResult, frameDump); var response = await restoredPage.EvaluateExpressionAsync <int>("7 * 8"); Assert.Equal(56, response); } }
public static async Task TestUber() { Console.WriteLine("Downloading chromium"); Console.WriteLine("Downloading browser"); await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); Console.WriteLine("Downloading browser end"); //Console.WriteLine("Navigating to developers.google.com"); var LaunchOptions = new LaunchOptions { Headless = false }; var ConnectOptions = new ConnectOptions() { BrowserWSEndpoint = wsChromeEndpointurl }; //var url = "https://www.google.com/"; //await Puppeteer.LaunchAsync(LaunchOptions); //using (var browser = await Puppeteer.LaunchAsync(LaunchOptions)) using (var browser = await PuppeteerSharp.Puppeteer.ConnectAsync(ConnectOptions)) using (var page = await browser.NewPageAsync()) { Uber.page = page; var user = Credentials.Uber.user; var password = Credentials.Uber.password; await Uber.Login(user, password); } }
/// <summary> /// Creates a connected client. /// In case credentials are provided, the user will be authenticated and the credentials will be stored in the session. /// By providing credentials in the constructor of the apiClient it is not necessary to provide credentials for each individual request. /// during the session. /// </summary> private static Client CreateApiClient(string username = null, string password = null) { Client apiClient = new Client(); try { apiClient.OnDataChanged += new Client.OnDataChangedHandler(OnDataChanged); apiClient.OnConnectionChanged += OnConnectionStateChanged; apiClient.OnError += OnError; ConnectOptions options = new ConnectOptions(username, password); // Connect and authenticate. By providing credentials to the connectWs method, the credentials will be stored in the session. ConnectionResponse connectResponse = apiClient.ConnectWs(WebSocketUrl, options).Result; if (connectResponse.Error != null) { Console.WriteLine(string.Format("Connect failed: {0}", connectResponse.Error?.First().Message)); } } catch (Exception ex) { Console.WriteLine("Error occurred during client creation: {0}", ex.Message); } Console.WriteLine(""); return(apiClient); }
public async Task <ConnectionData> GetConnectionDataAsync(ConnectOptions connectOptions, Int64 lastChangeId, CancellationToken cancellationToken = default(CancellationToken), Object userState = null) { using (new OperationScope(LocationResourceIds.LocationServiceArea, "GetConnectionData")) { var uri = new Uri(PathUtility.Combine(BaseAddress.GetLeftPart(UriPartial.Path), connectSubUrl)); var uriBuilder = new UriBuilder(uri) { Query = BaseAddress.Query }; var query = new List <KeyValuePair <String, String> > { new KeyValuePair <String, String>("connectOptions", ((Int32)connectOptions).ToString(CultureInfo.InvariantCulture)), new KeyValuePair <String, String>("lastChangeId", ((Int32)lastChangeId).ToString(CultureInfo.InvariantCulture)), new KeyValuePair <String, String>("lastChangeId64", lastChangeId.ToString(CultureInfo.InvariantCulture)) }; uri = uriBuilder.Uri.AppendQuery(query); var message = new HttpRequestMessage(HttpMethod.Get, uri.ToString()); message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return(await SendAsync <ConnectionData>(message, userState, cancellationToken).ConfigureAwait(false)); } }
/// <inheritdoc cref="IBrowserType"/> public override async Task <IBrowserApp> LaunchBrowserAppAsync(LaunchOptions options = null) { options ??= new LaunchOptions(); var(chromiumArgs, tempUserDataDir) = PrepareChromiumArgs(options); string chromiumExecutable = GetBrowserExecutablePath(options); BrowserApp browserApp = null; var process = new ChromiumProcessManager( chromiumExecutable, chromiumArgs, tempUserDataDir, options.Timeout, async() => { if (browserApp == null) { return; } var transport = await BrowserHelper.CreateTransportAsync(browserApp.ConnectOptions).ConfigureAwait(false); await transport.SendAsync(new ConnectionRequest { Id = ChromiumConnection.BrowserCloseMessageId, Method = new BrowserCloseRequest().Command, }.ToJson()).ConfigureAwait(false); }, exitCode => { browserApp?.ProcessKilled(exitCode); }); try { SetEnvVariables(process.Process.StartInfo.Environment, options.Env, Environment.GetEnvironmentVariables()); if (options.DumpIO) { process.Process.ErrorDataReceived += (sender, e) => Console.Error.WriteLine(e.Data); } await process.StartAsync().ConfigureAwait(false); var connectOptions = new ConnectOptions() { BrowserWSEndpoint = process.Endpoint, SlowMo = options.SlowMo, }; browserApp = new BrowserApp(process, () => process.GracefullyClose(), connectOptions); return(browserApp); } catch { await process.KillAsync().ConfigureAwait(false); throw; } }
public async Task <List <VirtualHost> > GetVirtualHosts(ConnectOptions connectOptions) { var client = BuildRestClient(connectOptions); var request = new RestRequest("vhosts"); var response = await client.ExecuteGetAsync <List <VirtualHost> >(request); return(response.Data); }
public async Task <bool> CanConnectAsync(ConnectOptions connectOptions) { var client = BuildRestClient(connectOptions); var request = new RestRequest("overview"); var response = await client.ExecuteGetAsync(request); return(response.IsSuccessful); }
private void connectToRoom(string roomName) { AudioFocus = true; ConnectOptions connectOptions = (new ConnectOptions.Builder()).roomName(roomName).localMedia(localMedia).build(); room = videoClient.connect(connectOptions, roomListener()); setDisconnectAction(); }
public async Task <List <Queue> > GetQueues(ConnectOptions connectOptions, string vhost) { var client = BuildRestClient(connectOptions); var request = new RestRequest("queues"); var response = await client.ExecuteGetAsync <List <Queue> >(request); return(response.Data); }
public async Task AddConnectOptions() { var options = new ConnectOptions { LoginOnly = false, StartDate = "5 days ago", List = true }; var addResponse = await this.Client.AddConnectAsync(PlaidTest.UserName, PlaidTest.Password, DefaultInstitutionType, options : options); addResponse.Dump(); }
/// <inheritdoc cref="IBrowserType.ConnectAsync(ConnectOptions)"/> public override Task <IBrowser> ConnectAsync(ConnectOptions options = null) { if (options?.BrowserURL != null) { throw new PlaywrightSharpException("Option \"BrowserURL\" is not supported by Firefox"); } return(FirefoxBrowser.ConnectAsync(options)); }
public async Task <ConnectOptions> GetConnectOptionsAsync() { var options = new ConnectOptions { BrowserWSEndpoint = await GetWSEndpoint() }; return(options); }
public override async Task <Browser> NewBrowser() { Logger.Debug("Launch browser"); var options = new ConnectOptions() { BrowserWSEndpoint = BrowserWSEndpoint }; return(await Puppeteer.ConnectAsync(options)); }
private IRestClient BuildRestClient(ConnectOptions connectOptions) { var baseUri = new UriBuilder("http", connectOptions.Host, connectOptions.HttpApiPort).Uri; return(new RestClient { BaseUrl = new Uri(baseUri, "api"), Authenticator = new HttpBasicAuthenticator(connectOptions.UserName, connectOptions.Password) }); }
private Task <Browser> ConnectBrowserAsync() { var options = new ConnectOptions { BrowserWSEndpoint = _settings.Token != null ? $"{_settings.BrowserWsEndpoint}?token={_settings.Token}" : _settings.BrowserWsEndpoint, }; return(Puppeteer.ConnectAsync(options, _loggerFactory)); }
/// <inheritdoc cref="IBrowserType.LaunchBrowserAppAsync(LaunchOptions)"/> public override async Task <IBrowserApp> LaunchBrowserAppAsync(LaunchOptions options = null) { options ??= new LaunchOptions(); var(firefoxArguments, tempProfileDir) = PrepareFirefoxArgs(options); string firefoxExecutable = GetBrowserExecutablePath(options); BrowserApp browserApp = null; var process = new FirefoxProcessManager( firefoxExecutable, firefoxArguments, tempProfileDir, options.Timeout, async() => { if (browserApp == null) { return; } var transport = await BrowserHelper.CreateTransportAsync(browserApp.ConnectOptions).ConfigureAwait(false); await transport.SendAsync(new BrowserCloseRequest().Command).ConfigureAwait(false); }, (exitCode) => { browserApp?.ProcessKilled(exitCode); }); try { SetEnvVariables(process.Process.StartInfo.Environment, options.Env, Environment.GetEnvironmentVariables()); if (options.DumpIO) { process.Process.ErrorDataReceived += (sender, e) => Console.Error.WriteLine(e.Data); } await process.StartAsync().ConfigureAwait(false); var connectOptions = new ConnectOptions() { BrowserWSEndpoint = process.Endpoint, SlowMo = options.SlowMo, }; return(new BrowserApp(process, () => Task.CompletedTask, connectOptions)); } catch { await process.KillAsync().ConfigureAwait(false); throw; } }
/// <summary> /// Returns true if we need to connect to the server. /// </summary> /// <param name="optionsNeeded"></param> /// <returns></returns> private Boolean NeedToConnect(ConnectOptions optionsNeeded) { // Make sure we refresh the information if the impersonated user has changed. if (m_locationDataCacheManager.CacheDataExpired) { m_connectionMade = false; m_validConnectionData = ConnectOptions.None; } return(!m_connectionMade || ((optionsNeeded & m_validConnectionData) != optionsNeeded)); }
public async Task <Browser> ConnectAsync(ConnectOptions options) { _plugins.ForEach(e => e.BeforeConnect(options)); var browser = await Puppeteer.ConnectAsync(options); _plugins.ForEach(e => e.AfterConnect(browser)); await OnStart(new BrowserStartContext() { StartType = StartType.Connect }, browser); return(browser); }
internal static async Task <IBrowser> ConnectAsync(IBrowserApp app, ConnectOptions options) { var transport = await BrowserHelper.CreateTransportAsync(options).ConfigureAwait(false); var connection = new FirefoxConnection(transport); var response = await connection.SendAsync(new TargetGetBrowserContextsRequest()).ConfigureAwait(false); var browser = new FirefoxBrowser(app, connection, response.BrowserContextIds); await connection.SendAsync(new TargetEnableRequest()).ConfigureAwait(false); await browser.WaitForTargetAsync(t => t.Type == TargetType.Page).ConfigureAwait(false); return(browser); }
internal static async Task <IBrowser> ConnectAsync(IBrowserApp app, ConnectOptions options) { var transport = await BrowserHelper.CreateTransportAsync(options).ConfigureAwait(false); var connection = new ChromiumConnection(transport); var response = await connection.RootSession.SendAsync(new TargetGetBrowserContextsRequest()).ConfigureAwait(false); var browser = new ChromiumBrowser(connection, response.BrowserContextIds); await connection.RootSession.SendAsync(new TargetSetDiscoverTargetsRequest { Discover = true }).ConfigureAwait(false); await browser.WaitForTargetAsync(t => t.Type == TargetType.Page).ConfigureAwait(false); return(browser); }
public Client(ConnectOptions options) { _options = options; ClientLogic client = new ClientLogic(); _logic = client; client.OnClientConnected += OnClientConnected; client.OnClientDisconnected += OnClientDisconnected; client.OnTick += OnTick; client.OnMessage += OnMessage; client.Connect(_options.Hostname, _options.Port); }
private async Task <ConnectionData> GetConnectionDataAsync(ConnectOptions connectOptions, int lastChangeId, CancellationToken cancellationToken) { int timeoutRetries = 1; while (true) { try { return(await m_locationClient.GetConnectionDataAsync(connectOptions, lastChangeId, cancellationToken).ConfigureAwait(false)); } catch (TimeoutException) when(timeoutRetries-- > 0) { } // Catch TimeoutException when we have retries remaining; otherwise, let it go. } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext context) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); string url = req.Query["url"]; if (url == null) { return(new BadRequestObjectResult("Please pass a name on the query string")); } else { string apikey = config["browserlessApiKey"]; var options = new ConnectOptions() { BrowserWSEndpoint = $"wss://chrome.browserless.io?token={apikey}" }; var browser = await Puppeteer.ConnectAsync(options); var page = await browser.NewPageAsync(); await page.GoToAsync(url); var stream = await page.ScreenshotStreamAsync(new ScreenshotOptions { FullPage = true }); byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, bytesInStream.Length); stream.Dispose(); await page.CloseAsync(); browser.Disconnect(); return(new FileContentResult(bytesInStream, "image/png")); } }
/// <inheritdoc cref="IBrowserType"/> public async Task <IBrowser> ConnectAsync(ConnectOptions options = null) { options = options == null ? new ConnectOptions() : options.Clone(); if (!string.IsNullOrEmpty(options.BrowserURL)) { if (!string.IsNullOrEmpty(options.BrowserWSEndpoint) && options.TransportFactory != null) { throw new ArgumentException("Exactly one of BrowserWSEndpoint or TransportFactory must be passed to connect"); } options.BrowserWSEndpoint = await GetWSEndpointAsync(options.BrowserURL).ConfigureAwait(false); } return(await ChromiumBrowser.ConnectAsync(options).ConfigureAwait(false)); }
private async Task ConnectToRoomAsync() { var token = await viewModel.GetCallToken(AppSettingsManager.UserNickName); client = VideoClient.ClientWithToken(token); // Prepare local media which we will share with Room Participants. PrepareLocalMedia(); ConnectOptions connectOptions = ConnectOptions.OptionsWithBlock(builder => { builder.LocalMedia = localMedia; builder.Name = "account" + AppSettingsManager.AccountId; }); room = client.ConnectWithOptions(connectOptions, roomDelegate); }
public async Task ShouldBeAbleToSetBrowserPropertiesUsingConnectOptions() { var initActionExecuted = false; var options = new ConnectOptions { BrowserWSEndpoint = Browser.WebSocketEndpoint, InitAction = brw => { initActionExecuted = true; } }; var browser = await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory); Assert.True(initActionExecuted); await browser.CloseAsync(); }
public List <Message> FetchMessages(ConnectOptions connectOptions, string vhost, string queue, HashSet <ulong> messagesToBeDeleted) { var factory = new ConnectionFactory { UserName = connectOptions.UserName, Password = connectOptions.Password, VirtualHost = vhost, HostName = connectOptions.Host, Port = connectOptions.AmqpPort, }; using var connection = factory.CreateConnection(); var messages = CreateChannelAndFetch(connection, queue, messagesToBeDeleted); return(messages); }
public async Task ShouldSupportCustomTransport() { var customTransportCreated = false; var options = new ConnectOptions() { BrowserWSEndpoint = Browser.WebSocketEndpoint, TransportFactory = (url, opt, cancellationToken) => { customTransportCreated = true; return(WebSocketTransport.DefaultTransportFactory(url, opt, cancellationToken)); } }; await using (await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory)) { Assert.True(customTransportCreated); } }
public void Connect(ConnectOptions options) { if (options == null) { throw new ArgumentNullException("服务器连接选项不能为空"); } ConnectOptions = options; if (!this.m_Client.IsConnected) { try { m_Client.ConnectAsync(this.ConnectOptions.ServerEP); } catch (Exception ex) { throw ex; } } }