Friday, 28 October 2011

Practical TDD Interview Test

If you're given a task to be done in TDD, it's not usually whether you can resolve that problem. It's about testing whether you have the right mindset, process and coding style that TDD suggests:

  • Do you really understand the TDD Process? Benefits? Disadvantages?
  • Can you explain the TDD process?
  • Do you follow the TDD process in practice if you say you understand? e.g. if add something to the production code for which you don't have test, you have failed TDD!
  • Will you choose a small behaviour from the spec before writing any test or you think big and complex?!
  • Will you write a very small test method before writing any production code? how committed are you to this mindset?
  • Will you run all your tests after writing your test, after making a production change?
  • Would your test method names follow a proper pattern?
  • Will you make sure that you write the minimum amount of implementation code so that only one test passes? You may be able to write all the solution quickly but that’s not TDD! only write the minimum possible amount of code to pass your failed test. remember code quality is not important at this stage. Will you write the minimum possible amount of code for your tests and production code? or you make things complicated or write production code without having the test for it.
  • Will you refactor your production code after your tests passed?
When should you run all tests according to TDD?
  • After adding a test
  • After each change to the production code to pass 1 test
  • After each refactoring
How to fail TDD Process?!

A TDD practical test in an interview often means that you should rigidly demonstrate TDD:
  • If you write 1 single line of production code before you have a failing test for it, you have failed TDD!
  • If you don't run all your tests after you made a production code change, you have failed TDD!
  • If what you write is not minimized and focused only to pass your failed test and covers more scenarios than what tests you have, you have failed TDD!
  • If you don't run all your tests after your refactoring, you have failed TDD!

Monday, 17 October 2011


a good sample for OUTER APPLY:

Returning the latest record of a child table:

SELECT ST.[SystemDetailID], ST.[SystemName], LH.LatestLoadStatus
FROM [SystemTable] AS ST
SELECT LHInner.LoadStatus AS LatestLoadStatus, LHInner.SystemDetailID FROM [dbo].[LoadHistory] AS LHInner
WHERE LHInner.LoadHistoryID in
SELECT LatestLoadHisotoryID FROM
SELECT MAX(LoadHistoryID) as LatestLoadHisotoryID, SystemDetailID FROM [dbo].[LoadHistory]
GROUP BY SystemDetailID
) l
) AS LH ON ST.SystemDetailID = LH.SystemDetailID

A simpler/shorter approach is:

SELECT ST.[SystemDetailID],
FROM [SystemTable] AS ST
FROM [dbo].[LoadHistory] LH
WHERE ST.SystemDetailID = LH.SystemDetailID

More info:

Monday, 10 October 2011

Symmetric Encryption with Rijndael Algorithm


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace MyProject
public interface IEncryptionManager
string Encrypt(string originalText);
string Decrypt(string encryptedText);

/// <summary>
/// This class uses the Rijndael Encryption Algorithm
/// </summary>
public class RijndaelEncryptionManager : IEncryptionManager
#region Fields

/// <summary>
/// The key can only be 16, 24 or 32 bytes.
/// </summary>
private static readonly byte[] EncryptionKey = new byte[] { 0x00, 0x11, 0x22, 0x03, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xAA, 0xBB, 0xC0, 0xDD, 0x0E, 0xFF };

/// <summary>
/// The vector also can only be 16, 24 or 32 bytes.
/// </summary>
private static readonly byte[] InitializationVector = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0xFD, 0x0E, 0x0F};


#region Methods

public string Encrypt(string originalText)
using (var myRijndael = new RijndaelManaged { Key = EncryptionKey, IV = InitializationVector })
// Encrypt the string to an array of bytes.
var encryptedBytes = EncryptStringToBytes(originalText, myRijndael.Key, myRijndael.IV);

return Convert.ToBase64String(encryptedBytes);

public string Decrypt(string encryptedText)
using (var myRijndael = new RijndaelManaged { Key = EncryptionKey, IV = InitializationVector })
// Encrypt the string to an array of bytes.
var encryptedBytes = Convert.FromBase64String(encryptedText);

