Wednesday, March 28, 2012

How to Connect 2 Windows 2008 R2 VisualBox VMs with virtual network

       When you create 2 Windows 2008 R2 VisualBox VMs, you must want to connect them together with virtual network to form a small LAN. Your goal is these 2 VMs must have internet access and be able to access each other by sharing and HTTP. Following are the steps how to setup with VisualBox 4.1.10:

       1. You need to install AD Domain Service and DNS roles on the VM works as domain controller. At the end of this step, you setup your local domain.

       2. Shutdown both VMs, add second network adapter to both VMs selecting "Host-only networking" mode.

       3. Start both VMs, you will find a new network connection. In its property, set DNS server address to your domain controller and disable TCP/IP V6. Restart both VMs.

       4. Join the VM to your domain.
 
       You will still have some small issues, such as, you can not enable network discovering. But actually you can access each VMs' shared resources. Another problem is you can only access the website on the other VM by IP (for example, http://192.162.3.66, rather than http://Yukon). I believe you can figure that out easily.

Sunday, March 25, 2012

Design Patterns: Interface

       The most important concept of OOP is probably interface. I personally think it's the beginning of all OOP magic. The terminology "interface" is independent of certain programming language, although most modern programming languages have a "interface" keyword. A interface is a contract between consumer object and supplier object. For example, you hire a painter to paint your walls, the painter must be competent to paint your walls no matter what his skin color is. So, the "painter" is a contract between you and the person you hire to paint your walls. With this contract concept, you don't have to hire a specific person to do your painting job, you can hire any qualified painter to do it. In OOP, this is called loosely coupled. This is very important for writing extendable, maintainable, testable software.
       Following is a very simple example to show how interface works. We have a IPlan interface for Customer, there are two classes implementing IPlan, named PlanBasic and PlanStandard. Different customers can have different plan. Let's take a look at the code in C#:
       The IPlan interface:
       public interface IPlan
    {
        string PlanName { get;}
        float getMonthlyPayment();
    }

       PlanBasic and PlanStandard:
       public class PlanBasic : IPlan
    {
        public string PlanName
        {
            get
            {
                return "Basic Plan";
            }
        }

        public float getMonthlyPayment()
        {
            float ret = 9.99f;
            return ret;
        }
    }

       public class PlanStandard : IPlan
    {
        public string PlanName
        {
            get
            {
                return "Standard Plan";
            }
        }

        public float getMonthlyPayment()
        {
            float ret = 29.99f;
            return ret;
        }
    }

       The Customer class that is the consumer class of contract IPlan:
       public class Customer
    {
        private string name;
        private IPlan plan;

        public string Name
        {
            get
            {
                return name;
            }
        }

        public Customer(string _name, IPlan _plan)
        {
            name = _name;
            plan = _plan;
        }

        public float getMonthlyPayment()
        {
           return plan.getMonthlyPayment();
        }

        public override string ToString()
        {
            return "Name: " + name + " Plan: " + plan.PlanName + " Monthly Payment: " + getMonthlyPayment();
        }
    }

       Let's write an unit test code to test the interface pattern:
       [TestMethod]
        public void InterfaceTest()
        {
            Customer customer = new Customer("John Smith", new PlanBasic());
            Assert.AreEqual("Name: John Smith Plan: Basic Plan Monthly Payment: 9.99", customer.ToString());

            customer = new Customer("John Doe", new PlanStandard());
            Assert.AreEqual("Name: John Doe Plan: Standard Plan Monthly Payment: 29.99", customer.ToString());
        }
       You can see the customer class don't have to know any information about any specific plan when it is written.

Thursday, March 22, 2012

Retrieving MD5 fingerprint by JDK 1.7 for generating Google Map API key

        When you develop Google Map API application on android platform, Google requires you sign your application with a Map API key and you need to include this key in your activity's layout xml. To signup Google Map API key, you need a Google account and a MD5 fingerprint. Basically, you need two fingerprints, one is for running your application on simulator, the other is for running your application on real Android device. Where do you get your finger print?

        If you use Eclipse, it signs your application with debug key storing in C:\Users\<your username>\.android\debug.keystore. The MD5 fingerprint of this debug key should be used to signup Google Map API key. For your release version, you should create your own release keystore file using JDK's keytool.exe in JDK1.7.0_01\bin folder. Once you have a keystore file, either debug or release, you can use keytool.exe to retrieve the MD5 from the keystore file.

        Retrieving MD5 fingerprint from keystore file on JDK 1.7 is a little bit tricky. You need to use the command like below to retrieve the MD5 fingerprint:

                keytool -list -v -keystore "[the path to your keystore file]"

         The tricky part is you must use "-v" to display all fingerprints, otherwise you only get the SHA1 fingerprint, which is not we need to signup Google Map API.

Thursday, March 15, 2012

Install Snow Leopard 10.6.2 in VisualBox on Windows 7

        To develop software for iOS, you need a Mac system. However, it's too expensive if you buy a Mac system just for learning how to write code on iOS especially when you are not sure if iOS or Mac software development is suitable for your taste. Naturally, virtual machine becomes inevitable inexpensive choice for studying purpose. There are a lots of articles on internet talking about installing Mac OS on virtual machine. This blog is a simple guide based on those articles.

       To install Snow Leopard 10.6.2, we need following software:
              1. Snow_Leopard_Client_Server_10.6.2_SSE2_SSE3_Intel_AMD iso.
              2. Boot loader iBoot (iBoot-Legacy-2.7.2 works for me, someone else may want to try iBoot-3.2.0)
              3. VisualBox (the one I used is 4.1.8).

       Preparation:
              1. Enable the VT-X / AMD-V CPU feature in BIOS of your motherboard.
              2. Create a Mac OS VM in VisualBox. The most important thing is UNCHECK the "Enable EFI" checkbox in system page.

       Install Snow Leopard 10.6.2:
              1. Mount Snow_Leopard_Client_Server_10.6.2_SSE2_SSE3_Intel_AMD iso to VM's DVD drive. Start the VM.
              2. Install snow leopard using default setting.
              3. Unload Snow_Leopard_Client_Server_10.6.2_SSE2_SSE3_Intel_AMD iso and load iBoot-Legacy iso when the installer reboots VM.
              4. Use iBoot boot the installed snow leopard and finish the post install configuration.

       You may need iBoot to boot every time when you reboot the VM.
      
       To check your Mac OS version in terminal:
              $ /usr/bin/sw_vers
              ProductName: Mac OS X
              ProductVersion: 10.6.2
              BuildVersion: 10C540
              $

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.