NMock2 Doesn't Mock Concrete Classes

By Mithun Bose at February 19, 2010 16:36
Filed Under: Troubleshooting, Test Driven Development

Today while running unit tests using NUnit and NMock2 framework, I stumbled upon following error.

System.TypeLoadException : Could not load type 'MultiInterface1' from assembly 'Mocks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it attempts to implement a class as an interface.

This error message is very specific but probably isn't very obvious. The only time you will get this error is when you try to mock a concrete class object rather than an interface using NMock2 framework. I overlooked the fact that I was mocking a concrete class. I decided to post this because I didn't see much of help pages on this topic after googling it.

 

Test Driven Development

By Mithun Bose at February 19, 2010 14:06
Filed Under: Test Driven Development

Introduction

In my development career there have been many instances where I had just discovered a new technique and straight away realized on how much I’ve been missing out. Test Driven Development is one of such technique which I adopted couple of years ago and very much regretted not adopting it any sooner. From then on I followed TDD style of development on all the major projects that I worked on, except the ones which were of temporary nature and with super super tight deadlines

What is Test Driven Development?

In a traditional or should I dare say the old school way - testing was followed after the development phase. The testing team would perform set of Unit test, Integration Tests and various other tests only after the coding was completed.

Test Driven Development emphasises in doing exactly the opposite, stressing the need of writing test cases before writing the code itself. Now I know it seems all a bit strange to start with. How can one write test cases for something which doesn’t exist yet??? But that’s the entire point - it enforces the developer to be very clear about what tests the program should pass and what test it should fail; therefore, bringing such concerns to the forefront of the software design process.

It may sound weird, but I’ve written many class libraries and sometimes the entire project without having to run a debugger, while using the Test Driven Development method.

Steps in Test Driven Development

So on a very broad level here is the sequence for TDD.

  1. Write a test: Each new feature or more specifically before implementing each new method in a class, write a test case for that particular method first. Yes, you’ve read it right, the class and the method doesn’t exist yet, but we are writing a test case for it.
  2. Run the test: Obviously as the class/method that is being tested doesn’t exist, the test project won’t compile and you will get an error. So create the class and the corresponding method, but don’t implement the method yet, instead throw an Exception in that method. Run the test and expect it to fail, this validates that the test case fails, when the method that is to be tested is not implemented as per the test case expectations.
  3. Write some code: Write code for the corresponding method with the goal of passing the test that failed in step 2. The code doesn’t necessarily have to be elegant but should do the job that it is supposed to do. 
  4. Run the test: Run the same test again and see it passing.
  5. Refactor the code: Update/refactor the code written in step 3. The goal here is transform the inelegant code written in step 3 to elegant code. After refactoring run the test and see it pass.

 Repeat the above steps for each new feature that is added in the code.

In my next blog in this series, I’ll demonstrate the above steps using Visual Studio and NUnit testing framework.

MessageContract Vs DataContract

By Mithun Bose at February 07, 2010 19:55
Filed Under: .NET Framework, WCF

For anyone new to WCF, this probably is the most common question they get. Why do we need MessageContract when DataContract can do the job?

A very simple answer to the question is, when you need a higher level of control over the message, such as sending custom SOAP header, you then use MessageContract instead of DataContract. But in my opinion, most of the messaging needs can be catered by DataContracts.

This is the extract from MSDN : Sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.

To elborate on the above mentioned MSDN extract, a message contract allows you to specifically control which elements will be in the SOAP header, and which will be in the SOAP body and this isn't possible using the DataContract. As DataContracts represent types. Messages are not used as types but rather the payload a method operates on and they are specific to the operation they are passed to and from.

This situation arises when you have a communication partner which requires a very specific format and you have to tweak your SOAP messages to match that given layout exactly. In my view, always use DataContracts unless you have to use MessageContract for a very good reason.

One of the hypothetical situation could be your communication partner would like to have a custom security header with username and hashed password. So you could have a message contract something similar to the below

 

