Tuesday, 18 August 2009

Automatic Birthday Scrap to Orkut friends Using WATiN

Fig 1. Flow Chart

Introduction
By using this application Orkut users can send birthday wishes scrap to their friends without fail and even without logging into Orkut site. It is just like eliminating human interaction with website while sending birthday scrap to Orkut friends without missing nearest, dearest friend’s birthdays. Just by running this application you can finish this work within seconds. You can set time to run this application on daily basis at predefined time.
Implementation
You have to add this application in your control panel scheduler with some predefined time. And at the predefined time this application will run and will do all the operation that you are supposed to do in Orkut while sending birthday scrap to your friend :)
If we run this console application, we will see an Internet Explorer browser opening and automating the entire manual process. Isn't that cool? :)

Background
I remember those days when I used to login in to Orkut to check for friends birthdays. if it’s there then I used to scrap them with best wishes. But the most difficult part is to remember friends birthdays (that’s my experience). Suppose we were not able to open Orkut on a particular day(that happen's to be my friends birthday) then it would be like we missed wishing friends. If next day we get a chance to login to orkut,then we need to send wishes with belated word :(
Then one day I thought we need to have any application which can remove our painful situation. The application should be in my control, in my hand and can take care about all this stuff. It’s like computer is working in place of me.
After struggling for few hours with my thinking, idea and knowledge I came up with an idea that why cant I develop an application which can do as per my thinking. That’s great :)
So, I would love to present an application which is replica of my knowledge/idea in c#, .Net and WATIN.

What is WATiN
WATIN, pronounced "What-in", is an acronym standing for "Web Application Testing in .Net". WATiN is a toolkit used to automate browser-based tests during web application development. This automated test tool uses the C# language to drive the Internet Explorer web browser. To know more about WATiN tool kit please refer http://watin.sourceforge.net/ link.

Using the Code
To interact with Orkut web site I have used WATIN tool as API interaction between my code and orkut web site. For programming language I used C# with .net 2.0 and I hope that you guys are familiar with WATiN.
I would prefer to explain the codes line by line so that we will get idea about How We can Use WATiN for Automation purpose as well as for other purpose like Interacting with other web site just like an API.

Flow chart: (see fig 1.)
1.
Open new instance of Internet explorer (can be in visible mode)
2. Go to http://www.orkut.com/
3. Login with predefined emailid and password.
4. Move to home page.
5. Check that any friends birthday fall today if yes then go to step 6 else step 10
6. Click at link LEAVE SCARP and go to selected friend’s scarp book.
7. Type predefined BIRTHDAY MESSAGE/WISHES and post that scrap.
8. Move back to home web page.
9. Further check for the next birthday date, if it fall today repeat step 6 to 8.
10. Click on logout link of Orkut web site.
11. On successful logout close the browser.

Now let’s put the above steps in code.

1. Open visual studio and select New project as Console application.(I assume that you are
familiar with Visual Studio2005)
2. Go to ADD reference and add WATiN.core.dll and Nunitframework.dll in your project.
3. ADD below namespace in you code file to access WATiN classes and method.

using Watin.core;
using NUnit.Framework;

4. I m using XML file to store login Emailid, Password and birthday wish. At first I thought
using APPconfig for Data information but I changed my mind to XML because XML is very
easy to maintain and easy to read through the code and best part is that anybody can easily
use this.
5. So first we will write code to read login Emailid, Password and Birthday wish
The xml file would look like this
------------- UserInputData.xml-------------------------
xml version="1.0" encoding="utf-8"?>
<root>
<UserEmailId>
<Value>jawed_ace@yahoo.com<Value>
<UserEmailId>
<UserPassword>
<Value>myPassword<Value>
<UserPassword>
<BirthdayMsg>
<Value>Wish you happy bithday.<Value>
<BirthdayMsg>
<root>
--------------------------------------------------------
//Start Reading Xml for Input data
//String variable to store data from XML file.

string[] UserInput=new string[3];
//Get the Current directory path
string xmlPath = Environment.CurrentDirectory;
//Get the xml path to read output
xmlPath = xmlPath.Replace("bin\\Debug","UserInputData.xml");
XmlTextReader reader = new XmlTextReader(xmlPath);
reader.Read();
int i=0;
/*start reading the XML file for UserEmailid,UserPassword and Birthday wishes.*/
while (reader.Read())
{
switch (reader.NodeType)
{
//Display the text in each element.
case XmlNodeType.Text:
//Console.WriteLine(reader.Value);
//store the value in string

UserInput[i] = reader.Value;
i++;
break;
}
}
//Stop reading from xml file

