C# IE11 Automation - Cannot Connect To Open IE Window - c#

I'm trying to connect to an Internet Explorer window that is already open. Once connected I need to send some keystrokes (via SendKeys) to the IE window for some processing. I've got the following code below that works up until the SendKeys command. It finds the IE window titled "Graphics Database". When it hits "SendKeys.Send("{TAB}");" I get the error "An unhandled exception of type 'System.NullReferenceException' occurred".
Additional information: I also get the following on the NullReferenceException error. The weird thing is if I code to open a new IE window and then use SendKeys it works fine. Connecting to an existing windows seems to cause this issue.
SendKeys cannot run inside this application because the application is not handling Windows messages. Either change the application to handle messages, or use the SendKeys.SendWait method.
Can anyone please help me figure out what to do to fix this?
Andy
InternetExplorer IE = null;
// Get all browser objects
ShellWindows allBrowsers = new ShellWindows();
if (allBrowsers.Count == 0)
{
throw new Exception("Cannot find IE");
}
// Attach to IE program process
foreach (InternetExplorer browser in allBrowsers)
{
if (browser.LocationName == "Graphics Database")
{
MessageBox.Show ("Found IE browser '" + browser.LocationName + "'");
IE = (InternetExplorer)browser;
}
}
IE.Visible = true;
System.Threading.Thread.Sleep(2000);
SendKeys.Send("{TAB}");
SendKeys.Send("G1007");
SendKeys.Send("{ENTER}");

I was able to resolve this issue. I could never get the IE.Visible = true to work. This seemed to do nothing in my code. I had to use the SetForegroundWindow() to set the focus to the IE window.
// Find the IE window
int hWnd = FindWindow(null, "Graphics Database - Internet Explorer");
if (hWnd > 0) // The IE window was found.
{
// Bring the IE window to the front.
SetForegroundWindow(hWnd);
This site helped me immensely with getting the SetForegroundWindow() working.
http://forums.codeguru.com/showthread.php?460402-C-General-How-do-I-activate-an-external-Window

Andy please bear with me as this will be long. First you are going to want to look mshtml documentation and Dom. https://msdn.microsoft.com/en-us/library/aa741314(v=vs.85).aspx I don't know why automation is so convoluted but it is. The UIautomation class works great for windows apps but has nothing really for IE that I've been able to find. Others will point to third parties like waitn and selenium. Waitn appears to no longer be supported and selenium won't let you grab an open IE browser. I have gone down this path recently because I wanted to be able to create an app to store my web passwords and auto fill them in since I can't save my username and passwords in browser due to security restrictions. I have an example here and hope it helps. First open up IE and navigate to http://aavtrain.com/index.asp. Then have a console project with mshtml referenced and shdocvw. Here is code below. It gets the window then finds elements for username, password, and submit. then populates the username and password and clicks the submit button. I don't have a login to this site so it won't log you in. I have been using it for my testing. Problem I have is sites with javascript login forms. If you get further with this info please post back as I am still trying to evolve the concepts and create something reusable.
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
Console.WriteLine("Starting Search\n\n\n");
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
if (ie.LocationURL.Contains("aavtrain"))
{
Console.WriteLine(ie.LocationURL);
Console.WriteLine("\n\n\n\n");
Console.WriteLine("FOUND!\n");
mshtml.HTMLDocument document = ie.Document;
mshtml.IHTMLElementCollection elCol = document.getElementsByName("user_name");
mshtml.IHTMLElementCollection elCol2 = document.getElementsByName("password");
mshtml.IHTMLElementCollection elCol3 = document.getElementsByName("Submit");
Console.WriteLine("AutofillPassword");
foreach (mshtml.IHTMLInputElement i in elCol)
{
i.defaultValue = "John";
}
foreach (mshtml.IHTMLInputElement i in elCol2)
{
i.defaultValue = "Password";
}
Console.WriteLine("Will Click Button in 2 seconds");
Thread.Sleep(2000);
foreach (mshtml.HTMLInputButtonElement i in elCol3)
{
i.click();
}
}
}
Console.WriteLine("Finished");

Related

Unable to handle authentication pop up

I am using C# , Selenium , AutoIt and Google Chrome.
I can launch the browser, and can see the authentication pop up.
Pop up window disappears when below code is executed and after that the browser stays there forever.
autoItX3 autoIt = new AutoItX3();
Driver.Instance.Manage().Window.Maximize();
Driver.Instance.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2);
try
{
Driver.Instance.Navigate().GoToUrl(Driver.BaseAddress);
}
catch
{
return;
}
autoIt.WinWait("Authentication Required");
autoIt.WinActivate("Authentication Required");
autoIt.Send("admin");
autoIt.Send("{TAB}");
autoIt.Send("pass");
autoIt.Send("{ENTER}");
Driver.Instance.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(-1);
You are trying to automate a child window.
Autoit doesn't see child windows untill told to.
Opt("WinSearchChildren", 1) ;0=no, 1=search children also
Allows the window search routines to search child windows as well as
top-level windows. 0 = (default) Only search top-level windows 1 =
Search top-level and child windows
hard to make comment without knowing the internals of the authentication implementation on the server. One thing is sure - it is a bad idea from security view because parameters appended to the URL are not secure.
like : http://myURL.com/index.jsp/j_security_check?j_username=username&j_password=password
or
"http://username:password#www.example.com/")
this is what worked for me according to our internal authentication :
https://myURL.com/login/Login.aspx?usestandardlogin=1
so its => "http:YouURL.com" + "?" + "usestandardlogin=1"
now I am not seeing any pop up , it just re-direct me on login.

