Wednesday, February 29, 2012

Design Patterns: Factory

       During software development, you may need to create an instance of a set of classes implement the same interface. It depends on runtime conditions / settings to create which concrete class instance. If you test the condition / settings each time when you need to create the instance. The logic that selects the class of instance will be scattered everywhere in your code. Once the select logic is changed, you have to change everywhere the logic is. You can use Factory pattern to resolve this problem.

       For example, we have a IVehicle interface:

       public interface IVehicle
    {
        void drive();
    }

       There are 3 classes Car, Truck, and Bus implement IVehicle interface:

       public class Car : IVehicle
    {
        public void drive() { }
    }

    public class Truck : IVehicle
    {
        public void drive() { }
    }

    public class Bus : IVehicle
    {
        public void drive() { }
    }

       We use a factory class VechicleFactory to read system settings and create IVechicle instance:

       public class VehicleFactory
    {
        public const int VEHICLE_TYPE_CAR = 1;
        public const int VEHICLE_TYPE_TRUCK = 2;
        public const int VEHICLE_TYPE_BUS = 3;

        public IVehicle createVehicle()
        {
            IVehicle ret = null;

            int type = getVehicleType();

            switch (type)
            {
                case VEHICLE_TYPE_CAR:
                    ret = new Car();
                    break;

                case VEHICLE_TYPE_TRUCK:
                    ret = new Truck();
                    break;

                case VEHICLE_TYPE_BUS:
                    ret = new Bus();
                    break;
            }

            return ret;
        }

        private int getVehicleType()
        {
            SystemSettings settings = SystemSettings.getInstance();
            return settings.VehicleType;
        }
    }

       To simplify the sample, we just hard code the vehicle type in System settings class, which is of singleton pattern in my previous blog:
       public class SystemSettings
    {
        private static int instanceNum = 0;
        private static SystemSettings settings;

        private int vehicleType = VehicleFactory.VEHICLE_TYPE_CAR;

        private SystemSettings() { instanceNum++; }
        public static SystemSettings getInstance()
        {
            if (settings == null)
            {
                settings = new SystemSettings();
            }
            return settings;
        }

        public static int InstanceNumber
        {
            get
            {
                return instanceNum;
            }
        }

        public int VehicleType
        {
            get
            {
                return vehicleType;
            }
        }
    }

       We write unit test code to test the factory pattern:
       [TestMethod]
        public void FactoryTest()
        {
            VehicleFactory factory = new VehicleFactory();

            IVehicle vehicle = factory.createVehicle();

            Assert.IsTrue(vehicle is Car);
        }
 
       You can see the client code don't have to know how to select the vehicle type to create the vehicle instance. The client just need to use factory to create the instance.

Tuesday, February 28, 2012

Design Patterns: Singleton


       During software development, you may need to create one and only one instance of a certain class when the application is running. For example, the database connection object. And you want the class maintain this rule by itself. This class is called a "Singleton" class. Let's look at a simple example:

       We need to make a class named SystemSettings a singleton class, we define it as following:

       public class SystemSettings
    {
        private static int instanceNum = 0;
        private static SystemSettings settings;

        private SystemSettings() { instanceNum++; }

        public static SystemSettings getInstance()
        {
            if (settings == null)
            {
                settings = new SystemSettings();
            }

            return settings;
        }

        public static int InstanceNumber
        {
            get
            {
                return instanceNum;
            }
        }
    }

       The private constructor make sure other the SystemSettings class instance can not be created from outside . getInstance() method make sure there is only one instance of settings class is created. We can write a unit test to test if this singleton class works like it should:

       [TestMethod]
     public void SingletonTest()
     {
           SystemSettings settings = SystemSettings.getInstance();
            Assert.IsTrue(SystemSettings.InstanceNumber == 1);

            settings = SystemSettings.getInstance();

            Assert.IsTrue(SystemSettings.InstanceNumber == 1);
      }

       As we expect, the test is successful.

Wednesday, February 22, 2012