6. Now our actual work/Code will start. In this section we will derive internet explorer using
WATiN through login in to Orkut.
We will create a new instance of internet explorer in invisible mode. The piece of code would be
look like

//Make Internet Explorer to run in invisible mode.
IE.Settings.MakeNewIeInstanceVisible = false;
//Open an Instance of IE
IE ie = new IE();


7. Through the code we will force the instance of browser to go to orkut website by typing
http://www.orkut.com/ in address bar and do the action of go.

// Type www.orkut.com in browser.
ie.GoTo("https://www.orkut.com");
ie.WaitForComplete();
//VERIFY THAT USER HAS NOT ALREADY LOGIN INTO ORKUT
/iF YES THEN cLOSE THE PREVIOUS SESSION AND START NEW SESSION.

Assert.IsTrue(ie.Link(Find.ByText("Logout")).Exists);
ie.Frame("orkutFrame").Link(Find.ByText("Logout")).Click();
ie.WaitForComplete();

8. Now on Orkut Home page we will provide Emailid and password to corresponding emailid
field and password field. These values are already we read from XML.
I think rest of the code is self explanatory to understand as I have included comments also
to get the clear picture of the code.
---------------OrkutBirthdayScrap.cs-------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using WatiN.Core;
using NUnit.Framework;
using WatiN.Core.Interfaces;
using System.Configuration;
using System.Xml;
using System.Xml.XPath;
using System.Data;
using System.Web;
//This Class would send out Birthday Scrap to your friend
//Author: Md.Jawed
//Date: 23 july 2009
namespace BirthDayScrapOrkut
{
class Program
{
//A common use for a cross-process Mutex is to ensure
//that only instance of a program can run at a time.
//Mutex provides the same functionality as C#'s lock statement,
//making Mutex mostly redundant.
static Mutex mutex = new Mutex(false, "http://jawedm.blogspot.com");
[STAThread]
static void Main(string[] args)
{
try
{
IE.Settings.MakeNewIeInstanceVisible = false;
//Start Reading Xml for Input data
//String variable to store data from XML file.
string[] UserInput=new string[3];
//Get the Current directory path
string xmlPath = Environment.CurrentDirectory;
//Get the xml path to read out put
xmlPath = xmlPath.Replace("bin\\Debug", "UserInputData.xml");
XmlTextReader reader = new XmlTextReader(xmlPath);
reader.Read();
int i=0;
//start reading the XML file for UserEmailid,UserPassword and Birthday wishes.
while (reader.Read())
{
switch (reader.NodeType)
{
// Do some work here on the data.
case XmlNodeType.Text: //Display the text in each element.
UserInput[i] = reader.Value;
i++;
break;
}
}
//Stop reading from xml file
//Open an Instance of IE

IE ie = new IE();
// Type www.orkut.com in browser.
ie.GoTo("https://www.orkut.com");
ie.WaitForComplete();
ie.WaitForComplete(300);
//VERIFY THAT USER HAS NOT ALREADY LOGIN INTO ORKUT
//iF YES THEN cLOSE THE PREVIOUS SESSION AND START NEW SESSION.

try
{
Assert.IsTrue(ie.Link(Find.ByText("Logout")).Exists);
ie.Frame("orkutFrame").Link(Find.ByText("Logout")).Click();
ie.WaitForComplete();
}
catch (AssertionException logAex)
{
//
}
catch (WatiN.Core.Exceptions.ElementNotFoundException logWex)
{
//
}
//Type Your emailid in to emailid textbox.
ie.TextField("Email").TypeText(UserInput[0]);
//Provide your Password in password textbox.
ie.TextField("Passwd").TypeText(UserInput[1]);
//Click on signIn button to login into orkut.
ie.Button(Find.ByName("signIn")).Click();
ie.WaitForComplete();
/*get the URL of browser after click on sign In button. To verify that Login is successful or not*/
string VerifyUrl = ie.Url;
ie.WaitForComplete();
//verify that login as successful. return true
if (VerifyUrl == "http://www.orkut.co.in/Main#Home.aspx")
{
//Check that Birthday box exist on home page.
bool res = ie.Frame("orkutFrame").Div("mbox").Table(Find.ByIndex(2)).Exists;
if (res)
{
//Remember the number of user exists in Birthday Box.
int numBirthdayFriend = 0;
while ((ie.Frame("orkutFrame").Div("mbox").Table(Find.ByIndex(2)).Div(Find.ByClass("boxgrid")).Div(Find.ByIndex(numBirthdayFriend)).Exists))
{
Div birthDayDiv=ie.Frame("orkutFrame").Div("mbox").Table(Find.ByIndex(2)).Div(Find.ByClass("boxgrid")).Div(Find.ByIndex(numBirthdayFriend));
try
{
Assert.IsTrue(birthDayDiv.Div(Find.ByIndex(1)).Exists);
//Check that anyone have birthday today or not
Assert.AreEqual("leave a scrap", birthDayDiv.Div(Find.ByIndex(1)).Link(Find.ByIndex(1)).Text);
//Click on leave scrap option to leave a scrap to birthday buddy
birthDayDiv.Div(Find.ByIndex(1)).Link(Find.ByIndex(1)).Click();
ie.WaitForComplete()
/ /Very that we have landended at friend’s Scrap book page.
Assert.IsTrue(ie.Frame("orkutFrame").TextField("scrapText").Exists);
//Type a Scrap to Birthday buddy.
ie.Frame("orkutFrame").TextField("scrapText").TypeText(UserInput[2]);
//Post an Scrap.
ie.Frame("orkutFrame").Link(Find.ByText("post scrap")).Click();
//Click on Home link to return back to Orkut home page after leaving scrap into friend’s scrap book.
ie.Frame("orkutFrame").Link(Find.ByText("Home")).Click();
ie.WaitForComplete();
}
catch(AssertionException Aex)
{
Console.WriteLine(Aex.Message);
}
catch(WatiN.Core.Exceptions.ElementNotFoundException Wex)
{
//
}
numBirthdayFriend = numBirthdayFriend + 3;
}
}
else
{
Console.WriteLine("No Birthday Table Exist for the login user");
}
//Loging out from orkut.
ie.Frame("orkutFrame").Link(Find.ByText("Logout")).Click();
ie.WaitForComplete();
//Close the instance of Browser.
ie.Close();
}
else
{
//Sorry Login Unsuccessful.
//Close the browser.
ie.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

}//end of the code
What can I Learn?
My learning from this article was that WATiN is not just for Automation purpose. We can use this for API interface also. And more important is that now onwards this application is going to take care about our Orkut needs.

Conclusion
After reading this article I hope that we should know how we can use WATiN framework to test web applications and as well as how we can utilize it for API purpose. I think that we can do intensive UI and functional testing with it and of course for API use and best part is by using this application we can avoid login in to Orkut for birthday wishes.

Future plan
I would love to put the same article with setup file on code project.
http://www.codeproject.com/KB/applications/OrkutBirthdayScrap.aspx

You can download Source code from below link.
http://www.4shared.com/file/129162544/9ffcdb85/BirthDayScrapOrkut.html[^]

and for setup file you can visit below link.

http://www.4shared.com/file/129160071/687976a9/OrkutBirthdaySetUp.html[^]

Points of Interest

Successive clicks of EXE open multiple browsers and command windows (Timeout exception occurs later). To avoid this issue: I have used the concept of Mutex. A common use for a cross-process Mutex is to ensure that only instance of a program can run at a time. Mutex provides the same functionality as C#'s lock statement, making Mutex mostly redundant.

Upcoming Application On my blog
1. How to use WATiN to get defects status, logged items and many more from DIGITE after that send that generated reports through email to group of people.
2. and i have developed an Application for Automation using WATiN. my self called that application as "An Automated functional graphical user interface testing application using WATiN". currently i am using this application for automation in my project.
Thank you very much to all of you :)
Feedback/Suggestion is always welcome.
Thanks & Regards
Md. jawed
(M) +91 9986415006 (D) +91 6610 5476
Testing is an Art to execute your Knowledge, Skill and Desire.
Aditi TechnologiesThink Product http://www.aditi.com/




Friday, 14 August 2009

What is Exploratory Testing?

A very good article to read about Exploratory Testing.
http://www.satisfice.com/articles/what_is_et.shtml

My Answer(s) posted on Code Project web site Part-2

Question : How to maximize window
Hi I'm using WatiN testing tool, I have problem in maximinzing the windowi used the following codeie.ShowWindow(NativeMethod.ShowWindowStyle.Maximize)but i'm getting error: "NativeMethod does not exist in the current context "and the window is not maximized.plz help me with this..
thanking you
Jawed: Hi Friend , please use the below code to maximizg the IE window.
ie.ShowWindow(NativeMethods.WindowShowStyle.Maximize);
Thanks.

Question: How to handle javascript popup's
Hi I've scenario where i need to create users and upon successfully creating a user i get a popup with Successfully created msg and contains a "OK" button i need to click on the popup to continue further how to handle these kind of popups and also how to downlaod a file and save it. please suggest some solution.
Jawed: For Succesfully created msg popup you can use below code(if it is ALERT)
//Add this namespace for dialogHandlers
using WatiN.Core.DialogHandlers;

AlertDialogHandler alertDialogHandler = new AlertDialogHandler();
ie.DialogWatcher.Add(alertDialogHandler );
alertDialogHandler.WaitUntilExists();
alertDialogHandler.OKButton.Click();
ie.WaitForComplete();
ie.DialogWatcher.RemoveAll(alertDialogHandler);
Hope it would be usefull for you.Thanks!!

Question: Use WatiN to fill form fields in a running IE instance
Hi,Is it possible to use WatiN to interact with a running instance of IE. I'm looking for a toolset that makes it easy to fill fields (such as textboxes, comboboxes, checkboxes) in a webpage (that's part of a portal solution).Does WatiN also allow to select submenu-items on a page ? Thanx Filip!
Jawed: Hi , WATiN can perform an action similar to a tester or user is performing on any application.the action perform by WATiN tool is called as Automation yeah WATIN can allow you to select submenu-items on an application page.after writing few lines of code in WATIN using C# it can fill the required input fields like(textboxes,select combo- boxes,checked/unchecked checkbox,radio button,click on link etc etc).
please refer the below link for more information
http://watin.sourceforge.net/gettingstarted.html
Happy Automation.

Question: Re:Use WatiN to fill form fields in a running IE instance
Thanks Jawed !
But can I also hook WatiN into a running instance of IE, or not ?
Or in other words, what does the following line of code do when an other IE window is already opened?
// Open Internet Explorer window and
// goto the portal webapp
IE ie = new IE(http://www.e-notariaat.be);
Does it add another TAB or does it open a separate IE window (with seperate logon credentials) ?
In Delphi, I could do automation on a running OR new instance of e.g.
Word : try MSWord := GetActiveOleObject('Word.Application');
except MSWord := CreateOleObject('Word.Application');
end;
The problem I see (although I'm not sure) is that the website I wish to target, is a portal that requires a SmartCard-based login (+manual pin-code), and as most users have already logged in to this portal in their running IE session, I wish to hook in there too ...I haven't tried any of this, but I try to foresee how and if this would work in a typical use case of my customers...
Jawed: Thanks Filip!!Please find below my answers related to your queries.
Filip: But can I also hook WatiN into a running instance of IE, or not ?
jawed: yes you can!!!just a simple Watin code can hook the running instance of IE
IE ie = IE.AttachToIE(Find.ByUrl(url));
the above line of would take the control of already running instance of IE searching by URL.
Filip: what does the following line of code do when an other IE window is already opened?
// Open Internet Explorer window and
// goto the portal webapp
IE ie = new IE(http://www.e-notariaat.be/);
Does it add another TAB or does it open a separate IE window (with seperate logon credentials) ?
Jawed:The above line of code will open a new instance of IE browser.
Filip: The problem I see (although I'm not sure) is that the website I wish to target, is a portal thatrequires a SmartCard-based login (+manual pin-code), and as most users have already logged in tothis portal in their running IE session, I wish to hook in there too ...
Jawed: For this approach you can apply method like : Find the already running instance of IE by URL/Value/title etc and take the control of that running IE instance.for that you can use below line of code
IE ie = IE.AttachToIE(Find.ByUrl("") Find.ByClass("") Find.ById("") Find.ByName("") Find.ByTitle("") Find.ByValue(""));
Please let me know for any question/concern
Continue..
Filip: Hi Jawed,
Thanks for the answers ! Now, I am convinced that WatiN will let me do the stuff I would like to accomplish. Right now, I am enjoying a weekend in the Ardennes (in the south of Belgium) with my wife and kids, but I will give WatiN a good spin real soon.
Thanks again.
Filip





Thursday, 13 August 2009

My Answer(s) posted on Code Project web site Part-1

In this Blog i would like to share my Answers which i have posted on Code project.
reference: http://www.codeproject.com/script/Forums/Messages.aspx?fmid=4764307
Question: Can WatiN accept inputs from an Excel sheet
Can WatiN accept inputs form an excel sheet. this functionality was there in watir.
Is this available in WatiN.

Jawed: yes it is.for that you need to write simple C# code to read from excel sheet.see below
some example from my side.

public class CommonClassAutomation
{
static string connectionString
= "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=
D:/test.xls;Extended Properties=Excel 8.0;";
public static string inputText= string.Empty;

public void TC_googletest()
{


//before calling instance of browser read input from excel sheet.
readExcelsheet();
//Open instance of IE browser.
IE ie=new IE();
//Open Google.com in browser
ie.goto("www.google.com");
/*Provide input text in to google search box. which you have already having from
excel sheet.*/
ie.TextField(Find.ByName("q")).TypeText(inputText);
//Click on Search button.
ie.Button(Find.ByName("btnG")).Click();
}
//Method To read data from Excel sheet
public void readExcelsheet()
{
DbProviderFactory factory = DbProviderFactories.GetFactory
("System.Data.OleDb");
int inputCount=0;
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM ["+ sheetName+"$]";
try
{
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
if (dr.Read())
{
inputText= dr[1].ToString();
}
}
}
catch(Exception ex)
{
//To Do
}
}
}
}
}
Hope, it would be useful for you.
happy automation
Thanks,
Md.Jawed
Hi I'm working on WatiN tool. I've scenario where i need to check a checkbox and click on ok button in the popup window. i've used AttachtoIE method and used URL attribute to attach to the popup window. Now the problem is URL contains the ID value, which changes each time the popup appears.. so how to handle this or is there any other method other than AttachtoIE.
please give some suggestion thanking you.
Other Member: Yes I got it right, I ignored the query string part in the URL which used to change everytime.
for example,http://192.168.25.10:221/admin/UploadContent.aspx?opener=CustomContent_Add.aspxIn the above URL the second line is the query string which will be present after the question mark in the first line.so I used only the first line neglecting the second like this
IE popup = IE.AttachToIE(Find.ByUrl(Url, true);
this worked for me, hope this will help you
Jawed: Hi,@ninay_fz: nice reply
Just I want to add few points over here to make your piece of code to work with dynamic changing URL.In this situation is good practice to use Regular expression.
Add this name space to your code file.

using System.Text.RegularExpressions;

Use below code to generalize while accessing URL.
string Url= "http://192.168.25.10:221/admin/UploadContent.aspx";(or whatever string you want to put!!)
Regex reg = new Regex(Url);
IE popup = IE.AttachToIE(Find.ByUrl(reg , true));
Hope it would solve your problem.
Thanks,
Continue..............

Monday, 3 August 2009

Automatic Birthday scrap to your Orkut friends

This application would almost eliminate the human or user interaction to Orkut web site while sending Birthday Scarp to your Orkut friends.
Just copy this piece(wait for next blog for code) of code to your local folder. And click on .exe.
Not feeling to click on .exe :) then,
-> Go to control panel and add this application to Scheduled Tasks to run some predefined time.
And the predefined time this application would automatic run and will do the below mention steps. Even being in invisible mode :)

  1. The flow chart of this application is as below:-
    1. Open Internet explorer (optional).
    2. Go to Orkut website.
    3. Login with predefined credential.
    4. On successful login check that any friends birthday fall today.
    5. If yes. Click on leave scarp and leave a predefined birthday wishes to selected friend’s scrap book.
    6. Come back to home page.
    7. Check for the next friend birthday if his/her birthday fall today repeat steps 5 to 6.
    8. After above steps click on logout link.
    9. Logout from Orkut and close the browser.

I have developed this console application using C#, .net2.0.
And for interface with Orkut I used WATIN tool/framework 2.0.
Note: best part of this aaplication is that i m not asking your Orkut's details at all.cuz this code would be with you so,whenever you want you can stop it or run it :)
For this blog I have attached only video.
In next blog, I would like to publish the code with .exe and about the code description. Thanks!!!

My learning from this blog -: WATiN is not for Automation only. It can be used as API Interface .
Happy Orkuting :)

Thanks,
Md.Jawed