Monday, January 25, 2010

SharePoint 2010 Beta Installation Error: An exception of type Microsoft.Office.Server.UserProfiles.UserProfileException was thrown

I was installing SharePoint 2010 beta in Windows server 2008 x64. Everything went fine till installation and when I run configuration wizard it thrown the following exception at step 8:

An exception of type Microsoft.Office.Server.UserProfiles.UserProfileException was thrown.  Additional exception information: The request channel timed out while waiting for a reply after 00:00:19.9589870. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.”

Then I run the central administration site and it was working fine. But when I tried to run default site (at port 80), it was breaking. So I tried to find out the issue and finally found that it’s an timeout issue. The problem is that the user profiling WCF service was timed out. To fix this I increased the timeout value in the file “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\Profile\client.config”. The modification was in the following lines.

<binding name="ProfileServiceHttpsBinding"
            receiveTimeout="00:00:20"
            sendTimeout="00:00:20"
            openTimeout="00:00:20"
            closeTimeout="00:00:20">

In the above code snippet the timeout value is 20 sec. You can change it some other values (more than 20 secs). I had put 3 minutes as shown below:

<binding name="ProfileServiceHttpsBinding"
            receiveTimeout="00:03:00"
            sendTimeout="00:03:00"
            openTimeout="00:03:00"
            closeTimeout="00:03:00">

After changing the timeout value I had run the configuration wizard again and found the issue resolved.

Sunday, January 17, 2010

TDD: Mock static method

Most of the Mock framework doesn’t support static method mocking. So most of the time you need to modify your code to make the code testable. I’m going to use Moq mocking framework to show mocking.

Class with static method:

public class MyHelper
{
public static string GetHelp()
{
return "This is help";
}
}

Class under test and using static methods

public class MyManager
{
public bool IsManaged { get; set; }
public void Manage()
{
string help = MyHelper.GetHelp();
IsManaged = (!string.IsNullOrEmpty(help));
}
}

In the above code, the static method call (MyHelper.GetHelp())need to be mocked. The problem is that MyHelper can’t be passed from outside and second problem is that Moq framework doesn’t have option to mock static method.

 

Approach to use to modify code to make static method mockable

Now let’s modify the code so that we can separate the static method invocation from our methods that we want to test. Let’s modify the MyManager class to make it testable.

1. Modify Code to separate dependencies on static methods:

In the following code snippet I have separated extracted a method in MyManager which will return the help. The extract method GetHelp method needs to be virtual and protected as this will be overridden by stub class.

public class MyManager
{
public bool IsManaged { get; set; }
public void Manage()
{
string help = GetHelp();
IsManaged = (!string.IsNullOrEmpty(help));
}

protected virtual string GetHelp()
{
return MyHelper.GetHelp();
}
}

2. Create a stub of the class under test in the test project

Now you can override the GetHelp method in the stub class as shown below. So your stub class is not using static method rather it’s doing something fake.

public class MyManagerStub:MyManager
{
protected override string GetHelp()
{
return "this is help from stub";
}
}

3. Test stub class instead of actual class

Now your stub class MyManageStub is alike the MyManager except the static method invocation is removed. Now you test will use MyManagerStub as shown below

public void TestMe()
{
MyManagerStub manager = new MyManagerStub();
manager.Manage();
Assert.AreEqual(true, manager.IsManaged);
}

The approach I have described in this post is a one of the approach taken from this link.

Monday, January 11, 2010

Common Service Locator: Separate hard reference of your IoC/DI container from your solution

Service Locator

Dependency Injection is an way to separate dependency. Someone can use Constructor Injection, Setter Injection etc for injecting dependency. Service Locator solves the same problem as Dependency Injector but it uses different approach. Service Locator holds reference of all types/objects an application needs. So whenever you need to use an instance of a type/class, ask service locator to provide the instance. Simply, the Service Locator uses a container to hold all references to class/type to instance/object mapping. You can follow the links for details:

Why Common Service Locator?

Nowadays as a .NET developer, we have a set of DI/IoC containers to choose from. We have option for Spring.NET, Unity Application Block, Castle Windsor etc. Whenever you use any of them in your project, the project is tightly coupled with that container. So if you start your project with Spring.Net Container then your project will be tightly coupled with the Spring.Net container. But later if your decide to use Unity Application Block then can you imagine how much hassles are waiting for you? You need to remove all reference of Spring.Net container from your code. Another example might be, you are developing a library that will be used by other users. Now if you use a IoC Container (say Spring.Net) then you are forcing users to use Spring.Net whenever they want to use the library. So if it would be possible to loose the coupling between your code and the IoC container then you can easily remove dependencies on IoC container.The Common Service Locator project at codeplex is aimed to attain the goal.

Use Common Service Locator

1. Get an understanding of IServiceLocator interface
The Start with an Interface IServiceLocator which has few methods which is generic to any IoC container.The IServiceLocator inherits from IServiceProvider.
public interface IServiceProvider
{
    object GetService(Type serviceType);
}
 
public interface IServiceLocator : IServiceProvider
{
    object GetInstance(Type serviceType);
    object GetInstance(Type serviceType, string key);
    IEnumerable<object> GetAllInstances(Type serviceType);
    TService GetInstance<TService>();
    TService GetInstance<TService>(string key);
    IEnumerable<TService> GetAllInstances<TService>();
}
The Common service Locator will implement the interface IServiceLocator. The Common Service Locator framework has provided an abstract implementation of IServiceLocator called ServiceLocatorImplBase. The ServiceLocatorImplBase has two abstract methods which actually depends on IoC Container.
  • DoGetAllInstances: get all instance of a particular type from Container.
  • DoGetInstance: Get a particular instance from Container
