disable IE visibility while using WatiN - c#

I use watin, because I need to open some websites in the background for which the user needs to support Javascript. I don't know if WatiN is the best for this job, but at the moment it takes very long until Internet Explorer gets visible. I need to disable to popping up of Internet Explorer while using WatiN. User doesn't need to see the opening of sites. Is it possible while using WatiN to visit a website without showing it the user or should I use another alternative which supports JS on client side?
My code at the moment;
public static void visitURL()
{
IE iehandler = new IE("http://www.isjavascriptenabled.com");
if (iehandler.ContainsText("Yes"))
Console.WriteLine("js on");
else
Console.WriteLine("js off");
}

The WatIn.Core.IE class has a Visible property, you can initialize the object like that:
new WatiN.Core.IE() { Visible = true }
This way the IE will just blink on the screen when it's created, and then it will get hidden. You can later control the visibility of the IE with the ShowWindow method of WatiN.Core.IE class - I mean you can show it on the screen if you need, or you can hide again.

I use exactly that trick (of hiding IE) for writing UnitTests (using https://github.com/o2platform/FluentSharp_Fork.WatiN) that run in an hidden IE window
For example here is how I create a helper class (with an configurable hidden value)
public IE_TeamMentor(string webRoot, string path_XmlLibraries, Uri siteUri, bool startHidden)
{
this.ie = "Test_IE_TeamMentor".popupWindow(1000,700,startHidden).add_IE();
this.path_XmlLibraries = path_XmlLibraries;
this.webRoot = webRoot;
this.siteUri = siteUri;
}
which is then consumed by this test:
[Test] public void View_Markdown_Article__Edit__Save()
{
var article = tmProxy.editor_Assert() // assert the editor user (or the calls below will fail due to security demands)
.library_New_Article_New() // create new article
.assert_Not_Null();
var ieTeamMentor = this.new_IE_TeamMentor_Hidden();
var ie = ieTeamMentor.ie;
ieTeamMentor.login_Default_Admin_Account("/article/{0}".format(article.Metadata.Id)); // Login as admin and redirect to article page
var original_Content = ie.element("guidanceItem").innerText().assert_Not_Null(); // get reference to current content
ie.assert_Has_Link("Markdown Editor")
.link ("Markdown Editor").click(); // open markdown editor page
ie.wait_For_Element_InnerHtml("Content").assert_Not_Null()
.element ("Content").innerHtml()
.assert_Is(original_Content); // confirm content matches what was on the view page
var new_Content = "This is the new content of this article".add_5_RandomLetters(); // new 'test content'
ie.element("Content").to_Field().value(new_Content); // put new content in markdown editor
ie.button("Save").click(); // save
ie.wait_For_Element_InnerHtml("guidanceItem").assert_Not_Null()
.element ("guidanceItem").innerHtml()
.assert_Is("<P>{0}</P>".format(new_Content)); // confirm that 'test content' was saved ok (and was markdown transformed)
ieTeamMentor.close();
}
Here are a number of posts that might help you to understand how I use it:
https://github.com/TeamMentor/Dev/tree/master/Source_Code/TM_UnitTests/TeamMentor.UnitTests.QA/TeamMentor_QA_IE
http://blog.diniscruz.com/2014/07/how-to-debug-cassini-hosted-website-and.html
http://blog.diniscruz.com/2014/07/using-watin-and-embedded-cassini-to-run.html
http://blog.diniscruz.com/search/label/WatiN

Related

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).

Selenium WebDriver for C# - Popup Dialog Boxes