// Decrypt the bytes to a string.
return DecryptStringFromBytes(encryptedBytes, myRijndael.Key, myRijndael.IV);

/// <summary>
/// Encrypts the string to bytes.
/// </summary>
/// <param name="plainText">The plain text.</param>
/// <param name="key">The key.</param>
/// <param name="iv">The IV.</param>
/// <returns></returns>
static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("key");
byte[] encrypted;
// Create an Rijndael object
// with the specified key and IV.
using (var rijAlg = Rijndael.Create())
rijAlg.Key = key;
rijAlg.IV = iv;

// Create a decrytor to perform the stream transform.
var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

// Create the streams used for encryption.
using (var msEncrypt = new MemoryStream())
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
//Write all data to the stream.
encrypted = msEncrypt.ToArray();

// Return the encrypted bytes from the memory stream.
return encrypted;


/// <summary>
/// Decrypts the string from bytes.
/// </summary>
/// <param name="cipherText">The cipher text.</param>
/// <param name="key">The key.</param>
/// <param name="iv">The IV.</param>
/// <returns></returns>
static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("key");

// Declare the string used to hold
// the decrypted text.
string plaintext = null;

// Create an Rijndael object
// with the specified key and IV.
using (var rijAlg = Rijndael.Create())
rijAlg.Key = key;
rijAlg.IV = iv;

// Create a decrytor to perform the stream transform.
var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (var srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();


return plaintext;



Text Encryption and Decryption

Encryption Algorithms:
  • TripleDES
  • MD5
  • SH1
  • RC4
  • CRC32

Thursday, 29 September 2011

All About Assembly Signing - Public and Private Key

Why? Purpose?

An assembly is signed by a private key within the .snk file during the build process and other assemblies can access it using the public key.

Strong naming gives an assembly a unique identity and provides versioning feature.
To verify that an assembly came from a specified trusted source and have not been modified.
For example, you get an assembly from a colleague who says it is from Microsoft. If it's really from Microsoft, the public key that Microsoft has given you will make that assembly usable. Otherwise, if the public key doesn't work, then mean that assembly is not genuinely from Microsoft!

Prevents a malicious user from tampering and modifying an assembly and then re-signing it with the original signer’s key. Simply put, it prevents others to make fake versions of your assemblies.
Another purpose is that you have to sign an assembly before it can be installed in the global assembly cache (GAC) where it can be shared by multiple applications.

  •  Strong name private key must be kept secure.
  • Strong name public key will be given to the trusted referring assembly.
  • You should always protect your (.snk) file with a password to prevent someone else from using it.
  • One strong name key would be sufficient for all the projects but must be protected dearly!
  • You can’t just upgrade one assembly and deploy. If one assembly needs an upgrade, all the referenced assemblies must also be recompiled and deployed to point to the correct version.
  • The password information is stored in your computer's cryptographic storage database.
4 ways to sign an assembly:
To sign an assembly you'd usually need a public/private key pair.
  • Using Visual Studio/Project/Proeprties/Signing tab
  • Using AL.exe tool
  • Using AssemblyKeyFile attribute
  • Using AssemblyKeyName attribute
2 ways to create a public/private key pair:
  • Using Visual Studio/Project/Proeprties/Signing tab
  • Using Sn.exe (strong name) tool

How to extract the public key:
sn.exe -p KeyPair.snk PublicKey.snk

How to extract the public key token:

sn.exe -tp PublicKey.snk (this displays the public key in a slightly more sensible way!)


Sunday, 14 August 2011

Connect to Host IIS from Virtual PC

When you need to test your application with IE 6.0 using a virtual PC, you would need to make this configuration so that you can access the host application from the virtual pc.

The solution is quite simple as below:
  • Download the windows xp VHD and run it using VPC
  • Setup your web application on your local IIS
  • Configure Visual Studio to run the app from IIS rather the default VS Dvelopment Server:

  • Go to the Url and make sure that it's accessible from your host e.g. http://localhost/app1
  • Start the Windows xp VPC
  • Go to the settings and select Shared Networking (NAT) so that your VPC can access the host.
  • Find the ip address of the host machine by running ipconfig from the host
  • From the VPC, access the Host IIS Application using the ip address of the host e.g.

Important tip:
  • The VHD expires in Aug 2011. This is a workaround that you can use to change the current date of the VPC and takes less than 30m to configure and test.

Tuesday, 2 August 2011

Method Caching Options

Options to cache a method result

Using Postsharp as an AOP framework with this CodePlex Caching Manager:
  • hard to maintain if any bug appears
  • not very much reliable if a bug appears in the future
Using SPRING.NET as an AOP framework with Custom CacheManager:
  • most neat
  • less maintainability
CacheManager from Enterprise Library Caching Block and use it in each method
  • quickest to setup
  • Perhaps most stable
  • Duplicated code in every method (GET, ADD from/to cache)
My own Custom lightweight CacheManager and use it in each method
  • Lightweight and perhaps highest performance
  • More work
  • Duplicated code in every method (GET, ADD from/to cache)

Thursday, 7 July 2011

Hierarchy Representation of Data

During the past 4 weeks, I have been working to build a report engine to display Hierarchy information of different entities in my application. Everything gets generated at runtime programmatically and columns are customizable using external filters that user can choose on the screen. The Grids have exporting (Word, Pdf, Excel), paging and sorting enabled.

Using Nested Tables:

Monday, 4 July 2011

Friday, 17 June 2011

How to Instantiate a Generic Type With Input Parameters at Runtime?


There are times when we’d like to remove duplicated codes in instantiating types so we use generics to group similar classes and work with them easier.

Look at these classes:

public abstract class BaseType
protected int A { get; set; }
protected int B { get; set; }

protected BaseType(int a, int b)
this.A = a;
this.B = b;

public class Type1 : BaseType
public Type1(int a, int b) : base(a, b)


public class Type2 : BaseType
public Type2(int a, int b) : base(a, b)


Type1 and Type2 both inherit from the BaseType abstract class both of which require the same name and type of arguments to be instantiated.

Wouldn’t it be nice to have a generic method like

TypeCreator<T>(int a, int b) where T : BaseType


// instantiate type with a and b


Now I show you different ways to implement this.


1) Using Activator.CreateInstance… – anti-pattern

