Skip to main content


Showing posts from 2008

Code Metrics for a developer

Here are some code metrics each developer should be tracking all along.

Cyclomatic complexity:
Cyclomatic complexity of a program is the count of the number of linearly independent paths of execution. If the source code contained no decision points ( such as 'if' 'switch' 'while' ), the complexity would be 1, FLAT CODE, since there is only a single path through the code. If the code has a single ‘if’ statement there would be two paths through the code, one path where the ‘if’ statement is evaluated as true and one path where the ‘if’ statement is evaluated as false. So the complexity increasing with number of decision points in your code. If you have not written your decision statements properly, it will lead you into unnecessary conditions and hence complexity of the program increases.

Measuring CC tells you 2 important things.
How many ways your execution may end up. If you have higher CC, then maybe you can re-write your logic to make fewer conditions.
It tells…

Extension Methods

It's been a while working on Visual Studio 2008 but there are new features I still didn't use. Extension method is one of them.Extension methods, are a way to call static method by an instance using instance method syntax. There are occasions when you call static methods where you pass an instance as first parameter.
for e.g:
We often copy arrays as
would not it be more readable if we can invoke it like
source.Copy (Destination);
Extension methods make it possible.

But example above has hardly anything to do with the word 'Extension'. So, the main idea of a extension method is to enable developers to write a method outside its class definition (of course on requirement basis) and use it just like any instance method.

Let's say I want to extend functionality of an existing type string.
I want to add a new method IsValidPinCode, just like IsNullOrEmpty or any other pre-defined methods.I can do it easily by "EXTENDING" the type str…

Functional Programming

You must have seen the amount of interest that is being generated for LINQ, Lamba Expressions with the release of C# 3.0.The entire Data Access Architecture has been focused on to LINQ to SQL, LINQ to XML and LINQ to Objects and more. So what exactly is Functional programming ?

FP is a programming model that treates computation as the evaluation of mathematical function.

For e.g, if we define two functions like given below
f(x) = x^2 + x + 1
g(x,y) = x * y

A problem f (g (2, 2) ) will be evaluated by compiler as
g(2*2)^2 + g(2*2) + 1
(4)^2 + (4) + 1
16+ 4 + 1

It is a declarative way of programming, where we leave the compiler to do the evaluation as late as possible. The user is only bothered about the result and not on how it is being evaluated.The focus is never on in the state transition of the variables, so one need not bother about the side effects.

 As the functional units do not have side effects, so their orders could be reversed.
 They can be performed in parallel. (suited…


eXtensible Messaging and Presence Protocol (XMPP) is a protocol to stream XML elements for messaging, presence and request-response services. It is mainly used in building IM and presence based applications.
The protocol is not coupled to any network architecture, but it’s generally used in client-server architecture. An XMPP server can communicate with its clients (recommended port: 5222) or with other XMPP servers (recommended port: 5269) over a TCP connection.

An example network architecture could be like

The gateway is necessary to translate the messages between a non-XMPP server and an XMPP server.

All XMPP messaging happens in the form of Streams and Stanzas. Stream is the container for all messages sent from one entity to the other. A stream is initiated with a <stream> tag and is destroyed with a </stream> tag. Multiple XML elements can be sent over the connection before the stream is closed.
These streams are unidirectional i.e. if a client initiates a stream with the …

LINQ - Introduction

LINQ (Language Integrated Query) introduces a generic and standard pattern for querying and updating data store of any kind. Basically a query is an expression that retrieves data from a data source. Queries are usually expressed in a specialized query language. I assume LINQ is intoduced to decouple the query language from the datasource. This avoids a lot of "unnecessary" learnings, because literally there is query language for each type of data source be it SQL databases, ADO.NET datasets, Collections types and XML documents.
A LINQ query operations has there distinct phases:

  Recognizing the Data Source
With LINQ, there is another concept that has been introduced called Queryable, implementing interface IQueryable. Any Enumerable type is a queryable type and it requires no modification as a LINQ data source. If the source data is not already in memory as a queryable type, the LINQ provider must represent it as such. For example, LINQ to XML loads an XML document into a que…

Marshalling Array of Structures

It is fairly easy to Marshal simple structures in .NET but when it comes to sending a whole bunch of structures as parameter it’s little head scratching task if you have not done it already. The worst part is you won’t find any articles on how one should go about it. When I had to marshal an array of structures, every time I ran into same state of confusion. I decided to blog it this time (for future reference of course :) )
So let’s assume there is a structure called StructType and structArray be an array of StructType.

//Lets not bother about how the array was populated
StructType[] structArray = new GetStructArray();
// Get the size of each element
int structSize = Marshal.SizeOf(structArray [0]);

Here int can be replaced with long (depends on 32 bit or 64 bit addressing)

// Total size of the memory block
IntPtr ptr = Marshal.AllocHGlobal(structSize * structArray.Length);
int addr = (int)ptr;
for (int index = 0; index < structArray.Length; index++)

Factory Method

In this design pattern, a contract is defined for creating an object. All derieved classes who implements this policy(via virtual method or implementing an interface ) decide which object in a class heirarchy to instantiate.

class Creator
virtual MyObject CreateObject();
Creator defines a contract that all its derieved classes expose a method "CreateObject" which should return an object which "IS" a MyObject.
class MyObject


