Setting up Unit Test Project using NUnit and MOQ

Add a new project(of type C# library) by right click on Visualstudio solution.
Select newly created project and add the project reference for which you are going to write unit test cases.

Add a configuration (app.config)file to simulate the same configuration which was used in the actual project. e.g. log4net, appsettings, unity and other configuration which are used in the actual project.

Setting up NUnit for Test project

Right click on project and go to Manage nuget packages.

    Install NUnit(2.6.2 version) and NunitRunners,nunit console packages
    Install NUnit2TestAdapter, which allow us to run or debug the test case in the visual studio.

Setting up MOQ framework for mocking
1. Install MOQ nuget package for mocking the objects while writing unit test cases.


Setting up OpenCover plugin in VisualStudio for Code Coverage

Download OpenCover UI plugin this is for Visual representation of coverage.
using tools > extension and updates option from Visuals studio
Configure OpenCover with NUnit in Visual studio. Behind the scenes OpenCover extract nunit test results and show it visually.

Tools > options > OpenCover.UI Options >
select nunit path as ..\packages\NUnit.Runners.Net4.2.6.4\tools\nunit-console.exe
select OpenCover Paht as ..\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe
Goto OpenCover menuitem > select opencover test Explorer to find out your test cases

Start writing your unit testing
Now add .cs files and start write unit test cases by make use of Nunit by decorating your method with [Test]

Typical issues you might face:
1) You can’t run the test cases ?

Ans: Check NUnit2TestAdapter installed properly.

2) Open Cover doesn’t open the test cases? It prompts to select the NUnitRunner executable file?

Ans: Follow Setting up OpenCover plugin in VisualStudio for Code Coverage section carefully as mentioned above. This is because of Test Results couldn’t find by OpenCover.

Once you setup with all the steps, your Visual studio should look like below ScreenShot.

You can see

Test Explorer( from main menu you can openTest > Run >All Tests),
OpenCover Explorer pane from Right hand side.


Note:

    Unit testing should never reach multiple levels, one test case one level the lower levels should be always mock-able.
    The number of conditions should be the ideal count number of test cases expected for a method.

Enabling log for Trace.Writeline

Download sample here

Just drop the dll in bin directory and place the below configuration in web.config

<system.diagnostics>

<trace autoflush=”true” indentsize=”4″>

<listeners>

<remove name=”Default” />

<add name=”rollingfile”

type=”Essential.Diagnostics.RollingFileTraceListener, Essential.Diagnostics”

initializeData=”c:\temp\log-{DateTime:yyyy-MM-dd}.log”

convertWriteToEvent=”true”

template=”{DateTime:yyyy-MM-dd HH:mm:ss.fff} Thread: {ThreadId} {Message}{Data}”  />

</listeners>

</trace>

</system.diagnostics>

JavaScript Design Patterns( Module pattern)

The Module pattern encapsulates “privacy”, state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer’s interface. With this pattern, only a public API is returned, keeping everything else within the closure private.

Refer this link for more details

 

Transient Fault Handling and retry policy

  • Create a console application 
  • Add nuget package using  package manager console
  • Install-Package EnterpriseLibrary.TransientFaultHandling

  • Copy the below code 

//Defining RetryPolicy
class Program
{
const int RETRY_COUNT = 5;

static void Main(string[] args)
{
try
{
var retryStrategy = new Incremental(RETRY_COUNT, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));

var retryPolicy = new RetryPolicy<CustomTransientErrorDetectionStrategy>(retryStrategy);

retryPolicy.ExecuteAction(NavigateTo);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}

// The block of code might throw exception
static private void NavigateTo()
{
Console.WriteLine(“Trial @ :” +DateTime.Now);

WebClient wc = new WebClient();
Console.WriteLine(wc.DownloadString(“c:\\temp.txt”));

}
}

//Implement the ITransientErrorDetectionStrategy interface
internal class CustomTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
{
public bool IsTransient(Exception ex)
{
if (ex is WebException)
return true;
return false;
}
}

Note:

NavigateTo method will loop 5 times as it throws exception due to temp.txt file unavailability.

If we keep the temp.txt file with some content it executes one time.

 

Dependency Injection in C#

Mostly in ASP.NET MVC applications we could find this kind of implementation.

Follow the below blog

http://www.codeguru.com/csharp/.net/net_asp/mvc/understanding-dependency-injection.htm

Using above as reference

Dependency Injection (DI) is a design pattern that takes away the responsibility of creating dependencies from a class thus resulting in a loosely coupled system. In order to understand DI you need to be aware of the following terms:

  • Dependency
  • Dependency Inversion Principle
  • Inversion of Control (IoC)

Let’s assume that you have a simple C# class as shown below:

public class Customer

{

           private DatabaseHelper helper; 

           public Customer()

          {

              helper = new DatabaseHelper();

           }

}