The simplest way to implement this would be to use the Activator.CreateInstance method. There are numerous articles which says this approach has an awful performance and avoid it but I’d just like to show how it simply works:

public static class MyTypeFactory<T> where T : BaseType
public static T Create(int a, int b)
return (T)Activator.CreateInstance(typeof(T), a, b);

// and use it like this
MyTypeFactory<Type1>.Create(1, 2);

2) Using a Static Delegate

For this approach to work, you’d need to provide a delegate to all your types in a Factory then use it. So it’s a bit inflexible as it has to know which types it can instantiate but it should have a very good performance:

public static class MyTypeFactory
static MyTypeFactory()
MethodRunner<Type1>.Func = (a, b) => new Type1(a, b);
MethodRunner<Type2>.Func = (a, b) => new Type2(a, b);

public static T Create<T>(int a, int b) where T: BaseType
return MethodRunner<T>.Func(a, b);

static class MethodRunner<T>
public static Func<int, int, T> Func { get; set; }

The static constructor of the MyTypeFactory class only runs once per application domain the first time the factory is accessed so it should also be thread-safe.

You can simply use it like this:

var type1 = MyTypeFactory.Create<Type1>(1, 2);

3) Using Expression Trees

In this approach, a lambda expression has to be compiled per type. So for each type a new compilation will be done initially then they're stored in a private field for further reuse. This has much better performance in comparison with Activator.CreateInstance.

Another good point about this approach is its flexibility; you don’t have to hard code the constructors like approach 2.

public static class MyTypeFactory<T> where T : BaseType
private static readonly Func<int, int, T> MethodDelegate = InitializeMethodDelegate();

private static Func<int, int, T> InitializeMethodDelegate()
var constructorInfo = typeof(T).GetConstructor(new[] { typeof(int), typeof(int) });
var param1 = Expression.Parameter(typeof(int));
var param2 = Expression.Parameter(typeof(int));

return Expression.Lambda<Func<int, int, T>>(Expression.New(constructorInfo, param1, param2), param1, param2).Compile();