[MessageContract]
public class BankingTransaction
{
  [MessageHeader] public string UserName;
  [MessageHeader] public string Password;
  [MessageBodyMember] private Account sourceAccount;
  [MessageBodyMember] private Account targetAccount;
  [MessageBodyMember] public int amount;

}

Notice on the above contract the UserName and Password are decorated with MessageHeader attribute. The generated SOAP message with WCF basicHttpBinding will look like following:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" 
xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
http://tempuri.org/IService1/MoveAccountData
</Action>
    <h:Password xmlns:h="http://tempuri.org/">HashPassword</h:Password>
    <h:UserName xmlns:h="http://tempuri.org/">TestUser</h:UserName>
  </s:Header>
  <s:Body>
    <BankingTransaction xmlns="http://tempuri.org/">
      <amount>10</amount>
      <sourceAccount>1234</sourceAccount>
      <targetAccount>5678</targetAccount>
    </BankingTransaction>
  </s:Body>
</s:Envelope>

 

Notice the SOAP the password and username members are serialized as SOAP header and the remaining members were serialized as SOAP body.

This was just one of the e.g. of the level of control that could be achieved by MessageContract. There are other controls such as encrypting or signing part of the messages, but that could be a blog post for another day.

 

 

WCF Service in IIS 7.0

By Mithun Bose at January 26, 2010 16:31
Filed Under: .NET Framework, Troubleshooting, WCF

Sometimes on hosting WCF service on IIS7.0 you might receive the following error

HTTP Error 404.3 – Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map. Detailed Error InformationModule StaticFileModule.

This happens when IIS7.0 doesn't know how to handle the .svc files. To fix this we need to register WCF with IIS7.0, following are the steps:

  1. Run Visual Studio 2008 Command Prompt as “Administrator”.
  2. Navigate to C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation.
  3. Run this command servicemodelreg –i.

The servicemodelreg is a command line tool which provides the ability to manage the registration on ServiceModel on a machine. There is more info on this commans on MSDN here.

 

Set up your first ASP.NET page on Linux

By Mithun Bose at January 25, 2010 06:23
Filed Under: .NET Framework, ASP.NET, MONO

Introduction

A few days ago I had a requirement to test and run a ASP.NET page on Linux on Mono .NET framework. Mono is an open source project led by Novell to create an Ecma standard compliant, .NET-compatible set of tools, including among others a C# compiler and a Common Language Runtime. Mono can be run on Linux, BSD, UNIX, Mac OS X, Solaris and Windows operating systems.

There are loads of documenation on MONO site and there are numerous configurations options available. In this post I've listed down the steps on how to quickly get your first ASP.NET page up and running on a Linux platform.

Steps

1) Install Mono Extension: If you are working on SUSE platform, you have to install Mono extension, you can download the evaluation or commercial package from here. SUSE platform comes with inbuilt MONO framework; however, this version of Mono is not built to be a platform to host ASP.NET and other .NET server applications. That's why you need to install the extension, which includes latest .NET features, such as ASP.NET 2.0 , AJAX, MVC and it can also be upgraded when new features of .NET becomes available in Mono.

The installation is very straight forword. Once you have downloaded the ISO file, run Yast to add this software. The full installation intructions is here.

2) Configure Apache to load Mono: Open the apache config file. The config file name is httpd.conf and it is usually in /etc/apache2 directory, add following line in httpd.conf

Include /opt/novell/mono/mod_mono.conf

The actual path to mod_mono.conf might vary depending on the distribution you use or the path where you installed apache.

Mod_Mono is an Apache module that provides ASP.NET support for the Apache web server. Click here if you interested in more details.

3) Configure the mod_mono.conf: The mod_mono configuration defaults to running the 1.0 runtime for applications, if you want to use the 2.0 runtime, you can just use the MonoServerPath directive to point to the 2.0 server, like this:

 

MonoServerPath "/usr/bin/mod-mono-server2"

4) Restart the Apache service: After changing the configuration files, you have to restart the apache service, use the following command:

apache2ctl restart

