Click here to Skip to main content
15,878,871 members
Articles / Programming Languages / C# 4.0

Automatic Birthday Scrap to Orkut Friends Using WATiN

Rate me:
Please Sign up or sign in to vote.
4.80/5 (17 votes)
2 Sep 2009CPOL6 min read 60.6K   944   26   22
By using this application, Orkut users can send birthday wishes scrap to their friends without fail and even without logging into Orkut site

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 a time to run this application on a daily basis at a 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 operations 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 happens to be my friend's birthday), then it would be like we missed wishing friends. If the next day, we get a chance to login to Orkut, then we need to send wishes with a belated word. :( Then one day I thought we need to have an application which can remove our painful situation. The application should be in my control, in my hand and can take care of all this stuff. It’s like a computer is working in place of me. After struggling for a few hours with my thinking, ideas and knowledge, I came up with an idea that I could develop an application which could do as per my thinking. That’s great. :) So, I would love to present an application which is a 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 to this 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 code line by line so that we will get an idea about how we can use WATiN for automation purposes as well as for other purposes like Interacting with other web sites just like an API.  

Flow Chart (http://jawedm.blogspot.com)  

  1. Open a new instance of Internet Explorer (can be in visible mode).
  2. Go to http://www.orkut.com/.
  3. Login with predefined email id and password.
  4. Move to Login User home page. 
  5. Check if any friends' birthday falls today, if yes, then go to step 6, else step 10 
  6. Click at link LEAVE a SCRAP and go to selected friend’s scrap book. 
  7. Type predefined BIRTHDAY MESSAGE/WISHES and post that scrap. 
  8. Move back to Login User home web page. 
  9. Further check for the next birthday date, if it falls today, repeat steps 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 Studio 2005) 
  2. Go to ADD reference and add WATiN.core.dll and Nunitframework.dll in your project.
  3. ADD below namespace in your code file to access WATiN classes and method.
    C#
    using Watin.core;
    using NUnit.Framework
  4. I'm using XML file to store login Emailid, Password and birthday wish. At first I thought of 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 the best part is that anybody can easily use this.
  5. So first we will write code to read login Emailid, Password and Birthday wish.

    Code to Read XML File for UserEmailId, Password and wish Scrap

    C#
    //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 logging in to Orkut. We will create a new instance of Internet Explorer in invisible mode. The piece of code would look like:
    C#
    //Make Internet Explorer run in invisible mode.
    IE.Settings.MakeNewIeInstanceVisible = false;
    //Open an Instance of Internet Explorer
    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 the address bar and do the action of go.
    C#
     // Type www.orkut.com in browser.
    ie.GoTo(<a href="https://www.orkut.com/">https://www.orkut.com</a>);
    ie.WaitForComplete();
    //Verify  that logout link exit.
    Assert.IsTrue(ie.Frame("orkutFrame").Link(Find.ByText("Logout")).Exists);
    //Click on logout link 
    ie.Frame("orkutFrame").Link(Find.ByText("Logout")).Click();
    ie.WaitForComplete();
    // ie.Close();
  8. Now on Orkut Home page, we will provide Emailid and password to corresponding emailid field and password field. These values are already read from XML. I think the rest of the code is self explanatory to understand as I have included comments so that you can get a clear picture of the code.
    C#
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Diagnostics;
    using WatiN.Core;
    using NUnit.Framework;
    //using WatiN.Core.Interfaces;
    using System.Configuration;
    using System.Text.RegularExpressions;
    using System.Xml;
    using System.Xml.XPath;
    using System.Data;
    using System.Web;
    using System.Threading;
    using System.Runtime.InteropServices;
    //Author: Md.Jawed
    //date: 24th July 2009
    //Description: This Application would sendout an Orkut scrap for Birthday wishes.;
    
    namespace OrkutBirthdayScrap
    {
        class OrkutBirthdayScrap
        {
            //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)
            {
                // Wait 3 seconds if contended – in case another instance
                // of the program is in the process of shutting down.
    
                if (!mutex.WaitOne(TimeSpan.FromSeconds(3), false))
                {
                    Console.WriteLine("Another instance of the app is running. Bye!");
                    return;
                }
                else
                {
                    Console.WriteLine("Automatic Birthday Scrap to Orkut 
    		friends Using WATiN Is Running!!! Please visit 
    		http://jawedm.blogspot.com for more information");
                    
                    //make the browser in invisible mode
                    // IE.Settings.MakeNewIeInstanceVisible = false;
                    //Open an Instance of IE
                    IE ie = new IE();
                    //declare an string to store value from xml
                    string[] UserInput = new string[3];
    
                    try
                    {
    
                        //Read from XML file 
                        //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.
                                    //store value in variable after 
    			     //reading from XML node by node.
                                    UserInput[i] = reader.Value;
                                    i++;
                                    break;
                            }
                        }
                    }
                    catch (Exception Gex)
                    {
                        ie.Close();
                        Console.WriteLine("Some problem has occured.
    			Please Run this application once again");
    
                    }
                    //Stop reading from XML file
    
                    //IE.Settings.MakeNewIeInstanceVisible = false;                
                    //VERIFY THAT USER HAS NOT ALREADY LOGIN INTO ORKUT
                    //iF YES THEN cLOSE THE PREVIOUS SESSION AND START NEW SESSION.
    
                    try
                    {
                        // Type www.orkut.com in browser.
                        ie.GoTo("https://www.orkut.com");
                        ie.WaitForComplete();
                        //Verify  that logout link exit.
                        Assert.IsTrue(ie.Frame("orkutFrame").Link
    				(Find.ByText("Logout")).Exists);
                        //Click on logout link 
                        ie.Frame("orkutFrame").Link(Find.ByText("Logout")).Click();
                        ie.WaitForComplete();
                        // ie.Close();
                    }
    
                    catch (Exception ex)
                    {
                        //
                    }
                    try
                    {
                        //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();
                        string VerifyUrl = ie.Url;
    
                        //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 exist in BirthdayBox. 
                                int numBirthdayFriend = 0;
                                Div birthDayDiv = ie.Frame("orkutFrame").
                                Div("mbox").Table(Find.ByIndex(2)).Div
                                (Find.ByClass("boxgrid")).Div(Find.ByIndex
    						(numBirthdayFriend));
    
                                while ((ie.Frame("orkutFrame").Div("mbox").
                                Table(Find.ByIndex(2)).Div(Find.ByClass("boxgrid")).
                                Div(Find.ByIndex(numBirthdayFriend)).Exists))
                                {
                                    if (ie.Frame("orkutFrame").Div("mbox").
                                    Table(Find.ByIndex(2)).Div(Find.ByClass("boxgrid")).
                                    Div(Find.ByIndex(numBirthdayFriend)).Div
    							(Find.ByIndex(1)).
                                    Link(Find.ByIndex(1)).Exists)
                                    {
                                        Assert.IsTrue(ie.Frame("orkutFrame").
                                        Div("mbox").Table(Find.ByIndex(2)).
                                        Div(Find.ByClass("boxgrid")).
                                        Div(Find.ByIndex(numBirthdayFriend)).
    				Div(Find.ByIndex(1)).Exists);
                                        //Check if any one has a birthday today or not
                                        Assert.AreEqual("leave a scrap", 
    				ie.Frame("orkutFrame").Div("mbox").
                                        Table(Find.ByIndex(2)).Div
    					(Find.ByClass("boxgrid")).
                                        Div(Find.ByIndex(numBirthdayFriend)).
    				Div(Find.ByIndex(1)).
    				Link(Find.ByIndex(1)).Text);
                                        //Click on leave scrap option to 
    				//leave a scrap to birthday buddy
                                        ie.Frame("orkutFrame").Div("mbox").
                                        Table(Find.ByIndex(2)).
    				Div(Find.ByClass("boxgrid")).
                                        Div(Find.ByIndex(numBirthdayFriend)).
    				Div(Find.ByIndex(1)).Link(Find.ByIndex(1)).
    				Click();
                                        ie.WaitForComplete();
                                        //Verify that we have landed at Scrap 
    				//book of birthday buddy page.
                                        Assert.IsTrue(ie.Frame("orkutFrame").
                                        TextField("scrapText").Exists);
                                        //Type a Scrap to Birthday buddy.
                                        ie.Frame("orkutFrame").TextField("scrapText").
    					TypeText(UserInput[2]);
                                        //Post  Scrap.
                                        ie.Frame("orkutFrame").Link(Find.ByText
    					("post scrap")).Click();
                                        ie.WaitForComplete();
                                        //Click on Home link to return back to 
    				//home page after leaving scrap for friend.
                                        ie.Frame("orkutFrame").Link(Find.ByText
    						("Home")).Click();
                                        ie.WaitForComplete();
                                    }
                                    numBirthdayFriend = numBirthdayFriend + 3;
                                }
                            }
                            else
                            {
                                Console.WriteLine("Sorry Today you don't 
    					have any friend's birthday");
                            }
                            ie.Frame("orkutFrame").Link(Find.ByText("Logout")).Click();
                            ie.WaitForComplete();
                            ie.Close();
                        }
                        else
                        {
                            //Sorry Login Unsuccessful.
                            ie.Close();
                        }
                    }
                    catch (AssertionException Aex)
                    {
                        ie.Close();
                    }
                    catch (WatiN.Core.Exceptions.ElementNotFoundException Wex)
                    {
                        ie.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Some problem has occured.
    				Please Run this application once again");
                        ie.Close();
                    }
    
                    Process.GetCurrentProcess().Kill();
                }
                mutex.ReleaseMutex();
            }
        }
    }

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.  