public static T Create(int a, int b)
return MethodDelegate(a, b);

and you can again use it like

var type1 = MyTypeFactory<Type1>.Create(1, 2);

Be careful not to re-comiple the type each time as this may make the performance even worse than Activator.CreateInstance(). Only once per type as shown above.

4) Using Reflection

The factors which should be important in your decision making are:

  • Performance

  • Simplicity of use

  • Flexibility
I think using Expression Trees in the way mentioned above provides the best result considering performance and flexibility.

Read Further:

Monday, 6 June 2011

Call a Page Method Using Drop Down List and JavaScript


When an item is selected from the drop down list, a method on the server should be called. AutoPostBack = True can’t be used as posting back the whole page is not required.


Page Source:

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var selector = ".ddlCountries";
$(selector ).change(function () {
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">

<asp:DropDownList CssClass="ddlCountries" ID="ddlCountries" runat="server" Width="100px">

Page Code Behind:

   protected void Page_Load(object sender, EventArgs e)

private void BindDummyData()
var countries = new [] {new { Name = "UK", ID = "1" },
new { Name = "USA", ID = "2" }

foreach (var country in countries)
this.ddlCountries.Items.Add(new ListItem(country.Name, country.ID));

public static void OnSelectedIndexChanged(string selectedValue)
// process

Sunday, 5 June 2011

Patterns of Creating the Data Access Layer

If you've decided not to use any ORM, then you'd need to decide about the pattern you'd like to use for creating your data access layer.

This is an old topic so I'm going to summarize them here:
  • Repository Pattern
  • Active Record
  • Data Mapper
  • Identity Map
  • Table Data Gateway
  • Row Data Gateway

Tuesday, 24 May 2011

Behaviour Driven Design and Domain Driven Design

1) DDD:
The purpose of Domain Specific Language (DSL) is to create a bridge between the technical and non-technical people. DSL is important in Domain Driven Design (DDD).

2) BDD:

BDD is pretty simple to understand:
  1. Business Analyst should communicate with the Business and gather requirements as User Stories.
  2. The Business Analyst should go through each user story with 1 or 2 developers and testers to create Main Scenarios and Edge Case Scenarios by Example using Gherkin Language and these can be saved in TFS or a similar tool.
  3. Business Analyst should prepare all user stories with their details then ask all developers and testers to read all of them before the Sprint Planning session.
  4. In Sprint Planning session, everyone should have already read the stories and its purpose is purely to estimate the work required for each User Story. If people are asking so many questions, it shows pre-sprint planning has failed.
  5. Now Sprint Starts
  6. For each Gherkin/behaviour, create a unit test and end to end test (you can use SpecFlow tool).
  7. Implement your code until your test passes.
Gherkin Language
Gherkin Language is a language used to represent specifications or scenarios in the following format: "Given -When - Then"

It is a language to define behaviour of the modules and basically test cases (scenarios) are created from these behaviours easily.

Given user opens a browser and navigates to the site
When user enters "BDD" or user enters "DDD"
Then result of the search are listed on the page.

Given I have gone to an interview well-prepared
When I answer all the challenging questions of the interviewers properly
Then I'll get a job offer!

  • A free tool which can be used to convert Gherkin to unit tests
  • It can be integrated into Visual Studio

Saturday, 21 May 2011

Software Architecture Competency

Everyone has played the role of an architect in their life.

Key skills to develop for being the best Software Architect:
  • Demonstrable leadership and motivational skills
  • Demonstrable interpersonal skills with different people with different religion, race, background, education and political views
  • Demonstrable communication and listening skills
  • Demonstrable previous success
  • Demonstrable envisioning a software; excellent with drawing tools
  • Creativity and Logical reasoning

Tuesday, 17 May 2011

Continuous Integration

The purpose of CI is to detect integration errors as quickly as possible by allowing team members to integrate code into the source control frequently.

Source Controls:
  • Subversion: free
  • Microsoft SourceSafe
  • Perforce
  • Microsoft TFS
  • CVS: free
Automating the Build and Test:
  • TeamCity: free
  • CruiseControl.Net: free
  • Microsoft TFS

Check Web Information

Saturday, 19 March 2011

Cloud Folder Storage and Sharing


Tuesday, 8 March 2011

How to create and install SSL certificate in IIS

C:\Program Files\IIS Resources\SelfSSL\selfssl.exe" /T /N:CN={0} v /V:180 /S:{1}

{0}: website name
{1}: website identifier

Monday, 7 February 2011

SharePoint WebPart Deployment

SharePoint WebPart Solution Package (WSP):

Deploy a web part to the bin directory:

Deploy a web part to GAC:

set url=http://serverName:Port

set wspFilePath= C:\Backups\ProjectName.wsp



CD c:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/BIN

@echo adding the solution to the sharepoint solution store

stsadm -o addsolution -filename %wspFilePath%

@echo deploying the solution to the sharepoint site collection

stsadm -o deploysolution -name "ProjectName.wsp" -url %url% -immediate -allowgac -force

@echo executing so that deployment happens immediately.

stsadm -o execadmsvcjobs


Sunday, 30 January 2011

Domain-Driven Design (DDD)

DDD is a collection of patterns and best practices to address software complexities and make them more understandable and manageable.

Friday, 28 January 2011

What Can't You Do With FireBug?

Spend some time reviewing the great features of firebug here.

Tuesday, 18 January 2011

How to Enable SessionState in SharePoint 2010?

You'd like to use session object in your code but you receive an error saying that by default it's disabled.

You'd need to make these changes in the web.config of your application:

1) add the SessionStateModule assembly
<add name="SessionState" type="System.Web.SessionState.SessionStateModule, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