5) Copy or create the new ASP.NET website: You can copy or create simple ASP.NET page in the Apache2 www home directory. In my environment it is /srv/www/htdocs. You can find the settings in httpd.conf file. In this folder you can create a new folder names MonoTest.  So if you just copy and paste a simple ASP.NET hello world page to /srv/www/htdocs/MonoTest/. Assuming the hello world page file name is HelloWorld.aspx, then after you have copied the files browse to http://localhost/MonoTest/HelloWorld.aspx and you should see your first ASP.NET page up and running in the Linux platform.

The interesting fact is Mono can run sites which are precompiled using Visual Studio and there is no need to recompile in Mono.

6) Update the web.config file: A point to note is that mono only supports None or Forms Authentication mode and in Visual Studio the authentication mode defaults to Windows. So you probably have to update the setting in the web.config in case you getting authentication error in step 5, see following:

<authentication mode="[None|Forms]">

Delete Table Rows + Reseed The Table

By Mithun Bose at January 09, 2010 16:50
Filed Under: SQL Server

During the development phase I frequently come across the need of deleting a table and resetting the IDENTITY column back to 0.

The truncate statement does reset the identity seed to its original value; however, truncate is now allowed on a table where the columns are being referenced as foreign key. You could remove the foreign key reference and truncate the table and then recreate the foreign key but that's a messy way of getting around it.  I normally use following two queries:

delete from SomeTable 
DBCC CHECKIDENT ("SomeTable", RESEED, 0)

Having said that, if your table is very large it probably will be quicker to drop the foreign key ref and then truncate and recreate the foreign key. But for smaller size table the above mentioned queries are much cleaner way of achieving this requirement.

Missing Excel Data Into SSIS (Jet Driver Config Issue)

By Mithun Bose at January 08, 2010 17:32
Filed Under: Integration Services, Troubleshooting

Couple of days ago while importing data from an Excel file to a SQL Server table using SSIS I ran into an interesting issue. I found out that some of the data in the Excel file were inserted as NULL in the SQL Server table. It was a bit confusing to start with, I thought I was doing something wrong but after a few checks I was convinced there is something behind the scenes which was causing this problem and there indeed was.

Issue:

SSIS inserts NULL value into a table even when there is good data in the corresponding cells in the excel source.

Reason:

SSIS uses the Jet driver under the hood to read data from an Excel file. During the import process the JET driver looks into the first 8 rows on each column to decide the corresponding data type. In my scenario the column was actually of type double; however, the first eight row was empty, so the JET driver treated that column as String data type or varchar. 

So, during the import process when the driver encountered a double data type, it decided that its a wrong type and it just silently ignored it and stored a NULL value in the table. If the column which you are inserting into does not allow nulls then the transformation will fail.

 

Fix:

There is a fix for this. The JET driver connection string has configuration named "Extended Property", this configuration has a flag name IMEX, if we set this to 1 then it instructs the driver to always read "intermixed" data as text. Intermixed mean columns that may contain numbers, strings etc data types. The connectionstrings.com website has the details on the different settings.

In SSIS you can access the ConnectionString property by clicking the Excel Connection Manager and then look for ConnectionString in the Properties window as shown in the image below

 

 

Set your connection string property similart to below:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\SomeExcelFile.xls;Extended Properties="EXCEL 8.0;HDR=YES;IMEX=1";

 

Syntax Highlighter Rendering Problem

By Mithun Bose at January 04, 2010 20:46
Filed Under: Troubleshooting

I installed the syntax highlighter extension in my blog which uses BlogEngine.Net. I stumbled upon a problem, the problem was that the highlighter wasn't rendering the C# code properly, it was adding a new line after every C# keyword. The image below shows the problem

 

 

After pulling my hair for good couple of hours, I accidently fixed the problem. I changed the theme from Indigo to some other theme and voila!!! the problem was gone. I am just guessing that it was due to some CSS setting in the Indigo theme which was causing this side effect????

SyntaxHighlighter is a great extension, you can get it from here

Decorator Design Pattern

By Mithun Bose at January 02, 2010 17:41
Filed Under: .NET Framework, C#, Design Patterns

What is it?

 In simple words decorator enables to attach additional responsibilities(Properties) or behaviours (Methods) to an object dynamically without actually having to subclass or inherit it.