ASP.Net MVC 3 - passing data to view by ViewBag, ViewData, and TempData

      ViewBag, ViewData, and TempData are 3 vehicles to pass data from action method to a view. But it's confusing what the differences are between them and when to use which method to pass the data to view. I would like to share my understanding of this topic.

       1. ViewBag:

              ViewBag is a new feature introduced with MVC 3. This feature allows you to define any property on a dynamic object, which can be accessed through the Controller.ViewBag property in a view. And the better thing is you don't have to cast the property.

       2. ViewData:

              ViewData is similar to ViewBag, but it derives from ViewDataDictionary class. So you access the data by key/value style and have to cast the value to known type. The casting make ViewData less attractive comparing with ViewBag.

       3. TempData:

              TempData is similar to Session data. But the life of TempData is much shorter than Session. It lasts only one more request and will be marked for deletion once it is read. So TempData is usually used to keep the data across a redirection.

Sunday, February 19, 2012

Some differences between ASP.Net MVC 3.0 and ASP.Net MVC 2.0

   ASP.Net MVC, first released around year 2009, has evolved to 3.0 (as I am writing this article, 4.0 is on the way). As the history proved, any Microsoft technologies, tools, which upgrade to 3.0, are worth to take a serious look. I would like to introduce some differences between MVC 3 and 2:

       1. ASP.Net view engine is changed to Razor. One of the direct effects is: the ASP.Net notation (<% %>) is changed to new notation @.

       2. Master page is gone. Well..., not really. It is re-invented as layout page, e.g. _Layout.cshtml.

       3. Induced a new feature ViewBag to pass parameter from controller to view.

       4. Better support to dependency injection.

       5. Better support to JQuery

       Above items are only from practice point of view. If you want to get the full list of new features of MVC 3.0, please read ASP.Net MVC 3.0 document.

Saturday, February 18, 2012

Installing ADO.Net Entity Framework with Package Manger Console


         ADO.Net Entity Framework is an ORM framework for .Net platform. It is integrated with LINQ to allow C# software developer to work with database elements, such as tables, using more familiar C# objects. There are lots of articles talking about ADO.Net Entity Framework, and there are many options to implement ORM on .Net platform (such as NHibernate). As usual, I won't discuss too much here. I just post a small tip about install Entity Framework 4.3 to your project. Hopefully this will save you some time.

       When you try to use "Add Library Package Reference..." to install Entity Framework 4.3, you may encounter an error stating " This package (or one of its dependencies) contains an init.ps1 file and needs to be installed from the Package Manager Console." This is because Entity Framework 4.3 package requires license agreement. You has to install it from Package Manger Console.

       You go to menu "Tools"->"Library Package Manager"->" Package Manger Console" to launch Package Manger Console.

       To do a keyword search in PM, type:

              PM> get-package -filter EntityFramework -listavailable

       You will get a list of packages.

       To install EntityFramework, type:

              PM> install-package EntityFramework
         
          PM will install EntityFramework 4.3.0 assuming you accept the license agreement.

Friday, February 17, 2012

Moq and Visual Studio 2010


       In TDD process, we often need to create a "fake" object has the same behaviors as a certain type. Creating a bunch of mock classes is a considerable workload. Fortunately, there are some mocking libraries can create the mock object for us. Moq is one of popular mocking libraries on .Net platform.

       To use Moq in your project, you can either download it from http://code.google.com/p/moq and add Moq.dll into your project reference or install it by menu "Tools"->"Library Package Manager"->"Add Library Package Reference". I would like to provide a simple example to introduce using Moq in .Net.

       Suppose you have a class named Man and an interface name IDevice:

       public interface IDevice

       {

              public bool detect(string s);

       }

       public class Man

       {

              private IDevice device;

              public string TestData { get; set;}

              public Man(IDevice _device) { device = _device; }

              public bool testTheField()

              {

                     return device.detect(TestData);

              }

       }

       Use Moq in your test method:

       // Create a Mock instance setting the interface you want to mock

       Mock< IDevice > mock = new Mock< IDevice >();

       // Setup the mock instance's behaviour

       mock.Setup(x => x. detect ("ping")).Returns(true);

       // Use the mock object

       Man man = new Man(mock.Object);

       man.TestData = "ping";

       bool testResult = man.testTheField();

       // Assert the result must be true

       Assert.AreEqual(testResult, true);

       As you can see, you don't have to create a mock class to implement the IDevice's behaviour to test the IDevice interface consumer class (Man). The Moq library creates the object with expected IDevice implementation for you.