The Customer class declares a variable of type DatabaseHelper. The DatabaseHelper class is supposed to be doing some database operations such as SELECT and UPDATE. The constructor of the Customer class instantiates the DatabaseHelper class and the instance is stored in the helper variable. In this case the Customer class is dependent on the DatabaseHelper class for its functioning. Thus DatabaseHelper is a dependency of the Customer class.

The problem with the above design is that the Customer class and DatabaseHelper class are tightly coupled. If you ever need to substitute DatabaseHelper with some other class (say XMLHelper) then you will have to change the code of the Customer class since it directly instantiates the DatabaseHelper. To help avoid this, tight coupling Dependency Inversion Principle (DIP) is used. The DIP states that – High-level modules should not depend on low-level modules. Both should depend on abstractions. That means Customer should not depend on a concrete implementation (DatabaseHelper) but rather should depend on an abstraction. At code level this means the Customer class won’t have a variable of DatabaseHelper type, instead it will have a variable of some interface (or abstract class) type. This is shown below:

  1. public class Customer
  2. {
  3. private IStorageHelper helper;
  4.  
  5. public Customer()
  6. {
  7. helper = new DatabaseHelper();
  8. }
  9. }

Now, the Customer class uses a variable of type IStorageHelper interface everywhere. IStorageHelper is supposed to be an interface that is implemented by the DatabaseHelper class and all such classes. Thus most of the code of the Customer class is now using an abstraction in the form of IStorageHelper.

Although the above code is better than the original implementation, it still has a problem. The helper variable is still instantiated inside the Customer class. This problem arises because the Customer class is responsible for creating its dependency (DatabaseHelper). The Inversion of Control principle (IoC) comes in handy in such cases. IoC states that the control of creating the decencies should be with the external system rather than the class itself. In the above example this means that the Customer class shouldn’t create an instance of DatabaseHelper, rather it should be received from the external system.

Dependency Injection is a way to implement IoC such that the dependencies are “injected” into a class from some external source. The injected dependencies can either be received as constructor parameters of a class or can be assigned to properties of that class designed for that purpose. The former approach is commonly used in ASP.NET MVC. So, the above code now becomes:

  1. public class Customer
  2. {
  3. private IStorageHelper helper;
  4.  
  5. public Customer(IStorageHelper helper)
  6. {
  7. this.helper = helper;
  8. }
  9. }

As you can see, the helper instance is now coming from the external world and is being injected into the Customer class through its constructor.

Applying Dependency Injection in ASP.NET MVC

Now that you understand the basics of Dependency Injection, let’s see how DI can be used in ASP.NET MVC controllers. Consider the following controller class:

  1. public class HomeController : Controller
  2. {
  3. ICustomerRepository repository = null;
  4.  
  5. public HomeController(ICustomerRepository repository)
  6. {
  7. this.repository = repository;
  8. }
  9.  
  10. public ActionResult Index()
  11. {
  12. List<CustomerViewModel> data = repository.SelectAll();
  13. return View(data);
  14. }
  15. }

The above code should be immediately familiar to you because it uses the concept of IoC and DI as discussed in the previous section. The HomeController class declares a variable of ICustomerRepository. The ICustomerRepository is an interface designed to implement the Repository pattern and is shown below:

  1. public interface ICustomerRepository
  2. {
  3. List<CustomerViewModel> SelectAll();
  4. CustomerViewModel SelectByID(string id);
  5. void Insert(CustomerViewModel obj);
  6. void Update(CustomerViewModel obj);
  7. void Delete(CustomerViewModel obj);
  8. }

In the above code some implementation of ICustomerRepository is injected inside the HomeController through its constructor. As you can see the Index() action method calls the SelectAll() method on the repository to retrieve all the customers as a List of CustomerViewModel objects. The CustomerViewModel is a simple class that acts as a view model and is shown below:

  1. public class CustomerViewModel
  2. {
  3. public string CustomerID { get; set; }
  4. public string CompanyName { get; set; }
  5. public string ContactName { get; set; }
  6. public string Country { get; set; }
  7. }

Although the above code seems to apply DI as expected there is a problem. The problem is that while instantiating the HomeController for processing the incoming requests, ASP.NET MVC framework uses the parameter less constructor of the HomeController. Since our HomeController no longer has one, the above code throws an exception at runtime. Luckily, ASP.NET MVC allows you to explicitly specify how controllers should be instantiated. This can be done by creating your own Controller Factory.

A controller factory is a class that usually inherits from DefaultControllerFactory class and is responsible for creating controller instances. Once created you need to register your custom controller factory with the ASP.NET MVC framework so that it can use your controller factory instead of the default one. Let’s create the custom controller factory first. Have a look at the following code:

  1. public class MyControllerFactory:DefaultControllerFactory
  2. {
  3. private Dictionary<string, Func<RequestContext, IController>> controllers;
  4.  
  5. public MyControllerFactory(ICustomerRepository repository)
  6. {
  7. controllers = new Dictionary<string, Func<RequestContext, IController>>();
  8. controllers[“Home”] = controller => new HomeController(repository);
  9. }
  10.  
  11. public override IController CreateController(RequestContext requestContext, string controllerName)
  12. {
  13. if(controllers.ContainsKey(controllerName))
  14. {
  15. return controllers[controllerName](requestContext);
  16. }
  17. else
  18. {
  19. return null;
  20. }
  21. }
  22. }

