Archive for the ‘.NET’ Category

Cellular automaton in .NET

Tuesday, June 30th, 2009

What is a cellular automata (CA). A cellular automaton is a discrete model studied in computability theory, mathematics, theoretical biology and microstructure modeling. It consists of a regular grid ofcells, each in one of a finite number of states, such as “On” and “Off” (1 nad 0, alive or death). The grid can be in any finite number of dimensions. For each cell, a set of cells called its neighborhood (usually including the cell itself) is defined relative to the specified cell. For example, the neighborhood of a cell might be defined as the set of cells a distance of 2 or less from the cell.

Some specific CA are:

Here is an sample of Conway’s Game of Life in C#. This is a pattern for Game of Life:

Every cell interacts with its eight neighbours, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

  1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
  2. Any live cell with more than three live neighbours dies, as if by overcrowding.
  3. Any live cell with two or three live neighbours lives on to the next generation.
  4. Any dead cell with exactly three live neighbours becomes a live cell.
We will create abstract class: RuleSet
class: RuleSet
using System;
using System.Collections.Generic;
using System.Text;

namespace GameOfLife
{
    public abstract class RuleSet
    {
        protected int _maxX = 0;
        protected int _maxY = 0;
        protected int[,] _field;

        public RuleSet(int [,] field, int maxX, int maxY)
        {
            _field = field;
            _maxX = maxX;
            _maxY = maxY;
        }

        protected int  GetNumberOfNeighbors(int x, int y)
        {

            int neighbors = 0;
            int xPos;
            int yPos;
            for (xPos= x -1; xPos < = x +1; xPos ++)
            {
                for (yPos= y -1; yPos <= y +1; yPos ++)
                {
                    if(xPos == x && yPos == y) continue;

                    if (xPos < _maxX &&  xPos >=0 && yPos < _maxY && yPos >=0 & _field[xPos, yPos] == 1)
                    {
                        neighbors++;
                    }     

                }
            }

            return neighbors;
        }

        public void GetNewState()
        {
            int [,] field2 = NewStateAlgorithm();
            Array.Copy(field2, _field, field2.Length);
        }

        protected abstract int[,] NewStateAlgorithm();
    }
}

Then we create our concrete class for “Game of Live” inherited from base class:
class: ConwaysGameOfLife

using System;
using System.Collections.Generic;
using System.Text;

namespace GameOfLife
{
    public class ConwaysGameOfLife : RuleSet
    {
       public ConwaysGameOfLife(int[,] field, int maxX, int maxY)
            : base(field, maxX, maxY)
        {

        }

        protected override int[,] NewStateAlgorithm()
        {
            int[,] field2 = new int[_maxX, _maxY];

            for (int y = 0; y < _maxY; y++)
            {
                for (int x = 0; x < _maxX; x++)
                {
                    int neighbors = GetNumberOfNeighbors(x, y);
                    if (neighbors == 3)
                    {
                        // cell is born.
                        field2[x, y] = 1;
                        continue;
                    }

                    if (neighbors == 2 || neighbors == 3)
                    {
                        // cell continues.
                        field2[x, y] = _field[x, y];
                        continue;
                    }

                    // cell dies.
                    field2[x, y] = 0;
                }
            }

            return field2;
        }
    }
}

And we have all we need. Now create Simple Windows Console application to run this:

using System;
using System.Collections.Generic;
using System.Text;

namespace GameOfLife
{
    class Program
    {
        private const char cellImage = 'o';
        private const int maxWidth = 80;
        private const int maxHeight = 60;
        private static int[,] field = new int[maxWidth, maxHeight];

        static void DrawCell()
        {
            Console.CursorLeft = 0;
            Console.CursorTop = 0;

            for( int y = 0; y < maxHeight; y ++)
            {
                for( int x = 0; x < maxWidth; x ++)
                {
                    Console.Write(field[x, y] == 1 ? cellImage : ' ');
                }
                Console.WriteLine();
            }
        }