2) Add a http module
<add name="SessionState" type="System.Web.SessionState.SessionStateModule" />

3) Enable session state
<pages enableSessionState="true" ... />

Wednesday, 12 January 2011

How to compress JS files?

Using js-builder, you can combine and compress JS files and resources from a simple user interface which improves the performance and download time of these files.

Another approach is using the ASP.NET 4.5 Bundling and Minification features:

Tuesday, 11 January 2011


It's another javascript library like JQuery but perhaps with more features and controls and we currently use it!

Sunday, 9 January 2011

How to Configure Url Rewrite Module in IIS 7.0?

Url Rewrite module is a free IIS 7.0 module which helps you implement url rewriting.

Ok, what is url rewriting anyway? for example you might want to let users use this url {0} and in the background you'd like that request to be sent to this url {1}.

{0}: http://sitename/productId=1
{1}: http://sitename/products/productdetails.aspx?pid=1
Reverse proxy with url rewrite can be used when you need to rewrite an external url into your original url. By external url, I mean a url which is not on the same site.

There are 2 ways to define the rules either using web.config or using IIS Url Writing section; both of these are sync with each other.

SSL Offloading:
When you enable SSL Offloading in IIS, then communication between ARR to the contents server will be using clear text rather than SSL.

Friday, 7 January 2011

URL Rewrite vs URL Redirect

URL Rewrite
  • Is a server side operation which means the rewriting is done at the server
  • May result in a static page, a dynamic page, or an image file
URL Redirect
  • Is a client side operation
  • Accepts the request then sends a response to the client immediately with the new URL
  • Therefore, it causes the client browser to make a second request with the new URL

Thursday, 6 January 2011

How to Add Custom CSS and JS files to Your Visual Web Part

Adding CSS

1. Add "Layouts" mapped folder to Visual WebPart Project.

2. Create a folder structure layouts/styles/themable

3. Add the css file to the styles folder .If you are using themable styles then also add it to themable folder too

4. Register the CSS file by adding following line into your visual webpart

<SharePoint:CssRegistration ID="cssId" name="/_layouts/projectName/cssName.css" runat="server" />

(Note: Another approach From sharepoint designer add css file to style library and refer it in css registration)

Adding JS

1. Add "Layouts" mapped folder to Visual WebPart Project.

2. Add you JS file to layout folder or your project specific folder

3. Add the script link to your webpart

<SharePoint:ScriptLink ID="scriptLinkId" name="ProjectName/jsFileName.js" runat="server" />