Whats the point?

 The first question which comes to mind is why not inherit or subclass the object in the first place, why use the decorator pattern? Well, some of the explaination to this questions are:

  • That class that is being "decorated", doesn't allow subclassing.
  • You want to add state or behaviour to the object dynamically.
  • You want to make changes to some object in a class without affecting others.
  • You want to avoid inheriting the object as that results in too many classes and inheritance hierarchies.

Class Diagram

The following diagram shows structure of typical decorator pattern, the diagram was taken dofactory.com

 

Decorator Pattern Class Diagram

The center of the above UML diagram is the Decorator class. It inherits from Component interface and also has a instance of Concrete object. This Decorator decorates the ConcreteComponent class. In the following section I've explained the pattern with an example.

Example

I've looked many examples on the various blogs and books, most of examples that I found were related to enhancing or adding functionality to an Image.  For e.g. adding border, tag, watermark etc as an added behaviour to an existing Image component. These are great examples and does describe the pattern very well; however, I wanted to share an example which I've used in my day to day work. I am working in telcoms domain for last 10 years and I've used decorator pattern a few times, one of the examples is as below.

Scenario

So the scenario was that we had a third party object packaged in a .NET DLL, this Object was responsible to send SMS(Text) messages. It did work very well. Some months down the line inevitably there was a new business requirement i.e. we should also be able to send a MMS(Picture) message with the SMS. The third party object could not be inherited. I had two options to add this fucntionality

  • Write a seperate component, which would only be used to send Picture Messages.
  • Decorate the third party component and add picture messaging facility as an added behaviour.

The second option was the logical way forward.

The third party class library had following interface and a class

 

1. ISMS Interface

 

namespace ThirdPartyLibrary
{
    public interface ISMS
    {
        void SendSMS(string smsText);
    }
}

 

2. SMS Concrete Object
namespace ThirdPartyLibrary
{
    public sealed class SMS : ISMS
    {
        
        public void SendSMS(string smsText)
        {
            /* Business logic to send SMS text message */
        }
       
    }
}

 

 

The requirement was to add additional behaviour in the above SMS concrete object, the additional behaviour would send picture message along with the text message.

The class below is the decorator pattern class which implements the additional functionality

public class SMSMMS : ThirdPartyLibrary.ISMS
    {
        ISMS sms;
        string pictureMessageLocation = "D:/SomePicture.jpg";
        public SMSMMS(ISMS _sms)
        {
            sms = _sms;
         
        }
        public void SendSMS(string smsText)
        {
            sms.SendSMS(smsText);
            SendPictureMessage();
        }
        void SendPictureMessage()
        {
            /* Picture Message sending logic */
        }
        
    
    }
}

 So as you'll notice the example starts with third party ISMS interface and a simple SMS component class that implements it. The above decorator class also implements the ISMS interface, and it includes a declaration of an ISMS, which is the object that it is decorating. Decorators always needs to know about the object that it is decorating, and in the example I've used the constructor injection. Notice in the constructor that I am passing ISMS component, which is then assigned to the sms variable. 

 

It then implements the SendSMS function, which calls the decorated object's SendSMS method and then also calls the SendPictureMessage method, which is the added behaviour.

Now how should I use this decorator, see below an example client code:

class Client
    {
        ISMS smsmmsObj = new SMSMMS(new SMS())
        public void sendMessage()
        {
            smsmmsObj.SendSMS("Test Text Message");
        }
        
   
    }

If you notice the client just created an object of type ISMS and called the same method "SendSMS"; however, this time the object not only sends SMS but also sends a picture message with it. The client didn't care or even know that it was the decorated object.

 

 I hope this post helped you understand the simple example of Decorator pattern.

 

 

About the author

I am a professional software developer based in London, England. I specialize in developing enterprise application and integration framework in C#, SQL Server, ASP.NET. 

My area of interests include SOA using WCF, Web, Business Intelligence and Database programming. I am a Computer Science Graduate and Microsoft Certified Professional Developer in enterprise application.