        static void Main(string[] args)
        {

            int startX = maxWidth / 2;
            int startY = maxHeight / 2;

            Console.SetWindowSize(maxWidth + 10, maxHeight + 10);
            Console.SetWindowPosition(0, 0);

           for (int x = 0; x < maxWidth; x++)
            {
                field[x, startY] = 1;
            }
            for (int y = 0; y < maxHeight; y++)
            {
                field[startX, y] = 1;
            }

            RuleSet gameOfLife = new ConwaysGameOfLife(field, maxWidth, maxHeight);
            for (int i = 0; i < 5000; i++)
            {
                DrawCell();
                gameOfLife.GetNewState();
                Console.WriteLine(i);
            }

        }
    }
}

and here is result. This is initila state for our “automata”.
Cellular Automata - Game of Live, Initial state
and this is how it looks after 10 iterations:
Cellular Automata - Game of Life after 10 iterations.

Illustrated C# 2008 - free ebook

Thursday, April 16th, 2009

If you want to learn C#, here is a great free pdf book for you. This is very good book for programmers beginners. Enjoy!
More about book…

C# - Parallel Computing

Wednesday, April 15th, 2009

Concurrent programming in C# - Parallel.Do method

This is a simple example of concurrent programming in C#. I will discuss about Do method. This example use Parallel Extensions to the .NET published in December 2007, so this is not up to date article. This extension provides System.Threading namespace and Class Parallel. We will use here it’s method Do.

public static void Do(
	params Action[] actions
)

This method “executes each of the provided actions inside a discrete, asynchronous task”. It doesn’t
finishes until each of provided actions has completed. That means, it will finish when the slowest action finishes. For example let’s imagine
that we have 2 long running methods called method1() and method2(). If you call them in sequential manner we’ll need to
wait until method1() finishes its job, then w’ll wait method2() finishes its job. But if we run them in parallel we’ll only need to wait as much as the longest of this two methods is executing. Let’s see an example.

    public class ParalellDemo
    {
        private static double x = 1000000000;

        private static void method1()
        {
              for (double i = 0; i < x; i++) ;
        }

       private static void method2()
        {
              for (double i = 0; i < x; i++) ;
        }

        static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            // *** sequential
            method1();
            method2();
            watch.Stop();

            Console.WriteLine("Not parallel: " +
                              (watch.ElapsedMilliseconds / 1000.0).ToString() +
                              "s");

            watch.Reset();
            watch.Start();
            // *** parallel
            Parallel.Do(() => method1(), () => method2());
            watch.Stop();

            Console.WriteLine("Parallel: " +
                              (watch.ElapsedMilliseconds / 1000.0).ToString() +
                              "s");
        }
    }

After starting this little demo, the time which you get running the above program, depends about your computer CPU. On my computer (Core 2 Duo, 2.49GHz, 3GB Ram) I get this result:

parallel-fx

parallel-fx


That’s all for now. For you who want some more, please read about an excellent extension for .NET - ParallelFX.
More links:

Create n-th layer app in .NET

Saturday, April 11th, 2009

I will create an example and we go through it. Suppose we have a task to display on some web page data from table customers.

at the moment I will not take care about database. let’s say that database already exists, tables and data are there. We can do this task very quickly. It is not some big deal. We will open connection to database, read data from table, display data and close connection.
all of that can be put in one class. Bu the question is: “Is that really good practice?” in my favorite C# I will write down some code. To follow me, create an empty ASP.NET project in your Visual Studio ( I use VS2005)and choose C# for language.
There is Default.aspx page in your solution. Add GridView control (drag and drop from Toolbox). Call your grid view as: “grdCustomers“.
Edit Default.aspx.cs file:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