What Did I Learn? 

My learning from this article was that WATiN is not just for automation purposes. We can use this for Driver/API interface also. And more important is that now onwards this application is going to take care of our Orkut needs.

Conclusion 

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

Upcoming Application 

  1. How to use WATiN to get/generate defects status, logged items and many more from DIGITE and send those generated reports through email to a group of people. 
  2. I have developed an Application for Automation using WATiN myself and 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.  

Note: I have included ReadMe file also with this OrkutBirthdayScrap.zip file which guides you on how to use this application.

You can visit my blog for more and recent developed applications using WATiN @ http://jawedm.blogspot.com.

History

  • 29th August, 2009: Initial post
  • 31st August, 2009: Uploaded setup file and modified source code
  • 1st September, 2009: Uploaded setup file with invisible mode functionality

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
http://jawedm.blogspot.com

Contact me for Freelancing at jawed.ace@gmail.com
Free to go anywhere,ready to learn anything...

Comments and Discussions

 
GeneralThis code doesn't work for me Pin
vernicht23-Aug-10 9:21
vernicht23-Aug-10 9:21 
QuestionWATIN Failes on Win2003+IE8. Any Insights? Pin
Hertzel Karbasi21-Feb-10 12:40
Hertzel Karbasi21-Feb-10 12:40 
AnswerRe: WATIN Failes on Win2003+IE8. Any Insights? Pin
kedde12-Mar-10 20:44
kedde12-Mar-10 20:44 
Generalhelp Pin
akshay_ms20-Jan-10 19:21
akshay_ms20-Jan-10 19:21 
AnswerRe: help Pin
jawed.ace22-Jan-10 21:20
jawed.ace22-Jan-10 21:20 
GeneralRe: help Pin
akshay_ms23-Jan-10 3:16
akshay_ms23-Jan-10 3:16 
Thank you for replying.

