Oct 31, 2008

Code Metrics for a developer

by
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 you how many test cases will be required to achieve full code coverage.

Depth of Inheritance:
It is the measure of the level of inheritance a given solution. The deeper a class is in the hierarchy, the greater the number of methods it is likely to inherit, making it more complex to predict its behavior. As we go down inheritance graph, refined classes constitute greater design complexity, since more methods and classes are involved. Deep Inherited types are by-products of an over engineered hierarchy and one should avoid this. It causes major performance hit.

Class Coupling:
Coupling is the measurement of code independence and re-usability. A module is considered highly coupled when resident classes relies on each one of the other classes. In highly coupled cases, change in one class forces a cascading changes in other classes, classes are hard to reuse or test because of their dependence on other modules.Usage of proper Creational pattern reduces the coupling between the classes. A Class should interact with another class through a stable interface and does not need to be concerned with its internal implementation.

I think every development environment has the feature of analyzing code metrics these days. Visual Studio team suite/ system has this feature of calculating code metrics from a solution.
If you track and address these issues at the earliest, it will save you from a lot of code re-factoring.

Oct 20, 2008

Extension Methods

by
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
Array.Copy(source,destination....);
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 string.
For this I have to write a static method outside definition of the type.

public static bool IsValidPinCode(this string s)
{
bool isValid = false;
// your logic to check whether an address is valid
// and assign ‘isValid’ accordingly

return isValid;
}
This method must be a defined inside a static class. Note that keyword this is being used in a static method.This would be signature of an extension method. Type for which it has been extended should be preceded in parameter list with this keyword. Once I define it, I can use it all across my code. (of course within the visibility of class where this method was defined)

string str = "500082";
bool isValid = str.IsValidPinCode();

I think it could be handy sometimes but it is not something I would go about as a language feature.

Oct 18, 2008

Functional Programming

by
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
21

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.

Advantages:
 As the functional units do not have side effects, so their orders could be reversed.
 They can be performed in parallel. (suited for parallel computing)
 They are thread safe as one does not interfere other. (Thread safety)
 Function can be evaluated as late as possible, providing composability. (late evalutation)
This gives the compiler as edge to reorder or combine the evaluation of expressions in a program.

I believe it is a very strong feature for a programming language to possess.

Jul 5, 2008

XMPP

by
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 server to send a request; the server initiates a new response stream on the same TCP connection. Unlike the client-server communication, the server-server communication requires two separate TCP connections for exchange of XML elements over streams.

Stanza is one atomic unit of information that can be sent from one entity to another over a stream. It is a structured XML element. Three types of stanzas are defined in the XMPP standards:

  message: used for instant messaging
  presence: used for presence related messaging
  iq: used in request-response services for querying information from entities.

The client-server (or server-server) communication can be thought of as two open-ended XML documents. The stream just wraps all the stanzas sent in a session from one entity to the other.
A stream with different stanzas:

Watch out for more on XMPP..

Jul 3, 2008

LINQ - Introduction

by
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 queryable XElement type.Types such as ArrayList that support the non-generic IEnumerable interface can also be used as a LINQ data source.
Here we will take an example of array int.

int[] array = new int[] {0,1,2,3,4};

  Defining the Query
A query specifies what data to be retrieved from a data source and how that information should be sorted and grouped. A query is stored in a query variable and initialized with a query expression. To make it easier to write queries, C# has introduced new query syntax.

// myQuery is an IEnumerable of type int
var myQuery =
from n in array
where (n % 2) == 0
select n;

Here the query expression contains three clauses: from, where and select just like any SQL query. The "from" clause specifies the data source, the "where" clause applies the filter, and the "select" clause specifies the type of the returned elements.

Note:
The important point is that in LINQ, the query variable itself takes no action and returns no data. It just stores the information that is required to produce the results when the query is executed at some later point.

Queries can also be expressed by using method syntax.( Something I am not aware right now )

  Query Execution
The query variable itself only stores the query commands. The actual execution of the query is deferred until we iterate over the query variable in a foreach statement. This concept is regarded as "deferred execution" and is demonstrated in the following example:

foreach (int num in myQuery)
{
  Console.WriteLine( "{0}", num );
}

Because the query variable itself never holds the query results, we can execute it as often as we like. For example, we may have a database that is being updated continually by a separate application, we could create one query that retrieves the latest data, and we could execute it repeatedly at some interval to retrieve different results every time.
Whenever the query variable is accessed or any of it's method is called, the query gets executed and the result sets are cached in the respective objects. This term is regarded as "Forced execution".
You can refer msdn for further details.

Jul 1, 2008

Marshalling Array of Structures

by
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++)
{
   Marshal.StructureToPtr(structArray [index],
         (IntPtr)(addr + structSize * index),false);
}

The IntPtr type ptr will hold the address of the memory block containing StructType array.

Jun 29, 2008

One for new bloggers

by
A nice blog for all new googlers. Gives useful informations and hacks on how to create effective blogs and to monetize your existing ones.
I liked it.

Jun 19, 2008

Factory Method

by
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()
  {
     return new MyConcreteObject();
  }
}


class
MyOtherConcereteObjectCreater : Creator
{
  virtual MyObject CreateObject()
  {
    return new MyOtherConcreteObject();
  }
}

Now the module which requires different flavours of MyObject need not worry about the instantiation of MyObject. It delegates the responsibility to "Creator" classes and they decide which type of MyObject is created.