namespace Customers
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strConnection = null;
            string strSQL = "select customerID, customerName, customerContact from Customers ";

            strConnection = "server=DB_SERVER_NAME; initial catalog=TestDB; user=usernameValue; password=passwordValue";
            DataSet ds = new DataSet();

            SqlConnection conn = new SqlConnection(strConnection);
            conn.Open();

            SqlDataAdapter da = new  SqlDataAdapter(strSQL, conn);
            da.Fill(ds);

            grdCustomers.DataSource = ds;
            grdCustomers.DataBind();

            conn.Close();
        }
    }
}

and when we start web app with “F5″ button, we get this on the screen:


What is wrong with this? This is working, right. What if we need an other web page to display Employees. The most of the previous code will be the same except the sql query; and we will have the copy paste in our application which is bad. The other problem is sql server connection string which is hardcoded. First we will put sql connection string into configuration: Web.Config.
Edit web config to looks like this:

< ?xml version="1.0"?>

and after that, change your Default.aspx.cs code. This line:

            strConnection = "server=DB_SERVER_NAME; initial catalog=TestDB; user=usernameValue; password=passwordValue";

Chamge with this one:

            strConnection = ConfigurationManager.ConnectionStrings["SQLServerConnStr"].ConnectionString;

That is better. Now we do not need to think about sql server, its location or username/password. When we move our application to some other server, we only need to edit web.config file. No “building” necessary at all. But this can make some problem letter. If in the future Microsoft publish some better way for reading from web config we will need to change our code and recompile it again. To avoid this I will create one new project which will be used in entire solution for reading from web.config.

Create new project, type of Class library, language C#. Call it: “WebCommon“. Renamce Class1.cs to Configuration.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace WebCommon
{
    public static class Configuration
    {
        public static string ReadSqlConfiguration
        {
             get
             {
                return ConfigurationManager.ConnectionStrings["SQLServerConnStr"].ConnectionString;
             }
        }
    }
}

You need to add System.Configuration reference to this WebCommon project.

When this is done, now get back to our web project and add reference to WebCommon project.
this is how Default.aspx.cs looks after modification:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;
using WebCommon;

namespace Customers
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strConnection = null;
            string strSQL = "select customerID, customerName, customerContact from Customers ";

            strConnection = WebCommon.Configuration.ReadSqlConfiguration();
            DataSet ds = new DataSet();

            SqlConnection conn = new SqlConnection(strConnection);
            conn.Open();

            SqlDataAdapter da = new  SqlDataAdapter(strSQL, conn);
            da.Fill(ds);

            grdCustomers.DataSource = ds;
            grdCustomers.DataBind();

            conn.Close();
        }
    }
}

This is how we read from web.config now:

         strConnection = WebCommon.Configuration.ReadSqlConfiguration();

we need this using directive:

         using WebCommon;

Now we will separate our presentation layer and data access layer. Data access layer will deal with database. Create new Project, type of class Library, language C#. Call it: “DAL” Data Access Layer. Rename Class1.cs to Helper.cs
Enter this code to Helper.cs

using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public class Helper
    {
        public DataSet GetDataSet(string strSql, string strSqlServerConnection)
        {
            DataSet ds = new DataSet();

            SqlConnection conn = new SqlConnection(strSqlServerConnection);
            conn.Open();

            SqlDataAdapter da = new  SqlDataAdapter(strSql, conn);
            da.Fill(ds);             

            conn.Close();
            return ds;
        }
    }
}

There is a public method GetDataSet(string strSql, string strSqlServerConnection) which executes sql query and return populated data set.
Now add reference to this project to our web project and modify Default.aspx.cs:

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;
using WebCommon;
using DAL;

namespace Customers
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataSet ds;
            string strSQL = "select customerID, customerName, customerContact from Customers ";

            DAL.Helper objHelper = new DAL.Helper();
            ds = objHelper.GetDataSet(strSQL, WebCommon.Configuration.ReadSqlConfiguration);

            grdCustomers.DataSource = ds;
            grdCustomers.DataBind();
        }
    }
}

This is code in code behind of Default.aspx page. As you can see there is a less code than in the begining. If we need some other page to display similiar info like employees, we will create new page and put some code like this:

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;
using WebCommon;
using DAL;