WatiN doesn't find anything

I'm new to C# and I'm trying to do an application that automatize Internet Explorer.
When I click a button, the application does :
using ( var Browser = new IE())
{
Browser.GoTo("http://testweb.com");
Browser.TextField(Find.ByName("username")).TypeText("User");
Browser.TextField(Find.ByName("password")).TypeText("Pass");
}
But it doesn't write anything. It navigates to the web but...
Try this:
IE ie = null;
ie = new IE();
ie.GoTo("Link");
ie.WaitForComplete();
At least to get started.
For the other bit, you need to get an exact identification and then you can tell WaTiN to interact with it.
Textfield userTextBox = ie.Textfield(Find.ByName("name"));
userTextBox.TypeText("user");
This may seem banal but now you can add a peek definition in your code and see if "userTextBox" gets found by name. If it doesn't you need to find it through another method (ID or class).

Create instance of internet explorer working with visual c#

I am working on a project to automate login and form fillup of a booking website.The user enters all the required info into a windows form.When i fire the Go button there is an automatic login followed by form fillup(it's an autofill thing i am trying to).I dont want to use the inbuilt web browser of visual c# of which i can easily create new instances.
Now i can start up Internet explorer but i need to tell the PC what info to fill in what page.So i think i need to create an instance of Internet Explorer for every different page
SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer();
IE.Navigate("https://www.irctc.co.in/eticketing/loginHome.jsf");
HtmlElementCollection inputs = IE.Document.GetElementsByTagName("input");
foreach (HtmlElement field in inputs)
{
if (field.GetAttribute("name").Equals("j_username"))
{
field.SetAttribute("value", "username");
}
if (field.GetAttribute("name").Equals("j_password"))
{
field.SetAttribute("value", "password");
}
}
When i use a web browser object instead of IE everything is fine.However now i get a runtime error
"Error HRESULT E_FAIL has been returned from a call to a COM component" in the getElemetsbytagname line.
You need to wait for the login page load to be completed before you try pulling and setting the inputs, add this line of code
while (IE.Busy);
before
HtmlElementCollection inputs = IE.Document.GetElementsByTagName("input");

C# open IE9 window and attach

I have a website that uses pre-installed IE plugins to provide secure communication. I don't have access to this plugins code, so if I want to parse pages from this server I have to do it with IE. Otherwise error message shows up.
I want to create a C# program that will open this site and get it's body.
I've tried to open the IE using
InternetExplorer ie = new InternetExplorer();
unfortunately this page caused not loading of plugins or not reacting to javascript that should make redirection.
I'm trying to do it with solution provided in http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=9683 However there's a problem - I cannot attach to the IE after creating the process.
ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
foreach(InternetExplorer Browser in m_IEFoundBrowsers) {
if(Browser.HWND == (int)m_Proc.MainWindowHandle) {
_IE = Browser;
break;
}
}
this code causes InvalidCastException. When I took a look at the Process tree, I've realised that my app launches console, that launches IE - that's the problem as far as I understand. Please help me in attaching to newly opened IE window... I've tried getting the parent of process running Browser, however it failed...
Locate the browser by finding which browser.Document is HTMLDocument and the LocationName or LocationURL specified. Attach that browser instance to your InternetExplorer object by typecasting browser as InternetExplorer. This code works with IE 11 on my system, and allows interaction with that IE browser instance.
InternetExplorer ie = null
// Launch IE program
// Get all browser objects
ShellWindows allBrowsers = new ShellWindows();
if (allBrowsers.Count == 0)
throw new Exception("Cannot find IE");
// Attach to IE program process
foreach (InternetExplorer browser in allBrowsers)
{
if (browser.Document is HTMLDocument && browser.LocationName == "My Test Web Site")
{
Console.WriteLine("Found IE browser '" + browser.LocationName + "'");
ie = (InternetExplorer)browser;
}
}
if (ie == null)
throw new Exception("Failed to attach to IE");

watin attach to manually started window keeps failing

IList<string> values = new List<string>();
var instance = Find.By("hwnd", "110CC");
...
if(instance != null)
{
var ie = Browser.AttachTo<IE>(instance);
The browser instance is manually started by the tester in case this makes any difference.
This just doesn't work for me I keep getting an exception from watin saying that it can't find a window with that handle.
I got the handle with Spy++.
I tried searching by window title or window url also but it also didn't work.
Is there any way to do this?
Thank you
The below works as expected / no errors. WatiN 2.1, IE9, Win7
Before running the code, open an IE browser and point it at cnn.com
IE browser = Browser.AttachTo<IE>(Find.ByUrl("www.cnn.com"));
browser.TextField("hdr-search-box").TypeText("searchy");

Categories