Archive for the ‘Visual Studio’ Category

Hello All

In test driven development its always needed to test a particular project tested with make it isolate ( test with removing dependency from other projects ), In this scenario we virtually create the input set which will be produced from other projects(class,methods etc) and test whether our testable methods are functioning with that input set or not.

To do that we have to make mock of the dependent objects. In the example bellow I have shown how to test a business logic layer with isolating it from data access layer.I have created three projects Web.Data , Web.Core & BL.Test .

The Web.Data project contains the Data Access Layer which will be responsible for pulling data from the data source,but as we are isolating our business logic layer from this project so in the example I will not completely  implement our desired method( as it will not be executed).

To do that we need some tools such as NMock and NUnit . We will found the NMock.dll , nunit.core & nunit.framework in both of its bin folder where we extract or install those.

our Web.Data contains only two files one is IMockDAL.cs interface and MockDAL.cs class.

IMockDAL.cs interface :

using System.Collections.Generic;

namespace Web.Data
{
   public interface IMockDAL
    {
       /* The method will return a string list of
        * active member's name from data source .
        */
        List<string> GetNameListDAL(bool active);
    }
} 

MockDAL.cs Class :

using System;
using System.Collections.Generic;

namespace Web.Data
{
    public class MockDAL:IMockDAL
    {
        #region IMockDAL Members

        /* This method will not be executed during the test,
         * as we will do mock of this method.
         */
       public List<string> GetNameListDAL(bool active)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

In our Web.Core there are also two files , one is IEmployeeService.cs interface & EmployeeService.cs the class file. in this project we have to add reference of Web.Data project as it has a dependency over that.
IEmployeeService.cs  interface :

using System.Collections.Generic;
using Web.Data;

namespace Web.Core
{
   public interface IEmployeeService
    {
        IMockDAL MockDAL { set; get; }
        List<string> GetAllEmployee();
    }
}

EmployeeService.cs Class :

using System.Collections.Generic;
using Web.Data;

namespace Web.Core
{
   public class EmployeeService : IEmployeeService
    {
        /* The MockDAL property will be used to assign
         * DAL through our mock object.
         */
        public IMockDAL MockDAL { set; get; }

        public EmployeeService()
        {
            MockDAL = new MockDAL();
        }

        #region IEmployeeService Members

        /* The "GetAllEmploye" will call the "GetNameListDAL"
         * from the mock object. For the sake of simplicity
         * I just call the DAL,not did any other operation.
        */

        public List<string> GetAllEmployee()
        {
            return MockDAL.GetNameListDAL(true);
        }

        #endregion
    }
} 

In BL.Test project we have to add some reference as it have dependency over  couple of projects and DLLs . We have to add reference of Web.Data & Web.Core and we also have to add NMock.dll , nunit.core & nunit.framework .In this project we have a class file named MockTest.cs

using System.Collections.Generic;
using NMock2;
using NUnit.Framework;
using Web.Data;
using Web.Core;

namespace BL.Test
{
    [TestFixture]
    public class MockTest
    {
        /* Assign property of our object that will be executed.
         */
        public Mockery _mock;
        public IMockDAL _mockDAL;
        public IEmployeeService _employeeService; 

        [SetUp]
        public void init()
        {
            /* initializing our objects.
             */
            _mock = new Mockery();
            _mockDAL = _mock.NewMock<IMockDAL>();
            _employeeService = new EmployeeService();
            _employeeService.MockDAL = _mockDAL;

        }

        [Test]
        public void TestEmployeeCount()
        {
            /* In the list bellow we are creating our virtual list of
             * string, which we are expecting after calling the DAL
             * this list will be returned.
             */
            List<string> employeeList = new List<string>();
            string emp = "Maix";
            string emp2 = "Pain";
            employeeList.Add(emp);
            employeeList.Add(emp2);

            /* _mockDAL -> is our mocked DAL object.
             * GetNameListDAL -> is one of the method name of the _mockDAL object.
             * With(true) -> the single boolean parameter of the GetNameListDAL method.
             * employeeList -> The expecter return value from the GetNameListDAL method.
             */
            Expect.Once.On(_mockDAL).Method("GetNameListDAL").With(true).Will( Return.Value(employeeList));

            List<string> employeeListResult = _employeeService.GetAllEmployee();

            /* Verify the mock object is executed successfully with its expectation.
             */
            _mock.VerifyAllExpectationsHaveBeenMet();

            Assert.AreNotEqual(null, employeeListResult);
        }
    }
}

To make it run we can set the project as our startup project and configure the NUnit .

That’s all for the day.

BYE

User ScrumPad for your Agile based projects. 

 

Hello all

Today I will show how to test UI ( User Interfaces ) in .NET with WatiN . WatiN is UI test framework. Though its a very simple but i have felt the documentation is not rich enough with example. So i have taken an initiative to make it more userfriendly for the developers.

I will not emphasize on how to configure WatiN as its already well documented in the following links. What i will try to do is make familiar with HTML controls that’s needed to be validated .

Follow accordingly to configure WatiN :

  1. Add reference as the documentation of WatiN, you dont have to follow the example which is documented there just add the reference.
  2. If you don’t know how to add reference please see this and for NUnit see this
  3. Visit this link for a good CodeProject’s example.

One of the common mistake we do is, open a class file in our website project and start the writing the test code in it, but what we have to do is make a new Class Project ,add reference in that project & select as startup project for NUnit test.

using WatiN.Core;
using NUnit.Framework;
using WatiN.Core.DialogHandlers;

namespace TestStie
{
  [TestFixture]
  public class AddArticleTest
    {

      [TestFixtureSetUpAttribute]
        public void SetUp()
        {
        }