namespace Customers
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataSet ds;
            string strSQL = "select employeID, employeeName, employeeAddress, zipCode, COuntry from Employees";

            DAL.Helper objHelper = new DAL.Helper();
            ds = objHelper.GetDataSet(strSQL, WebCommon.Configuration.ReadSqlConfiguration);

            grdCustomers.DataSource = ds;
            grdCustomers.DataBind();
        }
    }
}

If I think a litle bit more I will decide to remove this sql queries from my web project. web project should be presentation layer and there we only use information for publishing or perform some actions. I will create one more Layer for some business logic and derision making. It will be BL(Business Layer)

Create new Project, type of class Library, call it BL and renamce Class1.cs to Customers.cs and put this code there.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using WebCommon;
using DAL;

namespace BL
{
    public class Customers
    {
        public DataSet GetCustomers()
        {
            DataSet ds;
            string strSQL = "select customerID, customerName, customerContact from Customers ";

            DAL.Helper objHelper = new DAL.Helper();
            ds = objHelper.GetDataSet(strSQL, WebCommon.Configuration.ReadSqlConfiguration);
            return ds;
        }

        public int UpdateCustomer()
        {
            // to do
            return 0;
        }

        public int DeleteCustomer(int customerID)
        {
            // to do
            return 0;
        }

    }
}

You need to add references to “WebCommon” and to “DAL” in “BL” project. And now modify Web project. Remove reference to DAL and WebCommon and add reference to BL.
edit Default.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;
using BL;

namespace Customers
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataSet ds;

            BL.Customers objCustomers = new BL.Customers();
            ds = objCustomers.GetCustomers();

            grdCustomers.DataSource = ds;
            grdCustomers.DataBind();
        }
    }
}

Now our presentation layer, GUI or web form doesn’t know about data sources. All data it will get from BL. Just call proper method of BL. In BL project we can add more classes for Employees, Customers, Orders, …
DAL (Data Access Layer) is used to provide information.
that is all for now. Have a good day.

MVC ASP.NET VS2008 - quick overview

Monday, March 30th, 2009

There is a template for Visual Studio 2008 for MVC template. You can download it from here. After Installation, run VS 2008 and create new project.

VS2008 asks you about test project for your solution:

You can choose test project name and testing framework. And ‘voila’. This is you solution explorer and you can find bunch of some files there.


Some basic functionality is already there. “Home” and “About” pages and “Login” and “Register” functionality is created too.

The LINQ (Language-Integrated Query)

Wednesday, March 25th, 2009

LINQ is a combination of namespaces and C# 3.0 language enhancements. LINQ provides a high-level abstraction of virtually any data and emulates the query operations of the relational model. The LINQ Project seems to be just the beginning of many other future dramatic enhancements to .NET and .NET languages.

LINQ has three major components:

  1. LINQ to Objects
  2. LINQ to ADO.NET, which includes
    • LINQ to DataSet (originally called LINQ over DataSet) LINQ to Entities
    • LINQ to SQL (originally called DLinq)
  3. LINQ to XML (originally called XLinq)
To start playing with LINQ, first install it from here.

and here is sample of code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;

namespace Linq
{

[Table]
public class Customers
{
[Column(Id=true)]
public string customerId;
[Column]
public string companyName;
[Column]
public string city;
[Column]
public string country;
}

class Program
{
static void Main(string[] args)
{
// connection string
string connString = @"server = .\sqlexpress;integrated security = true; database = northwind ";
// create data context
DataContext db = new DataContext(connString);

// create typed table
Table customers = db.GetTable();

// query database
var custs =
from c in customers
select
c
;

// display customers
foreach (var c in custs)
Console.WriteLine(
"{0} {1} {2} {3}",
c.customerId,
c.companyName,
c.city,
c.country
);
}
}
}

ahd that is all.

ASP.NET MVC 1.0 now Live!

Friday, March 20th, 2009

