Open Source

Embracing Open Source for Connected Devices [DotNetCurry Magazine]

July 2, 2015 Azure, IoT, Open Source , ,

I am glad to inform that my article on Internet of Things on Azure using Javascript and .NET is featured in the 3rd anniversary of DotNetCurry Magazine (Issue 19).

An excerpt from the article is

With each passing day, we are getting hooked on to an increasing number of small devices. Besides, the Internet drives our lives like never before. It is obvious, as well as natural, that the connectivity of these small devices with the Internet, ultimately, will lead towards their inter-connectivity; where not only data exchange, but decision making will be a shared responsibility of these smart devices. That means the real value of Internet of Things (IoT) does not lie in just home automation, but rather in the data collection by these smart devices and analytics, further up the value chain.

In this article, we will explore the possibility of developing applications for IoT devices that capture data from low-cost sensors and communicate with real-time scalable services in Windows Azure – primarily using Open Source Technologies for devices and Managed Services in Azure.

Direct download: [PDF- DNC-July 2015] [ZIP- DNC-July 2015]

Migrating from SVN to GitHub

December 16, 2014 Open Source , ,

For those who are following my posts and my open source work, might have found that I’ve started adopting GitHub for KonfDB and my blog samples. So I thought of moving my open source tools from CodePlex to GitHub so that I can centralize my code. So here I go with what anybody would do – Google.

To my amusement, there are some posts that suggest using GitHub import wizard which looked quite easy to believe. But one of the bigger problem is that the import wizard does not allow providing user name and password. So for protected svn repositories, the GitHub import wizard does not work.

Another solution was to take the latest from CodePlex (SVN) and then check-in the code in GitHub. But that would mean letting go of the check-in history. So I needed something even more automated.

Procuring the tools – Ruby

You can get the latest version of Ruby Installer and install Ruby on your machine. This is because the tool we are going to use to migrate SVN to GitHub (svn2git) is built using Ruby and we need Ruby in the executable PATH.

Enabling Trust with RubyGems

 

Ruby uses RubyGems as Package Manager and apparently it uses HTTPS url to get the packages. On Windows, I was prompted with following error

ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)

 

I found the solution to this problem on StackOverflow – the summary of which is

Find out the directory for RubyGems by the command shown below


Download PEM file from https://raw.githubusercontent.com/rubygems/rubygems/master/lib/rubygems/ssl_certs/AddTrustExternalCARoot-2048.pem and copy it to

../2.1.0/rubygems/ssl_certs/ 

 

This should allow you to download packages from gem.

Procuring svn2git

To download svn2git, execute following command

gem install svn2git

 

The output of this command will be like,

 

Accessing CodePlex SVN repository

 

To get the SVN repository details, we can access the CodePlex repository > Source tab and click on Connect icon

Copy the SVN URL and execute these steps as shown below in a directory that is empty.

Downloading the code with history into Local Git Repository

 

svn2git https://codeinject.svn.codeplex.com/svn/ -v --username punitganshani --nobranches --notags --rootistrunk

 

Substitute the SVN url in the above command and default username and execute it on a Command Prompt

When accessing SVN repository, it will prompt you to accept Microsoft CodePlex certificate. You can accept it temporarily or permanently.

The output of this operation will look something like

Running command: git svn init --prefix=svn/ --username=punitganshani --no-metadata --trunk=https://codeinject.svn.codeplex.com/svn/
Running command: git svn fetch
Running command: git branch -l --no-color
* master
Running command: git branch -r --no-color
  svn/trunk
Running command: git config --local --get user.name
Running command: git config --local --get user.name
Running command: git config --local --get user.email
Running command: git checkout -f master
Already on 'master'
Running command: git gc

 

If you are going to use this code locally, you don’t need to proceed ahead with this article. But if you are looking at uploading this code with history to a public Git repository like GitHub or BitBucket, you can follow the next step

Upload this Local Git Repository to GitHub

 

So first you need a target GitHub Repository. You can choose 2 ways to perform this operation.

Using GitHub Website and Git in Console

Once you have created a GitHub Repository, you can copy the HTTPS URL which will appear like,

https://github.com/punitganshani/TestRepository.git

Next you need to configure local Git session to use this as remote URL

git remote add origin https://github.com/punitganshani/TestRepository.git

 

You can verify if this worked fine as shown in the screenshot below

Once this is done, a single command to push

git push –-all

 

This will push all the code from local Git to GitHub repository – includes history as well. If you have added some files manually to GitHub repository (like readme.md and .gitignore), you need to first update your local Git repository from GitHub repository using command

git pull

 

If you even after updating local Git repository, you get an error like

! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/punitganshani/TestRepository.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g. 
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

You can edit the .git\config file and add these 2 lines at the end of file and request a pull again.

[branch "master"]
    remote = origin
    merge = refs/heads/master

 

This should definitely resolve this error

Using GitHub for Windows

GitHub for Windows actually makes this quite easy for you.

First, click on the Options menu and update the path where you have got your local Git repository. Once you have updated it, you can scan for repositories.

If the repository is local, GitHub for Windows will allow you to Publish the repository to GitHub

Using XecMe to host Windows Services

March 21, 2014 Open Source, Visual Studio , ,

When you are developing server side components using .NET framework, you would either end up having a IIS hosted component (a website, WAS, Web Services (REST/SOAP/JSON, etc), HTTP Handlers, and alike) or a Windows Service for long running tasks or WCF-based services, or a scheduler task for trigger/time oriented tasks.  If the target deployment is IIS based deployment, IIS host manager takes care of the processes of hosting, application pool recycling, memory management, isolation, etc.  With Windows Service, the service console provides hosting capabilities and leaves the process of memory management to the Garbage Collector.  In addition, a very small part of the hosting process is configurable.   With the open source framework XecMe, the process of hosting a Windows Service, execution, CPU utilization, memory management can be eased and made configurable.  This post highlights how to create a Windows Service using XecMe framework and host it using command line arguments.

What is XecMe?

XecMe is an abbreviation for Execute Me.  It is an application block that provides a methodology and framework for executions and hosting batches, background processes and Windows Services.  It is a highly configurable and extensible framework and is built on the principles of task oriented design approach for solving the business problem.  XecMe also works well when integrated with Microsoft Azure in Worker Role.

At the moment, Nuget has a version that works great with .NET 4.0.  But if you are looking for .NET 4.5, you can download the source code from Codeplex and change the target .NET framework.   This framework can be best used for

  • Long running tasks
  • Windows Services
  • Azure Worker Role
  • Event based tasks
  • Context based tasks
  • Batch Processes

