Complete Internet Explorer Authentication Dialog with Selenium - c#

I am using Selenium to simulate a user to automate some legacy software. The software works only with IE6 (I'm using IE11 in compatibility mode) and is a bit crap.
There is a point in the software where the Windows Security dialog appears. This requires credentials before the user/simulator can proceed.
I'm using IAlert.SetAuthenticationCredentials to try and populate the dialog but this doesn't seem to work. To move on from this, I can enter the details manually, but then Selenium seems to thing the main browser window has been closed:
Currently focused window has been closed.
The WindowHandles collection at this point is empty, but the browser window is still open, and has rendered the correct page.
What's going on here?
UPDATE
The answers provided are suggestions on how to handle the dialog. I'm wondering why Selenium thinks the browser window is closed when in fact it is still there.

It is not possible to interract with native windows via selenium. The way to deal with your issue is for example to use analogue of Robot in Java. Since you are using C# there is a simulator here https://www.codeproject.com/Articles/28064/Global-Mouse-and-Keyboard-Library.
Example code would be like following:
// Simulate (Ctrl + C) shortcut, which is copy for most applications
KeyboardSimulator.SimulateStandardShortcut(StandardShortcut.Copy);
// This does the same as above
KeyboardSimulator.KeyDown(Keys.Control);
KeyboardSimulator.KeyPress(Keys.C);
KeyboardSimulator.KeyUp(Keys.Control);
There are also Mouse simulators, so with this framework it will be possible to enter the required values in window and accept it.

Try to switch to that alert by,
var alert = driver.SwitchTo().Alert();
alert.SetAuthenticationCredentials("Username", "Pwd");
alert.Accept();
I have tested it and it works for IE11, selenium v3.1.0
Ref: https://seleniumhq.github.io/selenium/docs/api/dotnet/html/M_OpenQA_Selenium_IAlert_SetAuthenticationCredentials.htm
Suggesstion 1-Go to internet explorer settings->security settings-> user authentication-> select automatic login with current username and password.
Suggesstion 2- if your application has access to it's API, then login via API, get the authentication token and set the auth.token in browser cookie.

Related

Windows Authentication Pop up Issue in Selinum Automation

I am trying to write UI Automation for a Portal but while Authentication Chrome after entering User name a Pop up comes which can not be handled by selenium c#
I have tried using
https://username:password{siteurl}.com
But it didn't work. Also Auto IT nuget is not working. Any suggestions will be really helpful
PFB the screenshot for the same.
You can't try using a "robot" keyboard which just types in the keyboard. There is no need for the element to be inside the HTML page, as long as you know the prompt is focused:
Install the NuGet InputSimulator:
InputSimulator sim = new InputSimulator();
sim.Keyboard.TextEntry("User123");
sim.Keyboard.KeyPress(VirtualKeyCode.TAB);
sim.Keyboard.TextEntry("Password123");
sim.Keyboard.KeyPress(VirtualKeyCode.RETURN);
This way you just "hit" the keyboard. You code works regardless of the webpage.
If the popping prompt is not part of the HTML page, but a Windows alert, you can try using the keyboard:
new Actions(driver).SendKeys("User_Name").Perform();
new Actions(driver).SendKeys(Keys.Tab).Perform();
new Actions(driver).SendKeys("Password_here").Perform();
new Actions(driver).SendKeys(Keys.Tab).Perform();
new Actions(driver).SendKeys(Keys.Enter).Perform();
Basically you just type the user_name and password and hit the Enter key using Selenium.

C# Based Testing Automation Attaching to Existing Browser

C#, Visual Studio 2015, .NET 4.x Framework, Internet Explorer 11 (or latest Chrome), Windows 8.1 Pro workstation.
For testing purposes, using a Windows Forms or Console application written in C#, I need to automate an existing browser instance running on a Windows 8 or 10 system.
I created a Windows Forms application, and I'm able to automate a browser that I start using the Navigate(...) method within the application using the WebBrowser control and do things like click on a button in a Javascript popup, login using a username and password, select an item from the datagridview and click on the "edit" button associated with that item.
However, once that "edit" button is clicked, additional browser windows are created that are now running outside the "scope" of the WebBrowser control.
The web application opens new instances of the browser using window.open(...,_blank);
I've tried working with the NewWindow event, but I don't seem to be able to grab any kind of "handle" or such to the newly opened windows. The event fires, but what I'm seeing when I debug inside the event is just information about the window that I'm currently working with (not the newly spawned window).
The other things I've tried are Selenium and WatIn.
For both, the examples I had an instance of Internet Explorer 11 running on my Windows 8.1 Pro workstation at www.google.com.
Generally, the examples seem to show that for "attaching to an existing instance" of a browser the examples first firing off the browser. I've tried to connect to an existing browser using both libraries, and I've not had success.
I've tried to use the RemoteWebDriver(...) for Selenium, using the InternetExplorer driver. Another Stack Overflow post indicates I don't need the server component running because the browser and application for testing are on the same machine. My code is as follows:
private void doSeleniumStuff()
{
DesiredCapabilities desired = DesiredCapabilities.InternetExplorer();
using (IWebDriver driver = new RemoteWebDriver(new Uri("http://www.google.com/wd/hub"), desired))
{
IWebElement query = driver.FindElement(By.Name("q"));
query.SendKeys("Cheese");
query.Submit();
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => d.Title.StartsWith("cheese", StringComparison.OrdinalIgnoreCase));
Console.WriteLine("Page title is: " + driver.Title);
}
}
I'm somewhat confused about the URL used in the RemoteWebDriver constructor. The documentation doesn't seem to describe this usage well. What is this "/wd/hub" usage all about?
It failes with:
{"Unexpected error. <!DOCTYPE html>\r\n<html lang=en>\r\n <meta charset=utf-8>\r\n <meta name=viewport content=\"initial-scale=1, minimum-scale=1, width=device-width\">\r\n <title>Error 404 (Not Found)!!1</title>\r\n <style>\r\n *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}#media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}#media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}#media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}\r\n </style>\r\n <a href=//www.google.com/><span id=logo aria-label=Google></span></a>\r\n <p><b>404.</b> <ins>That’s an error.</ins>\r\n <p>The requested URL <code>/wd/hub/session</code> was not found on this server. <ins>That’s all we know.</ins>\r\n"}
I've tried using the AttachTo(...) method in WatIn.
[STAThread]
private void doWatNStuff()
{
using (IE myIE = Browser.AttachTo<IE>(Find.Any))
{
DomContainer dc = myIE.DomContainer;
}
}
Fails in the using with
{"Could not find an IE window matching constraint: Any. Search expired
after '30' seconds."}
The example code provided for WatIn has the code first creating an instance of IE and then attaching to it. I can't help but think that WatIn can attach to a running instance of a browser, but WatIn must first create that instance.
That won't meet my needs.
My final attempt was to use System.Windows.Automation to get an open Internet Explorer window and try to work with it. While I get the window, all I can get access to are the Windows and Transform patterns. Hence, I could potentially automate the resizing of the browser window and close it. But, I can't get the DOM or anything useful.
There are a few articles out there about using Interop with MSHTML or SHDocVw, but nothing super helpful.
I would appreciate any guidance anyone can provide on using whatever tools possible for a .NET C# Windows Forms or Console application to use to somehow connect to an independently opened browser window on the same Windows machine and automating it.
I've been using WatiN succesfully for this. A console app with Program.cs that looks like the following works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WatiN.Core;
namespace WatinTest
{
class Program
{
[STAThread]
static void Main(string[] args)
{
var ie = IE.AttachTo<IE>(Find.ByTitle(new Regex(".*")));
foreach (var div in ie.Divs)
{
Console.WriteLine(div.IdOrName);
}
Console.ReadLine();
}
}
}
This is with Windows 10 and WatiN 2.1.0.

Check if Windows.System.Launcher.LaunchUriAsync was handled

I try to solve problem with the Windows Phone Launcher.
I have application and I would like to call another application using the uri and pass it some data. And I would like to know if the second application started. If the application was not started I would like to do some fallback.
Example:
bool result = await Windows.System.Launcher.LaunchUriAsync(new Uri("secondApp://data/123", UriKind.RelativeOrAbsolute));
if (!result)
{
// Opps. The second application is not installed.
ShowToast("Oops. The applications is not installed.");
UseInternalTinyFunctionalityInstead();
}
But the result is always true. Even though the second application is not installed. And additionally the windows message box is displayed "Search for app in the Store? You need to install an app for this task. Would you like to search for one in the Store? yes, no".
Is it possible to check if the second application was started/ is installed?
Is it possible NOT to display this dialog?
Thank you.
Myth Rush

http authorization with webdriver and popup window

I'm trying to use Selenium WebDriver to automatically login in to a site with a user-name and password. I've done my research and I don't believe this feature is supported by WebDriver, so I need to find another way. The site I'm trying to automate logging into is located here.
When prompted to login a popup window comes up that doesn't seem to be part of the browser. I'm using Firefox and Chrome. It seems Windows API may be required? I already tried passing the credentials in the URL but that didn't work. Also tried sendkeys, but received a Windows exception that the application was not accepting Windows messages. I also tried switching the current handle using driver.windowhandles but the popup doesn't seem to be a new handle.
Does anybody have any ideas? I'm kinda stuck. The preliminary code to get to the popup window is:
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.portal.adp.com");
string currentWindow = driver.CurrentWindowHandle;
IWebElement userLogin = driver.FindElement(By.Id("employee"));
userLogin.Click();
The popup you are seeing is prompted by web server and is a authentication prompt. Selenium doesn't support this operation.
One of the way to handle this limitation is to pass user and password in the url like like below:
http://user:password#example.com
More info available here : http://aleetesting.blogspot.in/2011/10/selenium-webdriver-tips.html
I wanted my answer out there because I think I've solved it. This answer does not require passing the credentials through the URL (for those of you that are unable to like me). It also does not require any custom Firefox Profiles or extensions to be installed or included with the solution or installed onto the browser eliminating cross-machine compatibility issues.
The issue with me was that the authentication could not be completed via passing the credentials through the URL because the login was behind a proxy.
So, I turned to windows automation toolkits and found AutoIT. Using AutoIT and Selenium, you can login automatically by sending the username and password to the windows dialog that appears. Here's how (note the steps below are for c#:
1 - Download AutoIT from http://www.autoitscript.com/site/autoit/downloads/
2 - Add the autoit .dll to your project references.
Right click on references, select Add Reference. Next click the browse button and browse to the dll location (most default installations it will be c:\Program Files (x86)\AutoIt3\AutoItX\AutoItX3.dll), and add to project.
3 - use AutoIT and Selenium like this (assuming your web driver is already initialized):
//Initialize AutoIT
var AutoIT = new AutoItX3();
//Set Selenium page load timeout to 2 seconds so it doesn't wait forever
Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(2));
//Ingore the error
try
{
Driver.Url = url;
}
catch
{
return;
}
//Wait for the authentication window to appear, then send username and password
AutoIT.WinWait("Authentication Required");
AutoIT.WinActivate("Authentication Required");
AutoIT.Send("username");
AutoIT.Send("{TAB}");
AutoIt.Send("password");
AutoIT.Send("{ENTER}");
//Return Selenium page timeout to infinity again
Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(-1));
Anyway, that's it, and it works like a charm :)
Also note that there are some special characters that need to be escaped in AutoIT using the sequence "{x}". For example, if your password is "!tRocks", you'd need to pass it into AutoIT as "{!}tRocks".
Happy automating.
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.http.phishy-userpass-length", 255);
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris", hostname);
Driver = new FirefoxDriver(profile);
hostname is your URL (example.com) then try to
Driver.Navigate().GoToUrl(http://user:password#example.com);
I just got done working on a prototype project that is supposed to handle exactly this kind of situation.
It utilizes BrowserMob, a popular open source proxy, to perform the authentication.
SeleniumBasicAuthWrapper Hope it helps! It is still a work in progress, but hopefully we'll get any kinks or defects ironed out in the near future.

How to hide the browser interface while executing a php script?

I have a php script which i would need the following 3 web browsers to execute it respectively without revealing the respective browser interface to the user.
The 3 web browsers are,
Internet Explorer, Google Chrome, Mozilla Firefox.
I found this C# code snippet but it is documented that it only works for Microsoft Products like Internet Explorer.
ProcessStartInfo PInfo;
Process Pro;
PInfo.CreateNoWindow = true;
PInfo.UseShellExecute = false;
PInfo.WindowStyle = ProcessWindowStyle.Hidden;
Pro = Process.Start(Execute the Php script);
Can anyone advice me how can I hide the browser interface for the other (Google Chrome, Mozilla Firefox) while executing the php script ? Please do give links or code snippets. (Preferably in C#).
PHP is server-side code. A browser is client-side only. This would be impossible without some intermediary code ran on the client's system. This would no doubt be classified as malware.
You can however, try to open up a popup and attempt to hide that popup --but this is unreliable since the client ultimately has the say on how their client behaves. Most browsers already block popups blockers in place for this reason.
Another suggestion might be to be to simply insert an within the webpage with style="visible: hidden" attribute set. This will execute the PHP you seek without the direct knowledge of your client. However, if your primary objective is to hide chrome/ff/ie, I don't think it can be done using white-hat methods.

Categories