What i am asking is that using watin can i open my email account in invesible mode(as in your article) and copying the contents of mail to notepad(like).

Thanks in advance.
GeneralGood Work Pin
Abinash Bishoyi12-Jan-10 21:14
Abinash Bishoyi12-Jan-10 21:14 
AnswerRe: Good Work Pin
jawed.ace22-Jan-10 21:15
jawed.ace22-Jan-10 21:15 
GeneralGood work.. Pin
jijopaul19-Sep-09 19:38
jijopaul19-Sep-09 19:38 
AnswerRe: Good work.. Pin
jawed.ace21-Sep-09 8:16
jawed.ace21-Sep-09 8:16 
GeneralMy vote for 5 Pin
sanu12431-Aug-09 21:33
sanu12431-Aug-09 21:33 
GeneralRe: My vote for 5 Pin
jawed.ace13-Sep-09 9:34
jawed.ace13-Sep-09 9:34 
QuestionOrkutBirthdayScrap.cs missing from solution? Pin
RK KL31-Aug-09 4:58
RK KL31-Aug-09 4:58 
AnswerRe: OrkutBirthdayScrap.cs missing from solution? Pin
jawed.ace31-Aug-09 6:30
jawed.ace31-Aug-09 6:30 
AnswerRe: OrkutBirthdayScrap.cs missing from solution? Pin
jawed.ace31-Aug-09 9:49
jawed.ace31-Aug-09 9:49 
GeneralMy vote 5 Pin
anjaliindia30-Aug-09 10:12
anjaliindia30-Aug-09 10:12 
GeneralRe: My vote 5 Pin
jawed.ace13-Sep-09 9:37
jawed.ace13-Sep-09 9:37 
GeneralExcellent work Pin
Imtiyaz8430-Aug-09 5:14
Imtiyaz8430-Aug-09 5:14 
GeneralRe: Excellent work Pin
jawed.ace13-Sep-09 9:38
jawed.ace13-Sep-09 9:38 
GeneralJava Applet Pin
Junaid Raza29-Aug-09 10:13
Junaid Raza29-Aug-09 10:13 
GeneralMy vote of 1 Pin
Henry Minute29-Aug-09 10:12
Henry Minute29-Aug-09 10:12 
GeneralRe: My vote of 1 Pin
jawed.ace29-Aug-09 10:48
jawed.ace29-Aug-09 10:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.