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/




8 comments:

Anonymous said...

wow..very useful tips you have provided here....i want to use it..thanks for that..
kristina
Cash Online Get Easy cash at your door step

Unknown said...

fantastic Jawed...awesome
i m very happy to see that you are fulfilling your dreams..still i remember those days when you was our Math Scientist:)
Thanks for nice Articles.sure i m going to use it.
keep it up..

Unknown said...

Good work jawed Hakimi...Keep it Up :)
i just love the way you have utilize WATiN apart from Automation tool...
Thank u very much for this articles and source code.
and i would love to see your Automation Application...

Anonymous said...

Hey,

When ever I surf on web I never forget to visit this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]jawedm.blogspot.com is filled with quality info. Do you pay attention towards your health?. Let me present you with one fact here. Recent Research presents that about 80% of all U.S. adults are either obese or overweight[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] Therefore if you're one of these people, you're not alone. Infact many among us need to lose 10 to 20 lbs once in a while to get sexy and perfect six pack abs. Now the question is how you are planning to have quick weight loss? Quick weight loss can be achived with little effort. Some improvement in of daily activity can help us in losing weight quickly.

About me: I am blogger of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health trainer who can help you lose weight quickly. If you do not want to go under difficult training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for effortless weight loss.

Anonymous said...

Understandably your article helped me altogether much in my college assignment. Hats high to you enter, will look ahead in behalf of more cognate articles without delay as its united of my choice subject-matter to read.

Anonymous said...

Rather interesting site you've got here. Thanks for it. I like such themes and anything connected to this matter. I definitely want to read more on that blog soon.
What do you think about changing it from time to time?

Anete Benedict
asian escorts nyc

Anonymous said...

Impressive page. Keep posting that way.

Kate Kuree
escorts in monterrey

Anonymous said...

Cool article. Keep posting that way.

Hilary Benedict
kiev ukraine escorts