Is there any support for working with popup dialogs (specifically file downloads) in c#?
For a popup windows dialog, you can use the alert to catch:
IAlert alert = driver.SwitchTo().Alert();
alert.Accept();
No, there isn't - at least not natively.
WebDriver only interacts with the webpage. A popup dialog, once instantiated, becomes the domain of the operating system instead of the webpage.
You can circumvent the file download/upload dialog by issuing a POST or a GET with the content you are retrieving or sending to the server.
You can use tools such as AutoIt, or the Windows Automation API, to interact with other dialog windows.
From the WebDriver FAQ: WebDriver offers the ability to cope with multiple windows. This is done by using the "WebDriver.switchTo().window()" method to switch to a window with a known name. If the name is not known, you can use "WebDriver.getWindowHandles()" to obtain a list of known windows. You may pass the handle to "switchTo().window()".
Full FAQ here.
Example from Thoughtworks
String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Iterator<String> windowIterator = browser.getWindowHandles();
while(windowIterator.hasNext()) {
String windowHandle = windowIterator.next();
popup = browser.switchTo().window(windowHandle);
if (popup.getTitle().equals("Google") {
break;
}
}
Below is the example converted from Java into C# (with deprecated methods replaced)
String parentWindowHandle = _browser.CurrentWindowHandle; // save the current window handle.
IWebDriver popup = null;
var windowIterator = _browser.WindowHandles;
foreach (var windowHandle in windowIterator)
{
popup = _browser.SwitchTo().Window(windowHandle);
if (popup.Title == "Google")
{
break;
}
}

Webbrowser control is not showing Html but shows webpage

I am automating a task using webbrowser control , the site display pages using frames.
My issue is i get to a point , where i can see the webpage loaded properly on the webbrowser control ,but when it gets into the code and i see the html i see nothing.
I have seen other examples here too , but all of those do no return all the browser html.
What i get by using this:
HtmlWindow frame = webBrowser1.Document.Window.Frames[1];
string str = frame.Document.Body.OuterHtml;
Is just :
The main frame tag with attributes like SRC tag etc, is there any way how to handle this?Because as i can see the webpage completely loaded why do i not see the html?AS when i do that on the internet explorer i do see the pages source once loaded why not here?
ADDITIONAL INFO
There are two frames on the page :
i use this to as above:
HtmlWindow frame = webBrowser1.Document.Window.Frames[0];
string str = frame.Document.Body.OuterHtml;
And i get the correct HTMl for the first frame but for the second one i only see:
<FRAMESET frameSpacing=1 border=1 borderColor=#ffffff frameBorder=0 rows=29,*><FRAME title="Edit Search" marginHeight=0 src="http://web2.westlaw.com/result/dctopnavigation.aspx?rs=WLW12.01&ss=CXT&cnt=DOC&fcl=True&cfid=1&method=TNC&service=Search&fn=_top&sskey=CLID_SSSA49266105122&db=AK-CS&fmqv=s&srch=TRUE&origin=Search&vr=2.0&cxt=RL&rlt=CLID_QRYRLT803076105122&query=%22LAND+USE%22&mt=Westlaw&rlti=1&n=1&rp=%2fsearch%2fdefault.wl&rltdb=CLID_DB72585895122&eq=search&scxt=WL&sv=Split" frameBorder=0 name=TopNav marginWidth=0 scrolling=no><FRAME title="Main Document" marginHeight=0 src="http://web2.westlaw.com/result/dccontent.aspx?rs=WLW12.01&ss=CXT&cnt=DOC&fcl=True&cfid=1&method=TNC&service=Search&fn=_top&sskey=CLID_SSSA49266105122&db=AK-CS&fmqv=s&srch=TRUE&origin=Search&vr=2.0&cxt=RL&rlt=CLID_QRYRLT803076105122&query=%22LAND+USE%22&mt=Westlaw&rlti=1&n=1&rp=%2fsearch%2fdefault.wl&rltdb=CLID_DB72585895122&eq=search&scxt=WL&sv=Split" frameBorder=0 borderColor=#ffffff name=content marginWidth=0><NOFRAMES></NOFRAMES></FRAMESET>
UPDATE
The two url of the frames are as follows :
Frame1 whose html i see
http://web2.westlaw.com/nav/NavBar.aspx?RS=WLW12.01&VR=2.0&SV=Split&FN=_top&MT=Westlaw&MST=
Frame2 whose html i do not see:
http://web2.westlaw.com/result/result.aspx?RP=/Search/default.wl&action=Search&CFID=1&DB=AK%2DCS&EQ=search&fmqv=s&Method=TNC&origin=Search&Query=%22LAND+USE%22&RLT=CLID%5FQRYRLT302424536122&RLTDB=CLID%5FDB6558157526122&Service=Search&SRCH=TRUE&SSKey=CLID%5FSSSA648523536122&RS=WLW12.01&VR=2.0&SV=Split&FN=_top&MT=Westlaw&MST=
And the properties of the second frame whose html i do not get are in the picture below:
Thank you
I paid for the solution of the question above and it works 100 %.
What i did was use this function below and it returned me the count to the tag i was seeking which i could not find :S.. Use this to call the function listed below:
FillFrame(webBrowser1.Document.Window.Frames);
private void FillFrame(HtmlWindowCollection hwc)
{
if (hwc == null) return;
foreach (HtmlWindow hw in hwc)
{
HtmlElement getSpanid = hw.Document.GetElementById("mDisplayCiteList_ctl00_mResultCountLabel");
if (getSpanid != null)
{
doccount = getSpanid.InnerText.Replace("Documents", "").Replace("Document", "").Trim();
break;
}
if (hw.Frames.Count > 0) FillFrame(hw.Frames);
}
}
Hope it helps people .
Thank you
For taking html you have to do it that way:
WebClient client = new WebClient();
string html = client.DownloadString(#"http://stackoverflow.com");
That's an example of course, you can change the address.
By the way, you need using System.Net;
This works just fine...gets BODY element with all inner elements:
Somewhere in your Form code:
wb.Url = new Uri("http://stackoverflow.com");
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wbDocumentCompleted);
And here is wbDocumentCompleted:
void wb1DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var yourBodyHtml = wb.Document.Body.OuterHtml;
}
wb is System.Windows.Forms.WebBrowser
UPDATE:
The same as for the document, I think that your second frame is not loaded at the time you check for it's content...You can try solutions from this link. You will have to wait for your frames to be loaded in order to see its content.
The most likely reason is that frame index 0 has the same domain name as the main/parent page, while the frame index 1 has a different domain name. Am I correct?
This creates a cross-frame security issue, and the WB control just leaves you high and dry and doesn't tell you what on earth went wrong, and just leaves your objects, properties and data empty (will say "No Variables" in the watch window when you try to expand the object).
The only thing you can access in this situation is pretty much the URL and iFrame properties, but nothing inside the iFrame.
Of course, there are ways to overcome teh cross-frame security issues - but they are not built into the WebBrowser control, and they are external solutions, depending on which WB control you are using (as in, .NET version or pre .NET version).
Let me know if I have correctly identified your problem, and if so, if you would like me to tell you about the solution tailored to your setup & instance of the WB control.
UPDATE: I have noticed that you're doing a .getElementByTagName("HTML")(0).outerHTML to get the HTML, all you need to do is call this on the document object, or the .body object and that should do it. MyDoc.Body.innerHTML should get the the content you want. Also, notice that there are additional iFrames inside these documents, in case that is of relevance. Can you give us the main document URL that has these two URL's in it so we / I can replicate what you're doing here? Also, not sure why you are using DomElement but you should just cast it to the native object it wants to be cast to, either a IHTMLDocument2 or the object you see in the watch window, which I think is IHTMLFrameElement (if i recall correctly, but you will know what i mean once you see it). If you are trying to use an XML object, this could be the reason why you aren't able to get the HTML content, change the object declaration and casting if there is one, and give it a go & let us know :). Now I'm curious too :).