All these tasks are configurable and their behavior can be controlled easily by changing parameters in the configuration.

Download the latest binaries

If you are using VS2013, you can use the Package Manager to download the libraries directly or you can manually download them from XecMe On CodePlex.

image

This will create a packages.config with XecMe reference like,

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <packages>
  3.   <package id="XecMe" version="1.0.0" targetFramework="net40" />
  4. </packages>

Understanding XecMe Libaries

 

There are three binary (DLL) files that will be added in your project (Class Library, Azure Worker Role, Windows Service, Website, etc).

  • XecMe.Core.dll – As the name suggests, this library consists of classes that serve core functionalities such as hosting services, reading configuration, rule rngine, task manager, task runners (or execution engines) and utilities
  • XecMe.Common.dll – This library supports the core library by providing functionalities such as argument parsers, reflection utilities, translation provider and most importantly CPU usage limiter
  • XecMe.Configuration.dll – This library also supports core library by providing extension methods and parsers for configuration management

Creating a Windows Service

 

The first step to developing Windows Service is to first start defining a task that can be translated to a Windows Service.   Once you have done that, you can create one or multiple Windows Services in a class library.  Let’s say one of the service name is LongRunningTaskAsService.  This class needs to be inherited from XecMe.Core.Services.IService interface as shown below.  Just like you implement any other Windows Service, you can define your code in common methods such as OnStart, OnPause, OnContinue, OnStop. However, there is an additional method OnShutdown which is called just before the service stops.

 

  1. using System;
  2. using XecMe.Core.Services;
  3. using System.Threading;
  4.  
  5. namespace XecMeSamples
  6. {
  7.     public class LongRunningTaskAsService : IService
  8.     {
  9.         private string _serviceName = "LongRuninngTaskAsService";
  10.         private Thread _thread;
  11.         private ManualResetEvent _shutdownEvent;
  12.  
  13.         public bool CanPauseAndContinue
  14.         {
  15.             get { return false; }
  16.         }
  17.  
  18.         public void OnContinue()
  19.         {
  20.             throw new NotSupportedException();
  21.         }
  22.  
  23.         public void OnPause()
  24.         {
  25.             throw new NotSupportedException();
  26.         }
  27.  
  28.         public void OnShutdown()
  29.         {
  30.             _shutdownEvent.Set();
  31.         }
  32.  
  33.         public void OnStart()
  34.         {
  35.             _thread = new Thread(RunInBackground)
  36.                 {
  37.                     Name = "Worker Thread",
  38.                     IsBackground = true
  39.                 };
  40.  
  41.             _shutdownEvent = new ManualResetEvent(false);
  42.             _thread.Start();
  43.         }
  44.  
  45.         private void RunInBackground()
  46.         {
  47.             // run some thing in background
  48.             while (!_shutdownEvent.WaitOne(0))
  49.             {
  50.                 // Replace the Sleep() call with the work you need to do
  51.                 Thread.Sleep(1000);
  52.             }
  53.         }
  54.  
  55.         public void OnStop()
  56.         {
  57.             if (!_thread.Join(3000))
  58.             {
  59.                 // give the thread 3 seconds to stop
  60.                 _thread.Abort();
  61.             }
  62.         }
  63.  
  64.         public string ServiceName
  65.         {
  66.             get { return _serviceName; }
  67.             set { _serviceName = value; }
  68.         }
  69.     }
  70. }

Configuration

 

Each service requires a configuration files.  This configuration file should contain XecMe settings along with application settings.  In the above case, since we have 2 services we will have 2 configuration files as shown in the Solution Explorer.

image

A sample configuration (for LongRunningTaskAsService) would appear like,

  1. <?xml version="1.0"?>
  2. <configuration>
  3.   <configSections>
  4.     <section name="xecMe.Core" type="XecMe.Configuration.XecMeSectionGroup, XecMe.Configuration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e34de6d98c38471a" />
  5.   </configSections>
  6.   <xecMe.Core>
  7.     <extensions>
  8.       <settings>
  9.         <add name="IService" type="XecMeSamples.LongRunningTaskAsService, XecMeSamples"/>
  10.       </settings>
  11.     </extensions>
  12.   </xecMe.Core>
  13. </configuration>

Service Installation

 

XecMeHost.exe acts as a service host and installer. So when you execute a the command below, the service will be installed on the target machine with appropriate settings.  So first thing to remember is to put all assemblies (XecMe DLLs and XecMeHost and your application assemblies) in one folder (from where the service has to be executed).   Alternatively, you can register all XecMe DLLs in GAC and keep only XecMeHost and your application assemblies in that folder

image

You will require administrative rights to perform this action if your OS supports UAC so you may require to run Command Prompt as an Administrator to avoid any errors.  Once you have done this, you can execute the following command

XecMeHost.exe -i -n="LongRunningTaskAsService"
-p="C:\ShortFolder"
-c="C:\ShortFolder\Config\LongRunningTaskAsService.config"
-cpu=50
-a=LocalService
-m=Automatic
-v

Let’s understand the syntax

image

This will install the service on your machine

image

Testing your Windows Service

You can navigate to Service Console to Start the service and test it.  If it fails to start for any reason, you can view the properties of the service to get the executable path and execute the executable path on DOS prompt.

image

For above service the path to executable is:

"C:\ShortFolder\XecMeHost.exe" -s  -p="C:\ShortFolder" -c="C:\ShortFolder\Config\LongRunningTaskAsService.config" -n="LongRunningTaskAsService"

If there are any configuration or start up issues, they will visible on the command prompt

Uninstalling your Windows Service

You can uninstall a Windows Service using Service Controller

installutil /u <servicename>
sc delete <servicename>

Or use XecMeHost like

XecMeHost  /u -n=LongRunningTaskAsService

Source Code

 

Download the source code :

Understanding Mock and frameworks – Part 4 of N

January 25, 2013 CSharp, Open Source, Unit Testing, Visual Studio , , , , , , , , ,

I am glad that this series has been liked by large audience and even got focus on Channel9 Video and that motivates to continue this series further on.