The MyControllerFactory class inherits from the DefaultControllerFactory class provided by the ASP.NET MVC framework. The constructor of MyControllerFactory accepts an instance of ICustomerRepository. This way the MyControllerFactory doesn’t depend on any concrete implementation of ICustomerRepository. The code then overrides the CreateController() method of the base class. A Dictionary objects maintains a list of controllers in the application. Notice that HomeController is being instantiated in the constructor and is stored with a key of Home. The CreateController() simply returns this instance of HomeController from the Dictionary.

Now that the custom controller factory is ready, you need to register it with the ASP.NET MVC framework. To help you with this registration we create a helper class – ControllerFactoryHelper – as shown below:

  1. public class ControllerFactoryHelper
  2. {
  3. public static IControllerFactory GetControllerFactory()
  4. {
  5. string repositoryTypeName = ConfigurationManager.AppSettings[“repository”];
  6. var repositoryType = Type.GetType(repositoryTypeName);
  7. var repository = Activator.CreateInstance(repositoryType);
  8. IControllerFactory factory = new MyControllerFactory(repository as ICustomerRepository);
  9. return factory;
  10. }
  11. }

The ControllerFactoryHelper class has just one static method, GetControllerFactory(). The job of GetControllerFactory() is to instantiate MyControllerFactory and prepare for the registration. This is the place where the concrete implementation of ICustomerRepository are required. This is so because unless these details are known you can’t instantiate MyControllerFactory (since the constructor of MyControllerFactory needs an object implementing ICustomerRepository). The above code assumes that these details are stored in the <appSettings> section of the web.config file as shown below:

  1. <appSettings>
  2. <add key=“repository” value=“DIDemo.Repositories.CustomerRepository”/>
  3. </appSettings>

The GetControllerFactory() reads the repository key and creates an instance of DIDemo.Repositories.CustomerRepository using Reflection. It then instantiates MyControllerFactory by passing this object. The factory object is then returned to the caller.

Now comes the final step. To register the custom controller factory you need to add the following code in Globa.asax:

  1. protected void Application_Start()
  2. {
  3. AreaRegistration.RegisterAllAreas();
  4. RouteConfig.RegisterRoutes(RouteTable.Routes);
  5.  
  6. ControllerBuilder.Current.SetControllerFactory(ControllerFactoryHelper.GetControllerFactory());
  7. }

The Application_Start event handler uses the ControllerBuilder instance and calls its SetControllerFactory() method. The factory object returned by the GetControllerFactory() static method is passed as a parameter to the SetControllerFactory() method.

That’s it! The following figure shows a sample run of the Index view.

Index View

Summary

Dependency Injection is a technique to separate the creation of dependencies from the main class under consideration. Using DI you inject the objects needed  by a class typically through a constructor. This article illustrated how DI can be used in ASP.NET MVC controllers. For the sake of simplicity it didn’t use any IoC Container frameworks such as Unity, Castle Windsor and NInject. In real world applications you may use one of such frameworks to make your job easier.

How to increase concurrency in wcf service to consume by more users.

We can achieve this by using Throttling.

WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance.

Attribute Description
maxConcurrentCalls Limits the total number of calls that can currently be in progress across all service instances. The default is 16.
maxConcurrentInstances The number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.
maxConcurrentSessions A positive integer that limits the number of sessions a ServiceHost object can accept. The default is 10.

Service Throttling can be configured either Adminstractive or Programatically

Administrative(configuration file)

Using <serviceThrottling> tag of the Service Behavior, you can configure the maxConcurrentCallsmaxConcurrentInstances ,maxConcurrentSessions property as shown below.

<system.serviceModel>
    <services >
      <service behaviorConfiguration="ServiceBehavior"  name="MyService">
        <endpoint address="" binding="wsHttpBinding" contract="IMyService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true "/>
          <serviceThrottling maxConcurrentCalls="500"
 maxConcurrentInstances ="100" 
maxConcurrentSessions ="200"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Programming Model

Use ServiceThrottlingBehavior object to set concurrent calls, session and instance property.

           ServiceHost host = new ServiceHost(typeof(MyService));
           ServiceThrottlingBehavior throttle
 = host.Description.Behaviors.Find();
            if (throttle == null)
            {
                throttle = new ServiceThrottlingBehavior();
                throttle.MaxConcurrentCalls = 500;
                throttle.MaxConcurrentSessions = 200;
                throttle.MaxConcurrentInstances = 100;
                host.Description.Behaviors.Add(throttle);
            }

            host.Open();