ASP.NET MVC 1.0 finally published. You can download it from here. For tutorials, videos, and more please check out the official site.
more about asp.net mvc you can read on other blogs:
here:
ASP.NET MVC 1.0 now Live! and Free ASP.NET MVC eBook Tutorial.

MVC - Model-View-Controller

Friday, March 13th, 2009

Model–View–Controller (MVC) is an architectural pattern used in software engineering. It allows software developers to build a Web application as a composition of three roles: Model, View and Controller. A Model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View extracts necessary information from a model and renders a user interface to display that”.<br/>

Here is the code for simple Calculator application written in Java which is organized according the the Model-View-Controller (MVC) pattern.<br/>

The main program initializes everything and ties everything together.

Main.java:

import javax.swing.*;

public class Main{
    public static void main(String[] args) {

        CalcModel      model      = new CalcModel();
        CalcView       view        = new CalcView(model);
        CalcController controller = new CalcController(model, view);

        view.setVisible(true);
    }
}

here is the View class:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class CalcView extends JFrame {
    private static final String INITIAL_VALUE = "1";

    private JTextField m_userInputTf = new JTextField(5);
    private JTextField m_totalTf     = new JTextField(20);
    private JButton    m_multiplyBtn = new JButton("Multiply");
    private JButton    m_clearBtn    = new JButton("Clear");

    private CalcModel m_model;

    CalcView(CalcModel model) {
        m_model = model;
        m_model.setValue(INITIAL_VALUE);

        m_totalTf.setText(m_model.getValue());
        m_totalTf.setEditable(false);

        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.add(new JLabel("Input"));
        content.add(m_userInputTf);
        content.add(m_multiplyBtn);
        content.add(new JLabel("Total"));
        content.add(m_totalTf);
        content.add(m_clearBtn);

        //... finalize layout
        this.setContentPane(content);
        this.pack();

        this.setTitle("Simple Calc - MVC");

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    void reset() {
        m_totalTf.setText(INITIAL_VALUE);
    }

    String getUserInput() {
        return m_userInputTf.getText();
    }

    void setTotal(String newTotal) {
        m_totalTf.setText(newTotal);
    }

    void showError(String errMessage) {
        JOptionPane.showMessageDialog(this, errMessage);
    }

    void addMultiplyListener(ActionListener mal) {
        m_multiplyBtn.addActionListener(mal);
    }

    void addClearListener(ActionListener cal) {
        m_clearBtn.addActionListener(cal);
    }
}

Here is the Controller class:

import java.awt.event.*;

public class CalcController {

    private CalcModel m_model;
    private CalcView  m_view;

    CalcController(CalcModel model, CalcView view) {
        m_model = model;
        m_view  = view;

        view.addMultiplyListener(new MultiplyListener());
        view.addClearListener(new ClearListener());
    }

    /*
     *  1. Get the user input number from the View.
     *  2. Call the model to mulitply by this number.
     *  3. Get the result from the Model.
     *  4. Tell the View to display the result.
     * If there was an error, tell the View to display it.
     */
    class MultiplyListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String userInput = "";
            try {
                userInput = m_view.getUserInput();
                m_model.multiplyBy(userInput);
                m_view.setTotal(m_model.getValue());

            } catch (NumberFormatException nfex) {
                m_view.showError("Bad input: '" + userInput + "'");
            }
        }
    }
    class ClearListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            m_model.reset();
            m_view.reset();
        }
    }
}

and here is the Model class:

import java.math.BigInteger;

public class CalcModel {

    private static final String INITIAL_VALUE = "0";

    private BigInteger m_total;  // The total current value state.

    CalcModel() {
        reset();
    }

    public void reset() {
        m_total = new BigInteger(INITIAL_VALUE);
    }

    public void multiplyBy(String operand) {
        m_total = m_total.multiply(new BigInteger(operand));
    }

    public void setValue(String value) {
        m_total = new BigInteger(value);
    }