       [Test]
        public void TestAddArticle()
        {
            using (IE ie = new IE("http://localhost:2456/testsite/login.aspx"))
            {

                /*
                 * For textbox and textarea we have to use TextField() method and to search by
                 * id of the control we have to use Find.ById() method & to fill the textbox
                 * we have to use TypeText() method as following.
                 */

                ie.TextField(Find.ById("ctl00_UserName")).TypeText("maxpain");
                ie.TextField(Find.ById("ctl00_Password")).TypeText("c0de71~123");

                /*
                 * For make a check box cheked we have to do as following.
                 */
                ie.CheckBox(Find.ById("ctl00_chkActive")).Checked = true;

                /*
                 * To upload a file we have to do as bellow.
                 */
                ie.FileUpload(Find.ById("ctl00_LogoFile")).Set(@"C:\calligraphy.jpg");

                /*
                 * To selct a value form a dropdown list we have to follow as bellow.
                 * In the exmaple "Software Engineer" is selected item's value.
                 */
                ie.SelectList("ctl00_BodyPlaceHolder_ddlSkillCategory").Select("Software Engineer");

                /*
                 * For make a radio button cheked we have to do as following.
                 */
                ie.RadioButton(Find.ByName("ctl00$BodyPlaceHolder$rbPublish")).Checked = true;

                /*
                 * To click a link we have to do as bello
                 */
                ie.Link(Find.ByUrl("http://localhost:2456/testsite/AddArticle.aspx?id=3")).Click();

                /*
                 * To click a button we have to do as bellow.
                 */
                ie.Button(Find.ById("ctl00_LoginButton")).Click();

                /*
                 * Suppose we have to make confirm a delect action through JS confirmation box when we click
                 * a link, then we have to do as follow.
                 */
                AlertDialogHandler alertDialogHandler = new AlertDialogHandler();
                ConfirmDialogHandler confirm = new ConfirmDialogHandler();
                using (new UseDialogOnce(ie.DialogWatcher, confirm))
                {
                    Link link = ie.Link(Find.ByUrl("http://localhost:2456/testsite/AllCaseStudy.aspx?id=5"));

                    link.ClickNoWait();
                    confirm.WaitUntilExists();
                    confirm.OKButton.Click();
                }
                ie.WaitForComplete();

                /*
                 * Now to check whether our operatin is successful or not we have to do assert test
                 * as we do in unit test. Here ContainsText("xxxx") method returns true when it found
                 * the "xxxx" string in the page appear after any event perform.(generally we show
                 * a confirmation message after any successful event performed.)
                 */
                Assert.IsTrue(ie.ContainsText("News Deleted successfuly"), "Deleted id not found.");
            }
        }

        [TestFixtureTearDownAttribute]
        public void TearDown()
        {
        }
    }
}

Thats all for today.

BYE

User ScrumPad for your Agile based projects.

Hello All

Today I will demonstrate how to do Form based authentication manually.Though it can be maintained through login controls which is provided by Visual Studio but sometime we need to do the task without using those controls and the required database.

First we have to perform validation for the user, then we needed to authenticate the user for different type of task according to the role of the user ( I will do role based authentication.) In my example I have a folder named "Secure" which can be access only by the Admin user. (in the following code I assume that U have done the validation for a user.)

  /* we are taking expire time duration form application settings file you may also hard coded this value.*/

double EXPIRETIMELIMIT = Convert.ToDouble(ConfigurationManager.AppSettings["EXPIRETIMELIMIT"]);

  FormsAuthentication.Initialize();
  FormsAuthentication.HashPasswordForStoringInConfigFile("password", "md5");

  StringBuilder roles = newStringBuilder();
  /* bellow i have added 2 roles , you may add roles according to your logic.*/
  roles.Append("Admin");
  roles.Append("Manager");

  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "User Name", DateTime.Now, DateTime.Now.AddMinutes(EXPIRETIMELIMIT), true, roles.ToString(), FormsAuthentication.FormsCookiePath);
  string hash = FormsAuthentication.Encrypt(ticket);
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
/*We have to set the cookie expire time manually,its not working which we set in the parameter  of the FormsAuthenticationTicket's constructor .*/
 cookie.Expires = DateTime.Now.AddMinutes(EXPIRETIMELIMIT); 

 if(ticket.IsPersistent)
    cookie.Expires = ticket.Expiration;

 Response.Cookies.Add(cookie);

 Response.Redirect("Admin/Home.aspx");

Now open the the Global.asax file,if its not exist in your current solution add it as a new item. Then add the following code block as bellow,which will chek the authentication in each page request.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
   {
       if (HttpContext.Current.User != null)
       {
           if (HttpContext.Current.User.Identity.IsAuthenticated)
           {
               if (HttpContext.Current.User.Identity is FormsIdentity)
               {
                   FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

                   FormsAuthenticationTicket ticket = identity.Ticket;
//         UserData is the roles which we have assigned before.
                   string[] roles = ticket.UserData.Split(new Char[] {','});

                   HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);

               }
           }
       }
   }

Now its the time to securing our folder from web.config  . When any Authorized user will try to access in the Admin folder then this will check the "Admin" role for the user.

<authentication mode="Forms">
        <forms name="MYWEBAPP.ASPXAUTH"  loginUrl="TeleMarketerLogin.aspx" protection="All" path="/"/>
    </authentication>
    <authorization>
        <deny users="?"/>
        <allow roles="Manager,Admin"/>
        <deny users="*"/>
    </authorization>

<location path="Secure">
    <system.web>
        <authorization>
        <deny users="?"/>
        <allow roles="Admin"/>
        <deny users="*"/>
        </authorization>
    </system.web>
</location>

<location path="App_Themes">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>

thats all for today.
BYE

User ScrumPad for your Agile based projects.