Thursday, February 16, 2012

TDD (Test-driven development) and Unit Test in Visual Studio 2010

    TDD is a software development method that you write the code uses your unit (usually it's a class or implementation of interface) first, this will cause the unit test failed. Then you write or change the unit code itself to make the unit test pass. TDD attracts more and more software developers' attention nowadays, so that Microsoft adds unit test feature in Visual Studio 2010. TDD is a big topic, there are many articles talking about it. I don't want to discuss too much in this blog. I would like to introduce how you do TDD with built-in unit test feature in Visual Studio 2010.

       Suppose your customer wants a class name Car and it must have a method named drive(). You decide to use TDD method to implement it. You add a unit test project into your solution in VS2010. The detail steps:

       1. Menu File->Add->New Project, select Test on the left pane, select Test Project on the right pane.

       2. Input the project name and click OK.

       3. A unit test project will be added to your solution. You can safely remove the auto-created UnitTest1.cs file from the unit test project because you will create your own later.

       After you create the unit test project, you add a CarTest class like following:

       [TestClass()]
       public class CarTest {

              [TestMethod]
              public void canDrive() {

                     Car car = new Car();

                     car.drive();

              }

       }

       Then you go to menu Test->Run->All Test in Solution to start the unit test, this will certainly fail. This failure is a "good" failure, because it drives you to write code to make the test pass. You add a class named Car, which has a method named drive(), into your application project.

       public class Car {

              public void drive() {

                     Console.WriteLine("drive car.")

              }

       }

       You run the unit test again. It is passed successfully this time. Next day, your customer tells you he wants to a new method name openSunRoof() to the Car. You add a canOpenSunRoof() into the CarTest class:

       [TestClass()]
       public class CarTest {

              [TestMethod]
              public void canDrive() {

                     Car car = new Car();

                     car.drive();

              }

              [TestMethod]
              public void canOpenSunRoof () {

                     Car car = new Car();

                     car.openSunRoof();

              }

       }

       Your application code fails to pass the unit test again. This drives you to add a new method named openSunRoof() to class Car:

       public class Car {

              public void drive() {

                     Console.WriteLine("drive car.")

              }

              public void openSunRoof () {

                     Console.WriteLine("open sun-roof.")

              }

       }

       Your code pass the unit test. Nice work!

       Above is just a very simple example to show how is TDD development circle like, it's not meaningful for such a small project. But in real world, keeping your project code unit test clean when you add new features to make it more and more complex is much more meaningful. And your colleagues will find your unit test classes are the best documents to show how to use your code.

       Maybe you are not comfortable with failures in unit test, you can write your code first and then add the unit test code later. VS 2010 also provides a function to make this happen: you can right-click the method you want to unit test and choose "Create Unit Test", you can see the method is pre-selected in the unit test creation dialog, click "OK" and VS 2010 will create a unit test class for you.

       Well, the downside of TDD is also obvious, it increases the code you need to write and maintain. Sometimes the unit test code itself also needs to be tested and  fixed. It's ironic, isn't it? But in the long run, it is worth.

Wednesday, February 15, 2012

Ninject and Visual Studio 2010

         Ninject is an open source DI container for .Net. I would like to briefly introduce how to use it in VS2010.
         It can be easily added to your project's reference by VS2010's "Add Package Library Reference" feature. The detail steps are:
  1. Right-click your project in Solution Explorer, select  "Add Package Library Reference" from popup menu.
  2. In the  "Add Package Library Reference" dialog, click "Online" on left pane, then type "Ninject" in the search field at the top right corner.
  3. Select "Ninject" (this is the core Ninject component) and click "Install".
         Ninject library should show up in the References list now.

         There are 3 steps to use Ninject in your code (I use the classes defined in my previous blog):

     1. Create an instance of Ninject kernel.

          IKernel kernel = new StandardKernel();

     2. Bind a interface to a class that implements that interface.

         kernel .Bind<IVehicle>().To<Car>();

     3. Create and use the instance has the interface implementation.

         // get the interface implementation using Get method of Ninject kernel
         IVehicle vehicleImpl = kernel .Get<IVehicle>();

         // create the instance of Man and inject the dependency
         Man men = new Man (vehicleImpl);

         // perform the car.drive() method
         men.drive();

Tuesday, February 14, 2012

Loosely coupled components, dependency injection (DI), and DI container

       During software development, we usually find different parts of our application are unnecessarily depended on each other. This reduces the flexibility of code and may cause issues. So we want the components of our application to be as independent as possible.

       Here is a simple example to describe how we can de-couple objects.For example, we need to build an application about a man drives car, truck, and tractor.We have a man class like this:

       public class Man
       {
              private Car car = new Car();
              private Truck truck = new Truck();
              private Tractor tractor = new Tractor();

              public Man() {}

              public void driveCar()
              {
                     car.drive();
              }

              public void driveTruck();
              {
                     truck.drive();
              }

              public void driveTractor();
              {
                     tractor.drive();
              }
       }

       As you can see, the "Man" class is coupled with 3 other classes. Any change on those classes (for example, Truck class is renamed to BigTruck) may cause Man class stop working or can not be compiled.

       It's time to de-couple them. We define an interface named IVehicle:

       public interface IVehicle
       {
              void drive();
       }

       We re-define Car, Truck, and Tractor class to implement this interface:

       public class Car : IVehicle
       {
              public void drive() { Console.WriteLine("drive car.");}
       }

       public class Truck : IVehicle
       {
              public void drive() {Console.WriteLine("drive truck.");}
       }

       public class Tractor : IVehicle
       {
              public void drive() {Console.WriteLine("drive tractor.");}
       }

       Then we change Man class as following to de-couple:

       public class Man
       {
              private IVehicle vehicle;

              public Man(IVehicle _vehicle)
              {
                     vehicle = _vehicle;
              }

              public void drive()
              {
                     vehicle.drive();
              }
       }

       We can "inject" the dependency at runtime like this:
    
       IVehicle vehicle = new Car();
       Man man = new Man(vehicle);
       man.drive(); // Man drives the car

       vehicle = new Truck();
       man = new Man(vehicle);
       man.drive(); // Man drives the truck

       vehicle = new Tractor();
       man = new Man(vehicle);
       man.drive(); // Man drives the tractor

       This is much better than the old code. But it's not enough, because we still have to create dependencies somewhere in our application. It's the time to introduce Dependency Injection Container, also known as IoC(Inversion of Control) container. It's an intermediate component to create the dependencies for us. What we need to do is register the interfaces with the DI container and tell it which actual class instances should be created to satisfy dependencies. In my next blog, I will talk about Ninject, a DI container can be added into Visual Studio 2010 project.

Monday, February 13, 2012

Solution to "Failed to create SQLServer user instance" error

I encountered a "Failed to create SQL
Server user instance..." error when I installed VS2010 on Windows 7 and tried to access a SQL Serer Express database. I found following solution from internet:

错误:由于启动用户实例的进程时出错,导致无法生成SQL Server的用户实例。
原因:重装SQLEXPRESS时,装在了不同的目录下;
解决方法:关闭Sqlserver及相关的程序,删除目录C:\Users\[user_name]\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS下的文件。那么如何在windows 7里面找到此目录呢?

首先打开控制面板〉外观和个性化〉文件夹选项〉查看〉隐藏系统受保护的文件(去掉)〉显示隐藏的文件〉确定。打开系统所在盘,发现有一大堆隐藏的。找到 “用户”文件夹,进入相关帐户,找到AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS, 删除该目录即可。

注意:进入相关帐户需以该帐户身份登陆,管理员帐户可以进入其他帐户文件夹。