public async Task <string> GetCode(string url, TimeSpan ts) { CancellationToken token; TaskCompletionSource <EventArgs> tcs = new TaskCompletionSource <EventArgs>(); GetTokenComplete += (o, args) => { try { tcs.TrySetResult(args); } catch (Exception ex) { tcs.SetException(ex); } }; // cancel in 30s or when the main token is signalled var navigationCts = CancellationTokenSource.CreateLinkedTokenSource(token); navigationCts.CancelAfter((int)ts.TotalMilliseconds); var navigationToken = navigationCts.Token; using (var apartment = new MessageLoopApartment()) { // create WebBrowser inside MessageLoopApartment ( create an independent STA thread) var webBrowser = apartment.Invoke(() => new WebBrowser()); // Add a handler for the web browser to auto comlete registration webBrowser.DocumentCompleted += WebBrowser_DocumentCompleted; // Add a handler for the web browser to capture content change webBrowser.DocumentTitleChanged += WebBrowser_DocumentTitleChanged; try { // run the navigation task inside MessageLoopApartment string html = await apartment.Run(() => webBrowser.NavigateAsync(url, navigationToken), navigationToken); // wait for end of atuth var timeoutTask = Task.Delay(ts); var winner = await Task.WhenAny(tcs.Task, timeoutTask); if (winner == timeoutTask) { throw new TimeoutException("Authentification timeout"); } return(_code);; } finally { // dispose of WebBrowser inside MessageLoopApartment apartment.Invoke(() => webBrowser.Dispose()); } } }
void MainForm_Load(object senderLoad, EventArgs eLoad) { using (var apartment = new MessageLoopApartment()) { // create WebBrowser on a seprate thread with its own message loop var webBrowser = apartment.Run(() => new WebBrowser(), CancellationToken.None).Result; // navigate and wait for the result var bodyHtml = apartment.Invoke(() => { WebBrowserDocumentCompletedEventHandler handler = null; var pageLoadedTcs = new TaskCompletionSource <string>(); handler = (s, e) => { try { webBrowser.DocumentCompleted -= handler; pageLoadedTcs.SetResult(webBrowser.Document.Body.InnerHtml); } catch (Exception ex) { pageLoadedTcs.SetException(ex); } }; webBrowser.DocumentCompleted += handler; webBrowser.Navigate("http://example.com"); // return Task<string> return(pageLoadedTcs.Task); }).Result; MessageBox.Show("body content:\n" + bodyHtml); // execute some JavaScript var documentHtml = apartment.Invoke(() => { // at least one script element must be present for eval to work var scriptElement = webBrowser.Document.CreateElement("script"); webBrowser.Document.Body.AppendChild(scriptElement); // inject and run some script var scriptResult = webBrowser.Document.InvokeScript("eval", new[] { "(function(){ return document.documentElement.outerHTML; })();" }); return(scriptResult.ToString()); }); MessageBox.Show("document content:\n" + documentHtml); // dispose of webBrowser apartment.Run(() => webBrowser.Dispose(), CancellationToken.None).Wait(); webBrowser = null; } }
public async Task EvalJavascriptFailsIfWebsiteDoesNotContainAnyJavascriptAsync() { using var apartment = new MessageLoopApartment(); using var cancellationTokenSource = this.CtsFactory(20); /* create WebBrowser inside MessageLoopApartment */ var webBrowser = apartment.Invoke(() => new WebBrowser()); var container = apartment.Invoke(() => new FormsWebBrowser(webBrowser)); // If the website does not contain any Javascript it will fail to evaluate new Javascript. await apartment.Run(() => webBrowser.NavigateAsync(Constants.PathToIssueWebsites.IssueWithMissingJavascript, ct: cancellationTokenSource.Token), cancellationTokenSource.Token); await Assert.ThrowsAsync <BrowservusException>(() => container.Document.GetElementByIdAsync("divWithId")); }
public async Task QuerySelectorFailsIfItemWasNotFoundAsync() { using var apartment = new MessageLoopApartment(); using var cancellationTokenSource = this.CtsFactory(20); /* create WebBrowser inside MessageLoopApartment */ var webBrowser = apartment.Invoke(() => new WebBrowser()); var container = apartment.Invoke(() => new FormsWebBrowser(webBrowser)); await apartment.Run(() => webBrowser.NavigateAsync(Constants.PathToWorkingWebsites.FullWorkingExample, ct: cancellationTokenSource.Token), cancellationTokenSource.Token); await Assert.ThrowsAsync <BrowservusException>(() => container.Document.QuerySelectorAsync("someWeirdQuerySelectorThatIsNeverSucceeding")); }
public async Task QuerySelectorSucceedsIfItemWasFoundAsync() { using var apartment = new MessageLoopApartment(); using var cancellationTokenSource = this.CtsFactory(20); /* create WebBrowser inside MessageLoopApartment */ var webBrowser = apartment.Invoke(() => new WebBrowser()); var container = apartment.Invoke(() => new FormsWebBrowser(webBrowser)); await apartment.Run(() => webBrowser.NavigateAsync(Constants.PathToWorkingWebsites.FullWorkingExample, ct: cancellationTokenSource.Token), cancellationTokenSource.Token); var element = await container.Document.QuerySelectorAsync(".querySelectorClass"); Assert.True(!string.IsNullOrWhiteSpace(element.BrowservusId)); }
public async Task EvalJavascriptFailsIfWebBrowserCompatModeIsNotSetAsync() { using var apartment = new MessageLoopApartment(); using var cancellationTokenSource = this.CtsFactory(20); /* create WebBrowser inside MessageLoopApartment */ var webBrowser = apartment.Invoke(() => new WebBrowser()); var container = apartment.Invoke(() => new FormsWebBrowser(webBrowser)); await apartment.Run(() => webBrowser.NavigateAsync(Constants.PathToIssueWebsites.IssueWithMissingXuaCompatMetaTag, ct: cancellationTokenSource.Token), cancellationTokenSource.Token); var error = await Assert.ThrowsAsync <BrowservusException>(() => container.Document.QuerySelectorAsync(".querySelectorClass")); Assert.Contains("querySelector", error.Message); }
public async Task GetElementByIdSucceedsIfItemWasFoundAsync() { using var apartment = new MessageLoopApartment(); using var cancellationTokenSource = this.CtsFactory(20); /* create WebBrowser inside MessageLoopApartment */ var webBrowser = apartment.Invoke(() => new WebBrowser()); var container = apartment.Invoke(() => new FormsWebBrowser(webBrowser)); await apartment.Run(() => webBrowser.NavigateAsync(Constants.PathToWorkingWebsites.FullWorkingExample, ct: cancellationTokenSource.Token), cancellationTokenSource.Token); apartment.Invoke(() => { var test = webBrowser.SafeInvoke(x => x.DocumentText); // would throw out of apartment }); var element = await container.Document.GetElementByIdAsync("divWithId"); Assert.True(!string.IsNullOrWhiteSpace(element.BrowservusId)); }
public SerferService() { // CancellationToken cancelToken WebBrowserExt.SetFeatureBrowserEmulation(); _cancelToken = new CancellationToken(); // create an independent STA thread _apartment = new MessageLoopApartment(); // create a WebBrowser on that STA thread _browser = _apartment.Run(() => new WebBrowser(), _cancelToken).Result; //// Add a handler for the web browser to auto comlete registration //_browser.DocumentCompleted += WebBrowser_DocumentCompleted; //// Add a handler for the web browser to capture content change //_browser.DocumentTitleChanged += WebBrowser_DocumentTitleChanged; }
private static async Task Work() { _config = Configuration.LoadConfig("config.json"); _chatbox = new Chatbox(_config); _skypeCommander = new SkypeCommander(_config); _skypeCommander.SetUp(); //_skypeCommander._skype.SendMessage("princess_bot", "[b]test[/b]"); _aprt = new MessageLoopApartment(); _aprt.Invoke(() => { Application.EnableVisualStyles(); _frm = new Form1(); _frm.Show(); }); _skypeCommander.OnMessageRecieved((message, status) => { Console.WriteLine("Message Recieved: " + message.Body); if (message.Body.IndexOf("|") == 0 && message.Body.Length != 1) { Container container = CreateContainer(message, status); using (var sw = new StringWriter()) { var i = -1; _skypeCommander.DoOnAdminChats(chat => chat.SendMessage(message.Sender.Handle + " - " + message.Body)); try { var commands = container.GetAllInstances<CommandBase>().Where(x => x.ShouldDisplay()); var commandLineToArgs = CommandLineToArgs(message.Body.Substring(1)); foreach (var command in commandLineToArgs) { Console.WriteLine(command); } i = ConsoleCommandDispatcher.DispatchCommand( commands, commandLineToArgs, sw, false); } catch (Exception e) { Console.WriteLine(e); i = 2; } if (i == -2) { message.Chat.SendNickedMessage("Error Processing Request"); } else { if(i != 0) message.Chat.SendNickedMessage(sw.GetStringBuilder().ToString().Replace("SkypeBotTest.vshost.exe", "")); } _config.Save(); } } }); foreach (var chatHandle in _config.RegisteredChats) { _chatbox.Start(_skypeCommander._skype.Chat[chatHandle]); } while (true) { Console.WriteLine("Waiting For Input!"); Console.ReadLine(); } }
public static void TestClassSetup() { s_apartment = new MessageLoopApartment(); }