class MyConcreteObject : MyObject


class MyOtherConcreteObject : MyObject

MyConcreteObject and MyOtherConcreObject are different flavour of MyObject.Each of the class share IS relationship with MyObject.
Let's implement few "Creators".
class MyConcereteObjectCreater : Creator
virtual MyObject CreateObject()
returnnew MyConcreteObject();

class MyOtherConcereteObjectCreater : Creator
virtual MyObject CreateObject()
returnnew MyOtherConcreteObject();
} Now the module which requires different flavours of MyOb…

Creational Patterns

Creational design patterns abstract the instantiation process. Introducing this design patterns makes a system independent of how its objects are created and composed.
Two major responsibilities of Creational patterns are:
To encapsulate the concrete classes that system uses.To encapsulate how instances of these classes are created.Factory Method: Creates an Instance from a several derieved classes
Abstract Factory: Creates Instance from several family of related classes.
Builder: Separates object instantiation from object representation.
Prototype: A single object is copied and cloned.

(.. to be continued in detail )

Common Software Design Blunders

I have been reviewing some of the codes at work (mostly my own ;) ). We tend to make a lot of mistakes especially when we have not put through enough thinking before we start writing code, only to regret later. Here are my favourite ones.

Explicit object Instantiation: If your design involves instantiating objects from concrete classes, then there's a flaw already. This commits an application to a particular implementation instead of a particular interface, it complicates future (unavoidable) changes.

Visibility to  Implementation:If a calling module knows how a library is represented or Implemented, it tends (rather unknowingly) to a design a system which is more specific to the implementation. Hiding this information from the client is better design, because even if the implementation of the object used is changed or altered, there are no cascading changes on the client.

Algorithmic Dependencies:Algorithms are prone to changes in the name of optimization and often are replaced wit…

C# Source Analysis tool

Microsoft has announced release of a new developer tool, Source Analysis for C#. This tool will help teams enforce a common set of best practices for layout, readability, maintainability, and documentation of C# source code. Source Analysis is similar in many ways to Microsoft Code Analysis tool FxCop, but there are some clear distinctions. FxCop performs its analysis on compiled binaries, while Source Analysis analyzes the source code directly. For this reason, Code Analysis focuses more on the design of the code, while Source Analysis focuses on layout, readability and tool

XSL template to split string

Finally came up with a xslt template that would split a delimited string into substrings. I don’t claim it’s the smartest script, but surely solves my problem.

<?xmlversion="1.0"encoding="iso-8859-1"?> <xsl:stylesheetversion="1.0"xmlns:xsl=""> <xsl:templatematch="/"> <xsl:for-eachselect="Paths/Item"> <xsl:call-templatename="SplitText"> <xsl:with-paramname="inputString"select="Path"/> <xsl:with-paramname="delimiter"select="Delimiter"/> </xsl:call-template> <br/> </xsl:for-each> </xsl:template> <xsl:templatename="SplitText"> <xsl:param

String Split Template

I want an XSL template which would split a given string. Spent a hell lot of time searching on net, but could not find one that would solve my problem.So I have decided I will write one myself.Hmm .. May be tomorrow.

Speed up Visual Studio 2005

Make sure Visual Studio 2005 SP1 is installed. Turn off animation.Go to Tools| Options| Environment and uncheck Animate environment tools. Disable Navigation Bar.If you are using ReSharper, you don't need VS2005 to update the list of methods and fields at the top of the file (CTRL-F12 does this nicely). Go to Tools | Options| Text Editor | C# and uncheck Navigation bar. Turn off Track Changes.Go to Tools | Options | Text Editor and uncheck Track changes. This will reduce overhead and speeds up IDE response. Turn off Track Active item.This will turn off jumping in the explorer whenever you select different files in different projects. Go to Tools| Options | Projectsand Solutions and uncheck Track Active Item in Solution Explorer. This will ensure that if you are moving across files in different projects, left pane will still be steady instead of jumping around.Turn off AutoToolboxPopulate.There is an option in VS 2005 that will cause VS to automatically populate the toolbox wit…

Enterprise Service Bus

ESB, Enterprise Service Bus is an architectural pattern in an Enterprise application.It is an abstraction of a channel through which messages flow within various components of an Enterprise Application.The primary advantage of ESB is to reduce the number of point-to-point connections required to allow applications to communicate.ESBs are typically built around the exchange of XML messages. The enterprise message model is defined in terms of a series of XML Schema definitions describing the set of legal messages. The message exchange is almost always done in a platform-independent manner. This allows the ESB to integrate applications that run on a variety of client-server operating systems. An ESB has four major functions: Message routing: An incoming message is sent to a destination determined either through logic known in advance, or dynamically-based on message. Routing is a key function to enable service virtualization. This level of indirection between the caller and the service a…

Schema Import using XSD tool

We are all aware of XSD tool that comes along the Visual Studio 2005.
We all might have used it to generate classes and dlls using this tool from xsd schemas.

In order to use schemas that import other schemas using xs:import, we need to specify both the base schema and the imported schema on the command line.As the XSD tool doesn't seem to understand schemaLocation attribute.
Just mentioning the import tag won't import the schema while creating classes.

So the correct usage of xsd.exe would be
xsd.exeImportingSchema.xsd ImportedSchema.xsd {options}