    public String getValue() {
        return m_total.toString();
    }
}

and here is the result:
Calculator MVC Model

have a nice day :)

Unit testing with Mock Objects

Friday, February 27th, 2009

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A developer creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.

We use Mock object for NUnit testing if we have 2, 3 or more layer architecture.
In programming terms mock objects are objects that “imitate” some other objects, claiming to have the same attributes, methods etc. like the original.

Rhino Mocks allows you to easily create mock objects and setup a wide range of expectations on them using strongly typed notation instead of compiler-opaque strings.

To mock an object, its class MUST implement an interface.

Public class Car : ICar
{
  public int StartEngine();
  …
  // More methods to be implemented
}
MockRepository mockRepository = new MockRepository();

MyCar = mockRepository.CreateMock<ICar>();

Here is the scenario and source code in C# for demonstration.

We have one solution and 2 projects, representing 2 layers.
Project: DataLayer which gets some information from xml file, database or some other web service, …
DataLayer project has one class: PersonDAL.

using System;
using System.Collections.Generic;
using System.Text;

namespace DataLayer
{
    public class PersonDAL
    {
        private string _name;
        private string _id;
        private List
 lista = new List
();

        public PersonDAL(string name, string id)
        {
            _name = name;
            _id = id;
        }

        public List
 CreateList()
        {

            lista.Add(new PersonDAL("Peter", "1"));
            lista.Add(new PersonDAL("George", "2"));
            lista.Add(new PersonDAL("Michael", "3"));

            return lista;
        }

        public PersonDAL GetPersonByID(string id)
        {
            PersonDAL result = new PersonDAL("", "");
            result = null;

            foreach (PersonDAL person in lista)
            {
                if (person.ID == id)
                {
                    result = person;
                    break;
                }
            }
            return result;
        }

        public string ID
        {
            get { return _id; }
        }
        public string Name
        {
            get { return _name; }
        }

    }
}

it is a simple class which gets data from some resource. In this case, data are hardcoded but never mind.
The other project is BusinessLayer, it represents some business logic. It is Layer 2.
Person class:

using System;
using System.Collections.Generic;
using System.Text;

using DataLayer;

namespace BusinessLayer
{
    public class Person
    {
        public string _id;
        public string _name;  

        public Person(string id, string name)
        {
            _id = id;
            _name = name;
        }

    }
}

interface IPersonService:

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessLayer
{
    public interface IPersonService
    {
        List
 GetPersons();

        Person GetPersonByID(string id);
    }
}

and PersonService class:

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessLayer
{
    public class PersonService : IPersonService
    {

        DataLayer.PersonDAL person = new DataLayer.PersonDAL("", "");        

        public List
 GetPersons()
        {
            List
 list = new List
();

            foreach (DataLayer.PersonDAL  objPerson in person.CreateList())
            {
                list.Add(new Person(objPerson.ID, objPerson.Name));
            }

            return list;
        }

        public Person GetPersonByID(string id)
        {
            return new Person(person.GetPersonByID(id).ID,person.GetPersonByID(id).Name);
        }
    }
}

Ok, that is part of some huge application. Let’s code some Unit test here. Supose we do not have data resource at this moment and we can not test this with real data. We must fake it.
So, create new project, type of Class Library into this solution and call it: Test
Add references for both projects and references for NUnit.Framework and
Rhino.Mocks. This project for now has only one class. We use it for testing.
PersonServiceTest class:

 using System;
using System.Collections.Generic;
using NUnit.Framework;
using Rhino.Mocks;

using BusinessLayer;
using DataLayer;

[TestFixture]
public class PersonServiceTest
{

    [SetUp]
    public void TestInit()
    {

    }

    [Test]
    public void Test()
    {
        MockRepository mockRepository = new MockRepository();
        IPersonService personRepository = mockRepository.CreateMock();

        Person mockPerson = new Person("1", "Milan");
        Person objPerson;

        Expect.Call(personRepository.GetPersonByID("1")).Return(mockPerson);

        mockRepository.ReplayAll();

        objPerson = personRepository.GetPersonByID("1");
        Assert.AreEqual(objPerson._id, mockPerson._id);
    }
}