This series on Mock and frameworks takes you through Rhino Mocks, Moq and NSubstitute frameworks to implement mock and unit testing in your application.  This series of posts is full of examples, code and illustrations to make it easier to follow.  If you have not followed this series through, I would recommend you to read following articles

  1. Understanding Mock and frameworks – Part 1 of N – Understanding the need of TDD, Mock and getting your application Unit Test ready
  2. Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq
    1. Understanding Mock and frameworks – Part 3 of N -  Understanding how to Mock Methods calls and their Output – Rhino Mocks, NSubstitute and Moq

    This part of the series will focus on exception management, and subscribing to events

    Exception Management

     

    Going back to the second post where we defined our Controller and Service interface,  the method GetObject throws an ArgumentNullException when a NULL value is passed to it.  The Exception Management with Mock allows you to change the exception type and hence, ignore the exception peacefully.

    Using Rhino Mocks

    Using the Stub method of Mocked Service, you can override the exception type.  So instead of getting a ArgumentNullException, we will change the exception to InvalidDataException.  But do not forget to add a ExceptedException attribute to the method (line 2 in example below) that ensures a peaceful exit.

    1. [TestMethod]
    2. [ExpectedException(typeof(InvalidDataException))]
    3. public void T05_TestExceptions()
    4. {
    5.     var service = MockRepository.GenerateMock<IService>();
    6.     // we are expecting that service will throw NULL exception, when null is passed
    7.     service.Stub(x => x.GetObject(null)).Throw(new InvalidDataException());
    8.     
    9.     Assert.IsNull(service.GetObject(null)); // throws an exception
    10. }

    Using NSubstitute

    NSubstitute does not expose a separate /special function like Throw. It treats exceptions as a return value of the test method. So u

    1. [TestMethod]
    2. [ExpectedException(typeof(InvalidDataException))]
    3. public void T05_TestExceptions()
    4. {
    5.     var service = Substitute.For<IService>();
    6.     // we are expecting that service will throw NULL exception, when null is passed
    7.     service.GetObject(null).Returns(args => { throw new InvalidDataException(); });
    8.     
    9.     Assert.IsNull(service.GetObject(null)); // throws an exception
    10. }

    Using Moq

    Moq exposes Throws method just like Rhino Mocks

    1. [TestMethod]
    2. [ExpectedException(typeof(InvalidDataException))]
    3. public void T05_TestExceptions()
    4. {
    5.     var service = new Mock<IService>();
    6.     // we are expecting that service will throw NULL exception, when null is passed
    7.     service.Setup(x => x.GetObject(null)).Throws(new InvalidDataException());
    8.     
    9.     Assert.IsNull(service.Object.GetObject(null)); // throws an exception
    10. }

    Event Subscriptions

    The next topic of interest in this series is managing Event Subscriptions with Mock frameworks. So the target here is to check if an event was called when some methods were called on the mocked object

    Using Rhino Mocks

    The code here is little complex compared to all previous examples.  So we are adding a ServiceObject to the controller which raises an event. Unlike real time examples, this event is hooked to the DataChanged method of the service. This means the controller will raise an event and a service method will be called dynamically.

    1. [TestMethod]
    2. public void T06_TestSubscribingEvents()
    3. {
    4.     var service = MockRepository.GenerateMock<IService>();
    5.     var controller = new Controller(service);
    6.  
    7.     controller.CEvent += service.DataChanged;
    8.     ServiceObject input =new ServiceObject("n1", Guid.NewGuid());
    9.     controller.Add(input);
    10.  
    11.     service.AssertWasCalled(x => x.DataChanged(Arg<Controller>.Is.Equal(controller),
    12.         Arg<ChangedEventArgs>.Matches(m=> m.Action == Action.Add &&
    13.                                               m.Data == input)));
    14. }

    Let’s go into detail of the AssertWasCalled statement – it takes a method handler in the lambda expression. Some of the other methods of interest are Arg<T> Is.Equal and Matches. The method Arg<T> creates a fake argument object of a particular type. Is.Equal() method assigns a value to it and Matches method adds like a filter on the values of input parameters to the original ‘DataChanged’ method.

    Using NSubstitute

    NSubstitute has a different set of methods for event subscription.  The output of Received() method exposes all valid method calls available, Arg.Is<T>() creates fake object for mocked service.

    1. [TestMethod]
    2. public void T06_TestSubscribingEvents()
    3. {
    4.     var service = Substitute.For<IService>();
    5.     var controller = new Controller(service);
    6.  
    7.     controller.CEvent += service.DataChanged;
    8.     ServiceObject input = new ServiceObject("n1", Guid.NewGuid());
    9.     controller.Add(input);
    10.  
    11.     service.Received().DataChanged(controller,
    12.       Arg.Is<ChangedEventArgs>(m => m.Action == Action.Add && m.Data == input));
    13. }

    Using Moq

    Apart from having different names of methods from NSubstitute, Moq does exactly the same as other two frameworks

    1. public void T06_TestSubscribingEvents()
    2. {
    3.     var service = new Mock<IService>();
    4.     var controller = new Controller(service.Object);
    5.  
    6.     controller.CEvent += service.Object.DataChanged;
    7.     ServiceObject input = new ServiceObject("n1", Guid.NewGuid());
    8.     controller.Add(input);
    9.  
    10.     service.Verify(x => x.DataChanged(controller,
    11.         It.Is<ChangedEventArgs>(m => m.Action == Action.Add && m.Data == input)));
    12. }

    The Code for Download

    Understanding RhinoMocks, NSubstitute, Moq by Punit Ganshani

    So that concludes how to use Rhino Mocks, NSubstitute and Moq for Exception Handling and Event Subscriptions.  Should you have any questions, feel free to comment on this post.

    Understanding Mock and frameworks – Part 3 of N

    January 22, 2013 CSharp, Open Source, Unit Testing, Visual Studio , , , , , , , ,

    This series on Mock frameworks takes you through Rhino Mocks, Moq and NSubstitute frameworks to implement mock and unit testing in your application.  This series of posts is full of examples, code and illustrations to make it easier to follow.  If you have not followed this series through, I would recommend you reading following articles

    1. Understanding Mock and frameworks – Part 1 of N – Understanding the need of TDD, Mock and getting your application Unit Test ready
    2. Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq

    In Part 1, we understood how to refactor our application so that it can be Unit tested with Mock frameworks and in Part 2, we understood 3 stages of Mocking – Arrange, Act and Assert with an example.  Now as understood in Part 2 ‘Arrange’ is the stage where implementation in all the three framework differs.  So in this post, we will focus on ‘Arrange’ and explore various types of mocking.

    Mocking Method Calls

    In the examples below, we will mock a method call GetCount of the service so that it returns value 10.  We will clear the controller and then check if GetCount method was actually called.  If this example was called without using Mock frameworks, the outputs would have been different. Please note that in the below examples all the mock methods are applied on the service; however, you can apply them on the controller as well.

    Using Rhino Mocks

    Rhino Mocks uses methods AssertWasCalled and AssertWasNotCalled to check if the ‘actual’ method was invoked.

    1. [TestMethod]
    2. publicvoid T03_TestMethodCall()
    3. {
    4.     var service = MockRepository.GenerateMock<IService>();
    5.     var controller = newController(service); // injection
    6.     service.Stub(x => x.GetCount()).Return(10);
    7.     controller.Clear();
    8.     service.AssertWasNotCalled(x => x.GetCount());
    9.     service.AssertWasCalled(x => x.Clear());
    10. }

    Using NSubstitute

    NSubstitute uses DidNotReceive and Received methods to check if the ‘actual’ methods got a call or not.  There are multiple similar methods available such as DidNotReceiveWithAnyArgs, ClearReceivedCalls, and ReceivedCalls.  Each of these functions can be used to manipulate or check the call stack.

    1. [TestMethod]
    2. publicvoid T03_TestMethodCall()
    3. {
    4.     var service = Substitute.For<IService>();
    5.     var controller = newController(service);
    6.     service.GetCount().Returns(10);
    7.     controller.Clear();
    8.     service.DidNotReceive().GetCount();
    9.     service.Received().Clear();
    10. }

    Using Moq

    Moq standardizes the verification of method calls with a single method Verify. The Verify method has many overloads allowing to even evaluate an expression.

    1. [TestMethod]
    2. publicvoid T03_TestMethodCall()
    3. {
    4.     var service = newMock<IService>();
    5.     var controller = newController(service.Object);
    6.     service.Setup(x => x.GetCount()).Returns(0);
    7.     controller.Clear();
    8.     service.Verify(x => x.GetCount(), Times.Never());
    9.     service.Verify(x => x.Clear());
    10. }

    Mocking Method Calls and their Output

    The next example focuses on a more real time scenario, where we will mock a method that takes input parameters and returns an output parameter.  The service will be mocked and we will test the functionality of our controller.

    So going back to Part 2 of our series, if a NULL input is passed to Add method of the controller it returns back false.  For any non-NULL input, it gives a call to Add method of the service and returns back the value returned by the service.  So we will pass two different types of objects to the controller and return 2 different outputs based on our mock.  When we pass ServiceObject with name ‘m1’ we will mock it to return value ‘false’ while ServiceObject with name ‘m2’ should return value ‘true’

    Using Rhino Mocks

    What’s important to focus at his moment is that we altered the behavior and hence used the method Stub on the mocked service and then later we defined the expected result by the method Returns.

    1. [TestMethod]
    2. publicvoid T04_TestConditions()
    3. {
    4.     var service = MockRepository.GenerateMock<IService>();
    5.     var controller = newController(service); // injection
    6.     ServiceObject oneThatReturnsFalse = newServiceObject(“m1”, Guid.NewGuid());
    7.     ServiceObject oneThatReturnsTrue = newServiceObject(“m2”, Guid.NewGuid());
    8.     service.Stub(x => x.Add(oneThatReturnsFalse)).Return(false);
    9.     service.Stub(x => x.Add(oneThatReturnsTrue)).Return(true);
    10.     Assert.AreEqual(false, controller.Add(oneThatReturnsFalse));
    11.     Assert.AreEqual(true, controller.Add(oneThatReturnsTrue));
    12. }

    Using NSubstitute

    NSubstitute does not require any method like Stub. When you are defining any method on the mocked service object, it automatically assumes that the framework has to alter the behavior of the method.  Just like Rhino Mocks, method Returns defines the expected mocked output of that method.

    1. [TestMethod]
    2. publicvoid T04_TestConditions()
    3. {
    4.     var service = Substitute.For<IService>();
    5.     var controller = newController(service);
    6.     ServiceObject oneThatReturnsFalse = newServiceObject(“m1”, Guid.NewGuid());
    7.     ServiceObject oneThatReturnsTrue = newServiceObject(“m2”, Guid.NewGuid());
    8.     service.Add(oneThatReturnsFalse).Returns(false);
    9.     service.Add(oneThatReturnsTrue).Returns(true);
    10.     Assert.AreEqual(false, controller.Add(oneThatReturnsFalse));
    11.     Assert.AreEqual(true, controller.Add(oneThatReturnsTrue));
    12. }

    Using Moq

    Moq like Rhino Mocks requires a special method call Setup and then followed by another method call to Returns method

    1. [TestMethod]
    2. publicvoid T04_TestConditions()
    3. {
    4.     var service = newMock<IService>();
    5.     var controller = newController(service.Object);
    6.     ServiceObject oneThatReturnsFalse = newServiceObject(“m1”, Guid.NewGuid());
    7.     ServiceObject oneThatReturnsTrue = newServiceObject(“m2”, Guid.NewGuid());
    8.     service.Setup(x => x.Add(oneThatReturnsFalse)).Returns(false);
    9.     service.Setup(x => x.Add(oneThatReturnsTrue)).Returns(true);
    10.     Assert.AreEqual(false, controller.Add(oneThatReturnsFalse));
    11.     Assert.AreEqual(true, controller.Add(oneThatReturnsTrue));
    12. }

    Strict Mock vs Normal Mock

     

    Strict Mock creates brittle tests.   A strict mock is a mock that will throw an exception if you try to use any method that has not explicitly been set up to be used.  A dynamic (or loose, normal) mock will not throw an exception if you try to use a method that is not set up, it will simply return a default value from the method and keep going.  The concept can be applied to any mocking framework that supports these 2 types of mocking.

    Let’s see an example with Rhino Mocks.  We will alter our controller class to add a method Find that invokes two methods of our IService interface

    1. publicpartialclassController
    2. {
    3.     publicServiceObject Find(string name)
    4.     {
    5.         if (string.IsNullOrEmpty(name))
    6.             thrownewArgumentNullException(name);
    7.         if (_service.GetCount() > 0)
    8.         {
    9.             /* Can have more business logic here */
    10.             return _service.GetObject(name);
    11.         }
    12.         else
    13.         {
    14.             returnnull;
    15.         }
    16.     }
    17. }

    Now with a Strict Mock on the method GetObject and no mock on method GetCount, we should expect an exception to be thrown.  However, when using a dynamic/loose mock, GetCount will return its default value which is Zero (0 ) and hence Find Method will return NULL

    1. [TestMethod]
    2. publicvoid T10_TestStrictMock()
    3. {
    4.     // data
    5.     string name = “PunitG”;
    6.     ServiceObject output = newServiceObject(name, Guid.NewGuid());
    7.     // arrange
    8.     var service = MockRepository.GenerateMock<IService>();
    9.     var controller = newController(service);
    10.     var strictService = MockRepository.GenerateStrictMock<IService>();
    11.     var controllerForStrictMock = newController(strictService);
    12.     // act
    13.     service.Stub(x => x.GetObject(name)).Return(output);
    14.     // assert
    15.     Assert.AreEqual(null, controller.Find(name));
    16.     Assert.AreEqual(output, controllerForStrictMock.Find(name)); // exception expected
    17. }

    When you execute this Test, the first assert will pass and the second assert will throw an exception.  Overall the test will fail.

    The Code for Download

    Understanding RhinoMocks, NSubstitute, Moq by Punit Ganshani

    Hope this helps. In the next post, we will explore how to mock Exceptions and Events

    Understanding RhinoMocks, NSubstitute and Moq

    January 20, 2013 CSharp, Open Source, Visual Studio , , , , ,

    For those who are following me on Codetails, would know that I am actively blogging (since Nov 2012) on Codetails on all technology stuff.  One of the series of articles I wrote on Codetails that got great applause from the technical community is on Mocking Frameworks with .NET Here are the links that describe the technical details

    1. Understanding Mock and frameworks – Part 1 of N – Understanding the need of TDD, Mock and getting your application Unit Test ready
    2. Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq
    3. Understanding Mock and frameworks – Part 3 of N –  Understanding how to Mock Methods calls and their Output – Rhino Mocks, NSubstitute and Moq
    4. Understanding Mock and frameworks – Part 4 of N –  Understanding how to Mock Exceptions and Event Subscriptions  – Rhino Mocks, NSubstitute and Moq

    And here is my proud moment – featured on Microsoft Channel9

    Linkhttp://channel9.msdn.com/Shows/This+Week+On+Channel+9/TWC9-January-18-2013

    Understanding Mock and frameworks – Part 2 of N

    January 10, 2013 CSharp, Open Source, Unit Testing, Visual Studio , , , , , , , , ,

    Continuing on where we left in the previous post – Understanding Mock and frameworks Part 1 – this post will take a very simple example and illustrate how to implement Mock frameworks.  I was mailed by one of our readers asking if I could define TDD – Test Driven Development in my words.

    Test driven development is a methodology that states that test cases should be driving the design decisions and development.  This also that TDD advocates knowing the expected behaviour of our application (or a part of it), before we write the code.  It also enforces incremental design and allows us to write just enough code to pass our test. That means, no redundant code (YAGNI – You ain’t gonna need it) ships with our product, and our code is fairly simple (KISS – Keep it simple, stupid!) to understand. Sounds cool, isn’t it?

    So you start writing tests first, design your application gradually and then start writing the implementation so that each test passes.  I prefer TDD over Test-After-Development (TAD) where you first design your application and write code.  Once your code is complete (or partially complete), you write the required test cases. Theoretically, a TAD system would appear to produce as high-quality product as TDD would.  But to my opinion, TAD involves taking design decisions up front – right from the start rather than taking incremental baby steps.  This also means that when time to delivery is short and critical, there are chances of not having a 100% code coverage by TAD approach. Also, a developer can fall victim to his own ego that “I don’t bad write code that needs to be tested”

    That’s the way I see Test Driven Development (TDD) and Test-After-Development (TAD). So let’s get back to our topic of interest – an example to get started with Unit Testing with Mocks.

    The service (or data source) interface

    Assume that you are building an application that interfaces with just one service.  We have refactored our application to follow SOLID principles such as SRP, ISP, DIP and DI.  The service implements an interface IService.   This service interface could be interface of your internal service, or an external service whose behaviour and availability can not be controlled by you.

    At this moment, we are not really interested in the implementation of IService and we will restrict our scope to the interface and the consumer (i.e. our application).

    public interface IService
        {
            string ServiceName { get; set; }
    
            bool Add(ServiceObject input);
            bool Remove(ServiceObject input);
            void Clear();
            int GetCount();
            ServiceObject GetObject(string name);
    
            void DataChanged(object sender, ChangedEventArgs args);
        }
    
        public class ServiceObject
        {
            public string Name { get; set; }
            public Guid Ref { get; set; }
            public DateTime Created { get; set; }
    
            public ServiceObject(string name, Guid reference)
            {
                Name = name;
                Ref = reference;
                Created = DateTime.Now;
            }
        }
    
        public enum Action
        {
            Add,
            Remove,
            Clear
        }

    The Controller (or our application)

     

    The consuming class (let’s call it Controller) isolates the dependency on the implementation of service object and ensures that the consuming class injects the appropriate service object.

    public class Controller
        {
            private IService _service;       
    
            public Controller(IService service)
            {
                _service = service;
            }
        }

    In reality, the Controller class could be just a facade or can contain business logic, or data manipulation and a lot of other complex logic.  For this example, it is kept simple and restricted to only service calls.   So our controller class looks like,

    1. public class Controller
    2. {
    3.     private IService _service;
    4.  
    5.     /// <summary>
    6.     /// To demonstrate events in Mock
    7.     /// </summary>
    8.     public event EventHandler<ChangedEventArgs> CEvent;
    9.  
    10.     public Controller(IService service)
    11.     {
    12.         _service = service;
    13.     }    
    14.     
    15.     private void RaiseEvent(Action action,
    16.                     ServiceObject input)
    17.     {
    18.         /* Can have more business logic here */
    19.         if (CEvent != null)
    20.             CEvent(this, new ChangedEventArgs(action, input));
    21.     }
    22.  
    23.     /// <summary>
    24.     /// To demonstrate methods with parameters and return value
    25.     /// in Mock
    26.     /// </summary>
    27.     public bool Add(ServiceObject input)
    28.     {
    29.         if (input == null)
    30.             return false;
    31.  
    32.         /* Can have more business logic here */
    33.  
    34.         _service.Add(input);
    35.         RaiseEvent(Action.Add, input);
    36.  
    37.         return true;
    38.     }
    39.  
    40.     /// <summary>
    41.     /// To demonstrate simple method calls in Mock
    42.     /// </summary>
    43.     public void Clear()
    44.     {
    45.         _service.Clear();
    46.     }
    47. }

     

    So to create an object of our controller, we need to pass an instance of a class that implements IService. As said earlier, we will not implement the interface IService to ensure that we do not have a functional service (to create a scenario of an unavailable service) for testing.  So let’s get started with our Mocking the interface IService.

     

    Mocking – Step Arrange

    All our tests will follow three step process

    • Arrange – This step involves creating a service/interface mock (using a Mock framework) and creating all required objects for that service/interface.  This step also includes faking the object behaviour.
    • Act – This step involves calling a method of the service, or performing any business functionality
    • Assert – This step usually asserts whether the expected result is obtained from the previous step (‘Act’) or not

    Step Arrange: With Rhino Mocks

    Rhino Mock framework maintains a repository of Mocks.   The MockRepository can be seen to follow a Factory design pattern to generate Mocks using Generics, object(s ) of Type, or stubs.  One of the ways to generate a Mock is,

    1. // Arrange
    2. var service = MockRepository.GenerateMock<IService>();
    3. var serviceStub = MockRepository.GenerateStub<IService>();

    There is a minor difference between a Mock and a Stub. A discussion on StackOverflow explains it very appropriately or Martin Fowler has explained it brilliantly in his post on Mocks Aren’t Stubs. To keep it short and simple,

    Mock objects are used to define expectations i.e: In this scenario I expect method A() to be called with such and such parameters. Mocks record and verify such expectations. Stubs, on the other hand have a different purpose: they do not record or verify expectations, but rather allow us to “replace” the behaviour, state of the “fake”object in order to utilize a test scenario.

    If you want to verify the behaviour of the code under test, you will use a mock with the appropriate expectation, and verify that. If you want just to pass a value that may need to act in a certain way, but isn’t the focus of this test, you will use a stub.

    Once the object has been created, we need to mock the service behaviour on this fake service object.  Let’s see how to fake a property

    1. // Arrange
    2. var service = MockRepository.GenerateMock<IService>();            
    3. service.Stub(x => x.ServiceName).Return("DataService");

    Similarly, we can mock methods.  We will see mocking different types in detail later.

     

    Step Arrange: With NSubstitute

    NSubstitute makes it simpler to read, interpret and implement.

    1. // Arrange
    2. var service = Substitute.For<IService>();

    Mocking property in NSubstitute is a lot easier to remember

    1. // Arrange
    2. var service = Substitute.For<IService>();            
    3. service.ServiceName.Returns("DataService");

    Step Arrange: With Moq

    Moq like Rhino Mocks also has MockRepository.  You can choose a mock to be a part of MockRepository or to let it hang individually.  Both the methods are shown as below.

    1.           // Arrange
    2.             var service = newMock<IService>();
    3.  
    4.           MockRepository repository = new MockRepository(MockBehavior.Default);
    5.           var serviceInRepository = repository.Create<IService>();

    Mocking property is somewhat similar to Rhino Mocks

    1.           // Arrange
    2.             var service = newMock<IService>();
    3.           service.Setup(x => x.ServiceName).Returns("DataService");

    Rhino Mocks and Moq both have two different types of behaviours’ – Strict and Loose (default).  We will look into what each of them means in the next article.

    Mocking – Step Act, Assert

    Once we have the fake service and have defined the expected behaviour, we can implement the next step.  This step involves calling a method of the service, or performing any business functionality. So here we can call a method of service, or use its output to do some work.  So our examples will vary from setting something in mocked service object to calling its methods.

    Step Act and Assert: With Rhino Mocks and NSubstitute

    As the output of the first step, both Rhino Mock and NSubstitute give you directly an object of IService (named, service).  So you can directly use this object as a substitute of the actual service.  The object service is a fake object whose ServiceName is expected to be "DataService".  Just to remind that in actual, neither the implementation of the service nor a real object of the service exists.  We are dealing with fake objects through all our examples

    1. // Act
    2. var actual = service.ServiceName;
    3.  
    4. // Assert
    5. Assert.AreEqual("DataService", actual);

    This test on execution will give a PASS

    Step Act and Assert: With Moq

    Moq unlike the other two frameworks does not directly provide you a fake service object.  It provides you the fake service object in one of its properties called ‘Object’.  Everything else remains the same

    1. // Act
    2. var actual = service.Object.ServiceName;
    3.  
    4. // Assert
    5. Assert.AreEqual("DataService", actual);

    If you put together the code, it forms our first Unit Test w/Mock frameworks.

    The Code for Download

    Understanding RhinoMocks, NSubstitute, Moq by Punit Ganshani

    In the next article, we will look into creating Mocks for methods using these frameworks.

    Understanding Mock and frameworks – Part 1 of N

    December 31, 2012 CSharp, Open Source, Unit Testing, Visual Studio , , , , , ,

    We have several posts on the Internet that focus on Test Driven Development and its benefits.  There is a group of SCRUM Masters around who emphasize on how Test Driven Development (TDD) is beneficial and can change the way you write and test code.  I completely agree that Agile and TDD can help you manage your teams, code, product quality and communication in a better way.  But this is not yet another post on Test Driven Development, or Unit Testing.  This is one of the articles on Test Mocking.  How is it different from others?  This series assumes that you have no knowledge of mocking and your application is not unit-test ready so it guides you on the concept of mocking, preparing your application, using mocking frameworks, comparing them and ensuring that your code is ‘Well-Tested and Covered’

    So let’s get started!

    Understanding Mock – What, Why?

    Now if you are following the discipline of TDD and are building large scale enterprise application that interacts with services, databases, or other data sources, writing data driven unit tests becomes a challenge.  Test setup (for each test) becomes more complicated and challenging than the actual unit test.  This is where the concept of Mock comes into picture.

    Mock – to deceive, delude, or disappoint.

    As the English definition of the word Mock suggests we want to deceive the process of unit test with a substituted data rather than retrieving a data set from the actual service or database.  This also means that we are getting rid of various other aspects of service availability, environment setup, data masking, data manipulation and conversion.  It is like telling the unit test

    Do not worry about the data source.  Stop worrying about the actual data and use the mocked up data.  Test the logic!

    OK, this sets a premise on why mocking is required!   Do you need an alternate definition to understand this even better?

    A mocking framework fakes objects to replace any dependencies you have and thereby, allow you to tell them (the mocked code) to behave as you want it to.  So even if the service may not exist if you have asked the mocking framework to mock it, the mocking framework will provide a fake service when requested by the consuming code.

    Refactoring application to be Unit Test ready

     

    Let’s assume that you were told one fine day that your application, for the simplicity is a typical 3-tier web application, needs to be unit tested.   So you start with the first step of analysing the most critical part that constitutes 80% of your business functionality.  Now there are two possibilities – either your application has been designed following the SOLID Principles or it is a legacy application built without considering these design principles.   The second possibility requires more effort on your side, so let’s assume that your application is not design correctly and you want to Unit Test it with Mocking.

    Single Responsibility Principle – Isolate your data sources

    First,  try isolating the all the data sources into repositories.  This means that if your application is reading configuration from XML file, business data from SQL database, real-time feeds from Web Services, and alike then check if the principle of isolation and single-responsibility is applied correctly.  This means that your application should not have a class that defines actions responsible for reading data from multiple sources, manipulate it, do some calculations, or store it.

    Your application should have one class object per data source (DAL class) that is responsible for retrieving / storing data in that data source.  If the need is to do some calculations, manipulations on one or more data sources, then there should be another class object who should have this responsibility.

     

    Interface Segregation Principle – Use interfaces instead of objects

    Now that you have your data sources isolated and have single responsibility of interacting with one-and-only-one data source, your next step is to ensure that all the references of this class object (that represents the data source) is not referenced as an object in all the calling objects.

    In simple words code like this,

    1. ConfigurationStore store = new ConfigurationStore();
    2. store.RefreshConfiguration();

    Needs to be refactored into something like,

    1. IConfigurationStore store = new XmlConfigurationStore();
    2. store.RefreshConfiguration();

    Please note the two changes in the above code. One – instead of creating an object of class ConfigurationStore we are now creating an object of an interface IConfigurationStore and have given more meaningful name to the class as XmlConfigurationStore.  This is also referred as ISP

     

    Dependency Inversion and Injection – Refactoring the construction of data source

    Now that you have isolation between classes representing data sources and have interfaces defining the definition of these classes, the next step is to ensure that there is no hard dependency on the implementation of these classes.  In other words,  we don’t want to make our consumer class dependent on the implementation of the class (representing data source) instead we want it to be dependent on the definition of this interface.

    Higher level module (the consuming classes responsible for any data manipulations, representation, etc) should not depend on low level module (the object of data source/DAL) rather should depend on a layer of abstraction (like an interface)

    This is known as DIP – Dependency Inversion Principle.  There are three ways to implement DIP – through constructor while constructing the higher level modules, through properties by assigning the lower level module objects to the property, or explicitly through methods.  We will not go into the details of implementation and would advise you to go through the MSDN article on Dependency Injection

    So we have a cleaner code that can be referred as unit-test-ready code

    Unit Test and Mock – How?

    Do we need any special infrastructure? Any third-party frameworks required?

    To get started with unit testing, all you need is Visual Studio 2010/2012.  Yes, that’s enough for basic testing. We build our unit tests using any one of NUnit, xUnit or MSTest and run them using appropriate tools.

    But since you are keen at implementing Mocks, you will require a well tested and proven Mocking Framework.  Three frameworks that I’ve used are

    • Rhino Mocks – This is unarguably the most adopted and extensive mocking framework with lots of features.  Some developers find it difficult the adopt considering a wide range of functionalities available.  However, post the series of articles of Mocking using this should not be difficult.
    • NSubstitute – Implementing mocking is made extremely easy using this framework
    • Moq – This is a great framework when you are developing a Silverlight application

    So, get ready to download one of the above frameworks to get your infrastructure ready.  If you are still confused which one, then

    I would recommend staying connected to this post as in the subsequent articles in the series we will see the differences in the implementation of mocking using these 3 frameworks!  We will look more into the ‘How’ aspects of implementing these frameworks!

    dI.Hook – Creating a dependency injection container

    September 9, 2012 Applications, CSharp, Open Source, Visual Studio , , , ,

    If you are new to dI.Hook, please visit the di.Hook Product Page for Overview, Release Version and Source Code.

    Some posts you might want to read would be:

    1. How to create a HookRepository?
    2. How to add hooks to HookRepository?
    3. How to add hooks via configuration file to a HookRepository?
    4. How to invoke all hooks using dI.Hook?
    5. How to invoke hooks that satisfy a condition?
    6. How to retrieve an object of hook?
    7. How to remove hooks from HookRepository?
    8. How to ignore hook on specific method?

    So this is the ninth article in the series which will deal with creating a dependency injection container and using them in your applications

    Creating a dependency container is very simple.  You can either choose a default implementation of Container, or you can implement the interface IContainer and write your own definition of container.    The implementation you would require to implement would be

    1. public interface IContainer
    2. {
    3.     ReadOnlyCollection<dIHook.Objects.ContainerItem> Collection { get; }
    4.     ReadOnlyCollection<Guid> Keys { get; }
    5.     void Register<TClass>() where TClass : class;
    6.     void Register<TClass>(Guid key) where TClass : class;
    7.     void Register<TInterface, TImplementation>() where TImplementation : class, TInterface;
    8.     void Register<TInterface, TImplementation>(Guid guid) where TImplementation : class, TInterface;
    9.     void Register<TInterface>(Guid key, TInterface objectValue);
    10.     void Register<TInterface>(TInterface objectValue);
    11.     TInterface Resolve<TInterface>() where TInterface : class;
    12.     TInterface Resolve<TInterface>(Guid key) where TInterface : class;
    13.     ReadOnlyCollection<Type> Types { get; }
    14. }

     

    Assuming that you are not implementing this interface and are using the default implementation provided with dI.Hook, you would involve having

    1. Some business interfaces and entities
    2. Container having a definition of interface and implemented entities
    3. Container resolving these entity objects

    For the sake of understanding, let’s have a eCommerce case study where we have 3 interfaces –

    • ICustomer – Represents customer and his order
    • INotifier – Notification service for the customer
    • IBillingProcessor – Processor that takes the payment type and processes the billing

    So let’s quickly set the stage with these interface and their implementation

    1. public interface IBillingProcessor
    2. {
    3.     void ProcessPayment(OnlineOrder order);
    4. }
    5. public class BillingProcessor : IBillingProcessor
    6. {
    7.     private PaymentType _paymentType;
    8.     public BillingProcessor(PaymentType paymentType) {}
    9.     public void ProcessPayment(OnlineOrder order) { }
    10. }
    11. public enum PaymentType { Cash,CreditCard}
    12. public interface ICustomer
    13. {
    14.     void UpdateCustomerOrder(int customerId, string product);
    15. }
    16. public class InternetCustomer : ICustomer
    17. {
    18.     public InternetCustomer() { }
    19.     public void UpdateCustomerOrder(int customerId, string product) { }
    20. }
    21. public interface INotifier
    22. {
    23.     void SendReceipt(OnlineOrder order);
    24. }
    25. public class EmailNotifer : INotifier
    26. {
    27.     public EmailNotifer() { }
    28.     public void SendReceipt(OnlineOrder order) { }
    29. }

         

        Now, let’s use the container with these business entities

        1. Container container = new Container();
        2. container.Register<IBillingProcessor, BillingProcessor>();
        3. container.Register<ICustomer, InternetCustomer>();
        4. container.Register<INotifier, EmailNotifer>();

         

        The above code creates a default objects of the BillingProcessor, InternetCustomer and EmailNotifier.  If you want to pass your own object you could write as below (see BillingProcessor object)

        1. Container container = new Container();
        2. BillingProcessor billingProcessor = new BillingProcessor(PaymentType.CreditCard);
        3. container.Register<IBillingProcessor>(billingProcessor);
        4. container.Register<ICustomer, InternetCustomer>();
        5. container.Register<INotifier, EmailNotifer>();

         

        Now let’s place an order on an eCommerce website using this container.  An eCommerce class would be of no use without a reference to ICustomer, IBillingProcessor and INotifier.  So eCommerce class for this example would be

        1. public class ECommerce
        2. {
        3.     public void Process(OnlineOrder order)
        4.     {
        5.         _BillingProcessor.ProcessPayment(order);
        6.         _Customer.UpdateCustomerOrder(order.CustomerId,
        7.             order.Product);
        8.         _Notifier.SendReceipt(order);
        9.  
        10.         Debug.WriteLine("Process called");
        11.     }
        12.  
        13.     public ECommerce(IBillingProcessor billingProcessor,
        14.                 ICustomer customer,
        15.                 INotifier notifier)
        16.     {
        17.         _BillingProcessor = billingProcessor;
        18.         _Customer = customer;
        19.         _Notifier = notifier;
        20.  
        21.     }
        22.  
        23.     IBillingProcessor _BillingProcessor;
        24.     ICustomer _Customer;
        25.     INotifier _Notifier;
        26. }

         

        So your eCommerce takes objects of ICustomer, IBillingProcessor and INotifier in the constructor and in the Process method, it

        1. Calls BillingProcessor to ProcessPayment for the order
        2. Calls Customer to UpdateCustomerOrder
        3. Calls Notifier to send notification

        Now let’s see how this can be invoked using dI.Hook container that we created

        1. OnlineOrder onlineOrder = new OnlineOrder()
        2. {
        3.     CustomerId = 12212,
        4.     EmailAddress = "[email protected]",
        5.     Price = 400,
        6.     Product = "NewProduct"
        7. };
        8. ECommerce commerce = container.Resolve<ECommerce>();
        9. commerce.Process(onlineOrder);

        The above code creates an object of ECommerce class.  Now what is important here is to see what internally happens.  When you call Resolve method, it tries creating an object of ECommerce class.  It finds that its constructor requires objects of IBillingProcessor, ICustomer and INotifier.  Now since you have already registered objects of these interfaces the dI.Hook Container retrieves the object from the collection and then will try to create an object of ECommerce.  If, however, ECommerce constructor required an un-registered object it will try to create a default object and add it in the container.

        So if you explicitly created an object of BillingProcessor with payment type as CreditCard and added them in Container, it will use that object; otherwise, it will use default object of BillingProcessor with payment type as Cash

        dI.Hook Container ensures that it resolves the hierarchical dependencies automatically.  However if it is unable to resolve for any reason, it will throw an exception.

        dI.Hook – How to ignore hook on specific method?

        August 9, 2012 CSharp, Open Source, Visual Studio , , ,

         

        If you are new to dI.Hook, please visit the di.Hook Product Page for Overview, Release Version and Source Code.

        Some posts you might want to read would be:

        1. How to create a HookRepository?
        2. How to add hooks to HookRepository?
        3. How to add hooks via configuration file to a HookRepository?
        4. How to invoke all hooks using dI.Hook?
        5. How to invoke hooks that satisfy a condition?
        6. How to retrieve an object of hook?
        7. How to remove hooks from HookRepository?

        So this is the eighth article in the series which will deal with

        – Ignoring one or more hook objects when executing OnInvoke in a method
        – but NOT removing the hook from the repository

        Step 1 – Creating a repository and add hooks into a repository

        The first decision in creating a hook repository is to think whether you want to have lazy loading or not. Once you have decided you can go through the steps – Creating a Hook Repository using dI.Hook

        Be selective in adding hooks into a repository if you plan to invoke all of them at one go. If you are thinking of manually adding hooks to a repository, would suggest going through – Adding hooks manually into a repository. However, if you are planning to load them through configuration you can read – Loading a configuration set of hooks into repository

        How to ignore a hook being invoked on a method?

         

        The repository created in step 1 consists of 2 hooks.

        Method One – Ignoring all hooks

         

        Ignoring all hooks
        [TestMethod] [RemoveAllHooks] public void Test_Standard_RemoveHooks()
        {
            int invokedHooks = hookRepository.InvokeAll();
            Assert.AreEqual(0, invokedHooks);
        }

         

        Method Two – Ignoring hooks with particular name

        Ignore hooks with name LogHook
        [TestMethod] [RemoveHook(new[] { "LogHook" })] public void Test_Standard_RemoveHooksWithName()
        {
            int invokedHooks = hookRepository.InvokeAll();
            Assert.AreEqual(1, invokedHooks);
        }

        or, you can have multiple hook names in the list

        Ignore multiple hooks
        [TestMethod] [RemoveHook(new[] { "LogHook", "DiagnosticsHook" })] public void Test_Standard_RemoveHooksWithName_MultipleHooks()
        {
            int invokedHooks = hookRepository.InvokeAll();
            Assert.AreEqual(0, invokedHooks);
        }

        or, using multiple attributes for doing the same

        Ignoring multiple hooks
        [TestMethod] [RemoveHook("LogHook")] [RemoveHook("DiagnosticsHook")] public void Test_Standard_RemoveHooksWithName_MultipleAttributesInMethod()
        {
            int invokedHooks = hookRepository.InvokeAll();
            Assert.AreEqual(0, invokedHooks);
        }

         

        Method Three – Ignore a hook of specific type

         

        Ignoring a hook type
        [TestMethod] [RemoveHookType(typeof(LogHook))] public void Test_Standard_RemoveHooksWithType()
        {
            int invokedHooks = hookRepository.InvokeAll();
            Assert.AreEqual(hookRepository.Hooks.Length – 1, invokedHooks);
        }

        or

        Ignoring multiple hook types
        [TestMethod] [RemoveHookType(typeof(LogHook))] [RemoveHookType(typeof(DiagnosticsHook))] [RemoveHookType(typeof(LogHook))] public void Test_Standard_AddRemoveHookCombination()
        {
            int invokedHooks = hookRepository.InvokeAll();
            Assert.AreEqual(0, invokedHooks);
        }

         

        So using these techniques, you can have a method ignore one or many hooks.  These hooks will still remain in the repository and methods without these attributes will continue to invoke their OnInvoke method.

        Follow on Feedly