Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Automatic Birthday Scrap to Orkut Friends Using WATiN

4.80/5 (17 votes)
2 Sep 2009CPOL6 min read 62.4K   944  
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)