NUnit testing

Friday, February 6th, 2009

What Is Unit test?

A unit test verifies that a function or set of functions meet the requirements.  Unit tests inspect both black boxes or white boxes. NUnitis a unit-testing framework for all .Net languages.
Here is an example. Let’s take a look this class:

namespace Bank
{
    public class Account
    {
        private float balance;

        public void Deposit(float amount)
        {
            balance += amount;
        }
        public void Withdraw(float amount)
        {
            balance -= amount;
        }
        public void TransferFunds(Account destination, float amount)
        {
            destination.Deposit(amount);
            Withdraw(amount);

        }
        public float Balance
        {
            get { return balance; }
        }
    }
}

for this class we make corresponding unit test class like this:

using NUnit.Framework;
using Bank;

namespace Test
{
    [TestFixture]
    public class AccountTests
    {
        [Test]
        public void TestTransferFunds()
        {
            Account source = new Account();
            source.Deposit(200.00F);
            Account destination = new Account();
            destination.Deposit(150.00F);

            source.TransferFunds(destination, 100.00F);

            //Here are assertions
            //we check actual value with expected value
            Assert.AreEqual(250.00F, destination.Balance);
            Assert.AreEqual(100.00F, source.Balance);

        }
  }
}

Assertions are central part of unit testing in any of the xUnit frameworks. NUnit provides a rich set of assertions as static methods of the Assert class.
Example:
Assert.AreEqual( int expected, int actual );
There are:

  • StringAssert
  • CollectionAssert
  • FileAssert

From version 2.0 on, NUnit has used custom attributes.
All NUnit attributes are contained in the NUnit.Framework namespace. Each source file that contains tests must include a using statement for that namespace and the project must reference the framework assembly, nunit.framework.dll.

SetUpFixture Attribute

This is the attribute that marks a class that contains the one-time setup or teardown methods for all the test fixtures under a given namespace. The class may contain at most one method marked with the SetUpAttribute and one method marked with the TearDownAttribute.
Example:

[SetUpFixture]
public class MySetUpClass
{
  [SetUp]
  RunBeforeAnyTests()
  {
    // ...
  } 

  [TearDown]
  RunAfterAnyTests()
  {
    // ...
  }
}

Test Attribute (NUnit 2.0)

The Test attribute marks a specific method inside a class that has already been marked as a TestFixture, as a test method. The signature for a test method is defined as follows:
public void MethodName()

Example:

[Test]
public void Add()
{
	 /* ... */
}

SetUpAttribute

This attribute is used inside a TestFixture to provide a common set of functions that are performed just before each test method is called. A TestFixture can have only one SetUp method. If more than one is defined the TestFixture will compile successfully, but its tests will not run.

Example:

[TestFixture]
public class SuccessTests
{
  [SetUp]
  public void Init()
  {
 	/* ... */
  }
}

TearDownAttribute

This attribute is used inside a TestFixture to provide a common set of functions that are performed after each test method is run. A TestFixture can have only one TearDown method. If more than one is defined the TestFixture will compile successfully, but its tests will not run.
Example:

  [TestFixture]
  public class SuccessTests
  {
    [SetUp]
    public void Init()
    {
	/* ... */
    } 

    [TearDown]
    public void Dispose()
     {
	 /* ... */
     } 

     [Test]
     public void Add()
    {
        /* ... */

    }
}

At the end I want to tell you about ExpectedException Attribute.
We use it when we want to test some exception.
This is the way to specify that the execution of a test will throw an exception.

Example:

  [ExpectedException( typeof( ArgumentException ) )]
  public void TestMethod()
  {
 	...
  }

  [ExpectedException( typeof( ArgumentException ), ExpectedMessage="expected message" )]
  public void TestMethod()
  {
 	...
  }
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in