void
SomeMethod(Creator bClass)
{
  MyObject myObject = bClass.CreateObject();
  // MyObject is specific to a particular Concrete Class
}


Advantages of Abstract Method:

  • Factory methods gives a hook for providing an extended version of an object.
  • Connects parallel hierarchies (MyObject --> Creator)

Jun 17, 2008

Creational Patterns

by
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 )

Jun 7, 2008

Common Software Design Blunders

by
I have been reviewing some of the codes at work (mostly my own ;) ).We make lots of " mind numbingly stupid" mistakes when designing a software, 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 (Server) Object Implementation: If a client module knows how an object is represented or Implemented, it tends (rather unknowningly) to a design which is more specific to object's implementation.Hiding this information from client is better design because even if 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 with better ones. Objects that depend on an algorithm will have to change whenever algorithm changes. Therefore algorithms that are likely to change should be isolated from rest of the lot.

Too much SubClassing: Subclassing requires an in-depth understanding of the parent class. Overriding one method might require overriding another and so on.Different ways of object composition would be a better approach than extending functionality by subclassing.

May 25, 2008

C# Source Analysis tool

by

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 documentation.

download tool

May 18, 2008

Hyderabad Traffic

by

I just had a near death experience today riding my bike to office. And tell you what, it is not something new in Hyderabad.Whether you see a BMW or some tin can with wheels, you have a maverick driver behind the wheel. Where on earth do you find traffic rules that are applicable only from 8 am to 8 pm? And if you try to follow these "nonexistent" rules, others make you look like a chump. There is total disregard for others' safety. Traffic signals do not mean anything more than blipping lights around the corner. It’s quite frustrating to see even so called educated people practicing these sort of “senseless” driving. I don't figure whether it's just a mad rush or men trying to get their pregnant wives to a hospital, everyone seems to be in crisis to reach "somewhere" in a jiffy.

We are witnessing Hyderabad developing into a Cosmopolitan (at least people say so..), it’s about time we have matching traffic etiquettes.

May 16, 2008

XSL template to split string

by
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.

Stylesheet:


<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:for-each select="Paths/Item">
<xsl:call-template name="SplitText">
<xsl:with-param name="inputString" select="Path"/>
<xsl:with-param name="delimiter" select="Delimiter"/>
</xsl:call-template>
<br/>
</xsl:for-each>
</xsl:template>
<xsl:template name="SplitText">
<xsl:param name="inputString"/>
<xsl:param name="delimiter"/>
<xsl:choose>
<xsl:when test="contains($inputString, $delimiter)">
<xsl:value-of select="substring-before($inputString,$delimiter)"/>
<xsl:text disable-output-escaping = "no"> </xsl:text>
<xsl:call-template name="SplitText">
<xsl:with-param name="inputString" select="substring-after($inputString,$delimiter)"/>
<xsl:with-param name="delimiter" select="$delimiter"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test="$inputString = ''">
<xsl:text></xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$inputString"/>
<xsl:text> </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>


XML file (to be transformed) :


<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="textSpliter.xslt"?>
<Paths>
  <Item>
    <Path>C:\ProgramFiles\SomeWierdSoftware</Path>
    <Delimiter>\</Delimiter>
  </Item>
</Paths>


Output: C: ProgramFiles SomeWierdSoftware
Hope it is useful.

String Split Template

by

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.

 

Mar 27, 2008

C# Code to Javascript

by
This is quite an interesting reading.
They claim to have developed a compiler that compiles C# code to JavaScript.
Relief to people like me who suffer from "separation enxiety" with C#.

Increase your productivity with Visual Studio

by
Nice blog on increasing your productivity with Visual Studio and C#.
Just trivial stuff but surely productive!!

Mar 21, 2008

Speed up Visual Studio 2005

by
  1. Make sure Visual Studio 2005 SP1 is installed.
  2. Turn off animation.Go to Tools| Options| Environment and uncheck Animate environment tools.
  3. 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.
  4. Turn off Track Changes.Go to Tools | Options | Text Editor and uncheck Track changes. This will reduce overhead and speeds up IDE response.
  5. 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 | Projects and 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.
  6. Turn off AutoToolboxPopulate.There is an option in VS 2005 that will cause VS to automatically populate the toolbox with any controls you compile as part of your solution. This is a useful feature when developing controls since it updates them when you build, but it can cause VS to end up taking a long time in some circumstances. To disable this option, select the Tools| Options| Windows Forms Designer and then set AutoToolboxPopulate to False.


Spell checker for VS 2005

by
We do make hell lot of spelling mistakes while working on literals.
Here is a cool link to download a spell checker for ASP.NET and HTML pages.

MSDN Code Gallery

by
Download and Upload .Net Source code.
Code Gallery is your destination for downloading sample applications and code snippets , as well as sharing your own resources.
http://code.msdn.microsoft.com/
Great Stuff !!

Mar 3, 2008

Enterprise Service Bus

by

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 allows the location of the service to be moved without the caller having to know about the change.
  • Message transformation: An incoming message is transformed from one format to another. For example, a csv message might be reformatted into SOAP so that the data can be passed to a Web service.
  • Protocol mediation: An incoming message is sent using a different protocol from the original. For example, the incoming message could use HTTP, while the outgoing message might use SOAP over TCP.
  • Event handling: An incoming message for an event is distributed to a number of endpoints, usually through a publication and subscription model.

Jan 23, 2008

Schema Import using XSD tool

by
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.exe ImportingSchema.xsd ImportedSchema.xsd {options}

Top Ad 728x90