For getting instance from container, ServiceLocatorImplBase uses above two methods. And those two methods are implemented by derived class. And Container is actually needed by those two methods. So Container is specific to individual implementation.
2. Develop your custom Service Locator
I have developed two service Locators for Unity and Spring.Net. UnityServiceLocator can use Unity container whereas Spring.Net can uses Object Factory. The following class diagram shows two implementations that I have developed in the project attached with this post.
image
Figure: Two sample implementations of Common Service Locator
3. Develop BootStrapper
So I have developed two service locators till now. Now I need to develop two bootstrappers for Spring.Net and Unity as type registration are different for two.
public abstract class CommonBootStrapper
{
    public static IServiceLocator Locator;
 
    protected CommonBootStrapper()
    {
        Locator = CreateServiceLocator();            
    }
 
    protected abstract IServiceLocator CreateServiceLocator();
}
The common bootstrapper has a instance of IServiceLocator which means it can hold reference to any class’s instance inheriting from ServiceLocatorImplBase (as ServiceLocatorImplBase implements IServiceLocator). So we can put the UnityServiceLocator or SpringServiceLocator in the CommonBootStrapper’s Locator variable. Now we need to two different bootstrappers for Unity and Spring.Net. The Unity implementation is shown below.
public class UnityBootStrapper : CommonBootStrapper
{
    protected override IServiceLocator CreateServiceLocator()
    {
        UnityContainer container = new UnityContainer();
        RegisterTypes(container);
        return new UnityServiceLocator(container);
    }
 
    private static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<ICustomer, GoldenCustomer>(typeof(ICustomer).FullName);
    }
}
As shown in code above, The UnityBootStrapper needs to override the CreateServiceLocator and in this method I have created an UnityContainer and packed it within UnityServiceLocator. For Spring.Net you can create an SpringServiceLocator with ObjectFactory packed in it.
4. Develop a BootStrapper Manager to provide a single point of access to Service Locator
Finally you need to develop a bootstrapper manager to hide the concrete implementation of CommonBootStrapper. The following code shows the BootStrapperManager
public class BootStrapperManager
{
    private static CommonBootStrapper _bootStrapper;
 
    public static void Initialize(CommonBootStrapper bootStrapper)
    {
        _bootStrapper = bootStrapper;
    }
    public static CommonBootStrapper BootStrapper
    {
        get { return _bootStrapper; }
    }
}
5. Access the IServiceLocator through BootStrapperManager
Now you need to register your BootStrapper to BootStrapperManager at some entry point to your application (like Main method). I have register as shown below:
BootStrapperManager.Initialize(new UnityBootStrapper());
Now from the application I only use CommonBootStrapper.Locator to get the IServiceLocator instance. So to get any instance from container I can write code like below:
ICustomer customer = CommonBootStrapper.Locator.GetInstance<ICustomer>(typeof(ICustomer).FullName);
customer.SendMessage("This is me.");

Conclusion

I have just gone through some basic ideas on how you can use Common Service Locator to decouple dependency to IoC Container from your production code. You can get more details on this visiting CodePlex link. For making my implementation I have included the Source Code from Common Service Locator in my Visual Studio Solution.

Monday, January 4, 2010

Test Driven Development Step by Step Part 2: Create a math library

In my last post I had did some paperwork describing what is TDD, how you can introduce TDD in your team what challenges you may face etc. In this second part I’ll show you how you can develop a C# math library with TDD approach. In non-TDD approach you add a class (say BasicCalculator) and in that class you implement few functions to meet your requirements (Add, Subtract, Multiply, Divide).

Non-TDD approach

The non-TDD approach is as follows:

1. Create a new project (say Math.Library) in Visual Studio. You doesn’t create a test project at this approach.

2. Add a new class BasicCalculator in the project.

3. Add a method Add that takes two operands and return a value as shown below:

public int Add(int operand1, int operand2)
{

                return operand1 + operand2;
}

4. Now you debug and test to check if the add method works perfectly.

TDD-Approach

In TDD approach you write test first and then write actual (called production) code. The steps are:

1. Create a new project (say Math.Library) in Visual Studio. This is any other project expect test project.

2. Create a new test project (say Math.Library.Test) in Visual Studio. You can use NUnit or VS unit test framework to create the project.

3. Now add a test class in the test project and name it BasicCalculatorTest.

4. Add a test method in BasicCalculatorTest class and name this method TestAddition.

5. Write test code in this TestAddition method to verify the add functionality of our basic calculator.

6. Create any production classes and methods to compile the VS solution.

7. Run the test and it’ll definitely fail as no production code is implemented yet.

8. Write/refactor Production code to make sure the test passes

How-to Video showing basic TDD development

The video included here will guide you how to start with TDD using Visual Studio and C#. The video show how to develop a math library in TDD approach. In TDD you first write test then write fewer code just to make the test run. Once the test will run the test will fail as you have not written any production code (code that will finally shipped to the production) yet. So then you’ll refactor the code to pass the tests. FYI, here I have used refactor in more general term though it’s not refactor. But this video is just to give you a starting with TDD.