Link object persisting across multiple pages within one browser instance using WatiN

I'm just getting started with WatiN and attempting to test a large number of pages with authentication. I've taken the approach of only creating a new instance of IE each time new login details are required. Once authenticated, the framework needs to navigate to 2 pages on the site and click a link on each to download a file (repeated multiple times within one authenticated session for different clients).
Navigating to the pages is fine and the download is working with IE9 using a combination of WatiN and SendKeys(). However, when it navigates to the second page and attempts to find the Link object by Text (which has the same text as on the previous page) it returns the download URL from the first page. This means that essentially whatever page I direct WatiN to, it still seems to be persisting the Link object from the first page.
The first method creates my browser object and returns it to the parent class:
public IE CreateBrowser(string email, string password, string loginUrl)
{
Settings.MakeNewIe8InstanceNoMerge = true;
Settings.AutoCloseDialogs = true;
IE ie = new IE(loginUrl);
ie.TextField(Find.ById("Email")).TypeText(email);
ie.TextField(Find.ById("Password")).TypeText(password);
ie.Button(Find.ById("btnLogin")).Click();
Thread.Sleep(1500);
return ie;
}
I then iterate through logins, passing the URL for each required page to the following:
public void DownloadFile(IE ie, string url)
{
//ie.NativeBrowser.NavigateTo(new Uri(url));
ie.GoTo(url);
Thread.Sleep(1000);
//TODO: Why is link holding on to old object?
Link lnk = null;
lnk = ie.Link(Find.ByText("Download file"));
lnk.WaitUntilExists();
lnk.Focus();
lnk.Click();
//Pause to allow IE file dialog box to show
Thread.Sleep(2000);
//Alt + S to save
SendKeys.SendWait("%(S)");
}
The calling method ties it all together like so (I've obfuscated some of the details):
for (int i = 0; i < loginCount; i++)
{
using (IE ie = HelperClass.CreateBrowser(lLogins[i].Email, lLogins[i].Password, ConfigurationManager.AppSettings["loginUrl"]))
{
...Gets list of clients we're wanting to check
for (int j = 0; j < clientCount; j++)
{
string url = "";
switch ()
{
case "Page1":
string startDate = "20110831";
string endDate = "20110901";
url = String.Format(page1BaseUrl, HttpUtility.UrlEncode(lClients[j].Name), startDate, endDate);
break;
case "Page2":
url = String.Format(page2BaseUrl, HttpUtility.UrlEncode(lClients[j].Name));
break;
}
HelperClass.DownloadFile(ie, url);
}
}
}
Does anyone have any idea what could be causing this or how to get around it? Do I need to create a new IE object for each request?
Okay, so I've managed to find out what was causing my Link object (and the parent Page object) to persist across multiple URLs.
It seems that because I'm clicking the Link which forces the "Save As" box in IE9, this keeps the Page object current, even as the browser runs through all the other URLs in the background. This seems to update the HTML rendered in the window but not release the existing Page object (or possibly creates additional Page objects in memory).
Because I'm using SendKeys() to hit the "Save" button, rather than a handled dialog in WatiN, the dialog stays open and persists the Page object.
From the looks of things, I need to find a different, handled way of performing my file downloads/saving.

Problem hiding Internet Explorer in WatiN, even when using Settings.Instance.MakeNewIeInstanceVisible = false

This question is more of a follow-up to this one:
Hiding Internet Explorer when WatiN is run
Like the person who asked that original question, I also want to stop IE from being shown when my WatiN tests are running, but even when using this setting in a seemingly correct manner (code snippet below), it still ends up showing an empty IE window initially (although it does not show the test behavior/web page interaction).
Is it possible to stop the window from showing at all, or is this as good as it gets?
My helper method to create a new IE instance:
public static IE CreateNewBrowserInstance(string url = DefaultAppUrl)
{
Settings.Instance.MakeNewIeInstanceVisible = false;
Settings.Instance.AutoMoveMousePointerToTopLeft = false;
Settings.Instance.AutoStartDialogWatcher = false;
return new IE(url, true);
}
You can Hide window after initializing new IE instance
browser.ShowWindow(NativeMethods.WindowShowStyle.Hide);

Categories