Working with NuGet Package Manager

NuGet is a visual studio extension which makes it easy to install and update open source libraries in visual studio. One can simply search for the library which needs to be added to the solution. The rest of the work i.e adding references, finding dependency etc. are all done by NuGet. It automatically updates your solution and library with the new libraries.

Download NuGet from here.

Steps to add an open source library from NuGet

Once the installation is done, fire up your visual studio and start a new project. for example, we have created a new web application. whose structure looks like the below screen.


Now, right click the project in which you want to add a library. Here we will be adding a library to our BusinessLibrary project. when you right click you will see the following pop up screen.


Select manage NuGet package from the list. after selection one more screen popups.


Click on the Online tab at the left hand side and Type in the search box to search your open source library which you want to add. for example, we will be adding Enterprise library logging library to our bussinesslibrary project.


You can see the list of libraries available from the search term enterprise. next we click on the install button for the library to be installed.


NuGet automatically resolves the dependency and adds references to all the libraries required to support the library chosen.

Once the installation is complete. You can see the details of the library added in the references.


Here, we have successfully added Microsoft Enterprise logging library and all the dependency libraries. Happy coding….

Tagged with: , ,
Posted in Microsoft .NET, NuGet

Using NHibernate in ASP .NET


We often need to create a Data Access Layer (DAL), which takes our business objects and performs CRUD (Create, Read, Update and Delete) in physical data store. If you have ever created the DAL you will come to know how tedious it is to do it again and again. Also, it’s very time consuming to map our objects to the relational database. Here comes Object Relational Mapper (ORM).

Object Relational Mapping (ORM) is a technique by which we map our objects in Object Oriented Programming to get mapped to the underlying relational database. For example, if we have a student object with attributes Name, Age, Roll No etc.and a database table name Student with columns Name, Age, Roll no etc. In traditional approach we will run an insert/update/delete/select query with scalar values to perform manipulations in database. But, what if we have the ability to directly save/remove/read/update the student object without thinking about underlying database. The query itself is getting removed.

Why NHibernate?

NHibernate is ORM framework which has the built in capability of concurrency checks, transactions, lazy loading (objects are not initialized until in use) and transparent persistence (allows to change the DAL without changing Domain Model).  To download the latest version of NHibernate visit NHibernate.

Let’s see the steps involved in configuring NHibernate to use in ASP .NET. Following are the common steps to be followed.

  1. Design your database
  2. Create your class files
  3. Create Mapping files to map class to database
  4. Create a Session Factory class
  5. Configure web.config file to use the datasource
  6. Create a Service class for CRUD

Design your Database

We start our example by creating a simple database name Students and creating a table name Student with following columns

Note: the Id is auto generated

Create the class file (POCO class)

Plain old CLR objects (POCO means that do not need to inherit from or implement an interface) business entities are mapped into the table entity.  We now create a class file with these columns as properties.  The Id column will be read only as it is getting generated in the database as identity. Our class file would look like

Public class Student


private string name;

private int id;

private DateTime dateofbirth;

private string address;

public int ID


get { return id; }

private set { id = value; }


public string Name


get { return name; }

set { name = value; }


public string Address


get { return address; }

set { address = value; }


public DateTime DateOfBirth


get { return dateofbirth; }

set { dateofbirth = value; }



Create Mapping files

Once our class files and table design is complete we need to creating a mapping file which tells the framework what column to map with what properties in the class. It’s a simple XML file. The naming format of the file is Student.hbm.xml. Note the hbm in between student and xml.

<?xml version=”1.0″ encoding=”utf-8″ ?>





<class name=”Student” table=”Student” lazy=”false”>

<id name=”ID” column=”id” unsaved-value=”0″>

<generator />


<property name=”Name”>

<column name=”Name” not-null=”true” />


<property name=”Address”>

<column name=”Address” not-null=”true” />


<property name=”DateOfBirth”>

<column name=”DateOfBirth” not-null=”true” />




From the above mapping we can see that we first need to define the namespace and assembly where our class files are located and have the same namespace and assembly. Next the class tag attribute name takes class name and table attributes the database table name. next the ID tag is the identification section to identify the identity column. It uses reflection to accomplish it so that only database is able to create those ID’s. You see the ID tag is defined above differently. Inside this class tag we define all the properties with property tag, where name is class property and column tag name is the table column name.

We need to change the build action to embedded resource so that it gets embedded in the assembly.

Define a Session Factory Class

This class will read all of the mapping files and configuration data and build a session that will enable you to talk to the database.

public class SessionFactory


private static NHibernate.ISessionFactory sFactory;

private static void Init()


NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();


sFactory = config.BuildSessionFactory();


public static NHibernate.ISessionFactory GetSessionFactory()


if (sFactory == null)




return sFactory;


public static NHibernate.ISession GetNewSession()


return GetSessionFactory().OpenSession();



Configure web.config file to use the datasource

We specify the database details with which we are making connection and the connection string in the web.config file. You also need to add reference to NHibernate.ByteCode.LinFu.dll and LinFu.DynamicProxy.dll which you can find in the NHibernate download.


<section name=”hibernate-configuration” type=”NHibernate.Cfg.ConfigurationSectionHandler, NHibernate”/>


<hibernate-configuration xmlns=”urn:nhibernate-configuration-2.2″>


<property name=”connection.provider”>



<property name=”dialect”>



<property name=”connection.driver_class”>



<property name=”connection.connection_string”>

Data Source=.\SQLEXPRESS;


Integrated Security=True;

User Instance=True


<property name=”proxyfactory.factory_class”>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>



Create a Service class for CRUD

Finally we need a service class which will talk to NHibernate and the datasource to perform operations. Operations like taking the list, inserting new record etc.

public class StudentService


public static ICollection<Student> GetAllStudents()


using (NHibernate.ISession session = SessionFactory.GetNewSession())


return session.CreateCriteria(typeof(Student)).List<Student>();



public static void Add(Student student)


using (NHibernate.ISession session = SessionFactory.GetNewSession())


using (NHibernate.ITransaction transaction = session.BeginTransaction())








As you can see there is no single code written for query statements. This is because the NHibernate framework has taken care about the underlying process. NHibernate exposes two interfaces IQuery and ICriteria to perform query operations.

Download complete project here.

Tagged with: ,
Posted in ASP .NET, Microsoft .NET, NHibernate, Object Relational Mapping (ORM)



In this article we will see how we can make use of jQuery library to make AJAX calls in ASP .NET with the help of HTTPHANDLERS. Also, the use of JSON (Javascript Object Notation) which is a format describing name/vale pairs in a structured manner.

Asynchronous Javascript and XML (AJAX) is a method in which we can exchange data with server without reloading the complete page.

jQuery is a Javascript library which makes it easier to manipulate, navigate DOM elements in a web page. It also helps in implementing AJAX in rapid web application development.  Currently we have Intellisense support for jQuery in Visual Studio 2008/2010.

 HTTP Handler is a process which returns data when its URL is called. The returned data can be anything from simple string to data formats like JSON or XML.

References:  jQuery, MSDN


Download the latest version of jquery from jquery site ( In visual studio 2010 it is added by default when any new web application is created.

Flow Diagram

Example: Making a simple Ajax call

In this example we will be making a simple Ajax call with the help of jQuery.ajax API to the httphandler. The response from the httphandler will be the JSON response which is then updated in the web page. Javascript Object notation (JSON) is a format of key/value pairs to store data. It’s easy to consume in javascript and compact then XML. So let’s start with creating a handler page.

public void ProcessRequest (HttpContext context) {

        string method = context.Request.QueryString[“MethodName”].ToString();

        context.Response.ContentType = “text/json”;

        switch (method)


            case “GetData” :





protected string GetData()


        return (@”{“”FirstName””:””Ravi””, “”LastName””:””Baghel””, “”Blog””:””””}”);


As you can see we are simply putting a response of json type with sample data. In order to demonstrate passing parameter to handler I have used the querystring methodname which will simply switch to the method you want to execute.

Now, we need to make a call to the handler.

<head runat=”server”>


    <script src=”Scripts/jquery-1.5.min.js” type=”text/javascript”></script>

        <script type=”text/javascript” >

    jQuery(function() {



                type : “GET”,

                url : “Data.ashx”,

                data : “MethodName=GetData”,

                success : function(data){

                    $(‘#display’).html(“<h1> Hi, ” + data.FirstName + ” ” + data.LastName + ” your Blog Address is http://&#8221; + data.Blog + “</h1>”);








    <form id=”form1″ runat=”server”>

    <input id=”btnClick” type=”button” value=”Ajax Call” />

    <div id=”display”>




We first need to add a reference to the jQuery library which we downloaded as

<script src=”Scripts/jquery-1.5.min.js” type=”text/javascript”></script>

If you look at the jQuery.ajax syntax you can see different parameters as

Type describes whether the reuest if get or post

URL of the httphandler

Data specifies querystring

Success defines a function which manipulates the response from handler.
Download the complete project here.

Tagged with: , ,
Posted in ASP .NET, jQuery

Web Custom Controls


This article describes the use of custom web controls in ASP .NET. Sometimes, when the requirement becomes complex and it’s difficult to build them using the available standard ASP .NET server controls. We can create a web custom control or web user control which will fulfill the requirement.

Web user controls are easy to build, but are less useful in advance scenarios. The web user control is compiled dynamically which makes it difficult to put in toolbox. It is created similar to the web forms and is placed inside the placeholder. In order to share the web user control, one needs to copy the control manually in its application.

Web custom control on the other hand is harder to build, but provide lots of flexibility. The code is compiled so that it can be placed in the toolbox. We can simply drag and drop the control in application and set the properties. It encourages re-usability, without much maintenance. We can install the single copy of web custom control in global assembly cache (gac) which can be shared by different applications.

If your control has a lot of static layout, a user control might make sense. If your control is mostly dynamically generated — for instance rows of a data-bound table, nodes of a tree view, or tabs of a tab control — a custom control would be a better choice.

Web user controls Web custom controls
Easier to create Harder to create
Limited support for consumers who use a visual design tool Full visual design tool support for consumers
A separate copy of the control is required in each application Only a single copy of the control is required, in the global assembly cache
Cannot be added to the Toolbox in Visual Studio Can be added to the Toolbox in Visual Studio
Good for static layout Good for dynamic layout

Reference MSDN

To download complete example of web custom control click here.

Tagged with: ,
Posted in ASP .NET, Microsoft .NET

Filter, Sort and Joins with LINQ

Language Integrated Query (LINQ) is a new component of .NET framework 3.5. It’s main function is to add data querying capabilities to .NET framework using syntax similar to SQL. LINQ integrates the query syntax within .NET programming which makes it possible to access different data sources with the same syntax. We write query expressions to directly manipulate data from different data sources in C# programming language. Let’s see some basic LINQ queries which are required frequently used.

Let’s go through example side by side. We first create the data source as

public class Student
public int Id;
public string Name;
public string Address;

public class Courses
public int StudentId;
public string CourseName;


Let’s now add some data to it.

var students = new List<Student>(){
new Student {Id=1,Name=”Ravi”,Address=”Chennai”},
new Student{Id=2,Name=”Arun”,Address=”Chennai”},
new Student {Id=3,Name=”Santosh”,Address=”Chennai”},
new Student{Id=4,Name=”Rahul”,Address=”Chennai”},

var courses = new List<Courses>()
new Courses{StudentId=2,CourseName=”C#”},
new Courses{StudentId=1,CourseName=”.NET”},
new Courses{StudentId=3,CourseName=”XML”},
new Courses{StudentId=4,CourseName=”Java”}


Once our data source is ready. It’s time to do some query. We will look at common queries such as Filtering, Sorting, Join.


Filtering means to get only those data which is required based on the given condition. People familiar with SQL statement know it is the where in SQL which does the work of filtering. Here also we have the where clause. for example

var stud = from s in students
where s.Id == 1
select s;

As you can see, how easy it is from the C# programming language to filter the data right from the C# code.


Ordering the elements of a sequence based on one or more attributes. The different sorting operators are orderby, orderbydescending,thenby,thenbydescending, and reverse. for example

var stud = from s in students
orderby s.Name
select s;


Joins are used to join objects in one data source with objects that share a common attributes in another data source. The join operators provided in LINQ are join and groupjoin. for our example, we have two data source with studentid as common in both

var stud = from s in students
join c in courses on s.Id equals c.StudentId
select new { s.Name, c.CourseName };

Displaying result

We can use foreach to loop through records and display output or it can be directly bind to the data bind controls.

Example Join
foreach (var sc in stud)
Console.WriteLine(“{0} has {1} course.”, sc.Name, sc.CourseName);

Example Filter,Sorting
foreach (var s in stud)
Console.WriteLine(“Id = ” + s.Id);
Console.WriteLine(“Name = ” + s.Name);
Console.WriteLine(“Address = ” + s.Address);

Tagged with: , , , ,
Posted in LINQ, Microsoft .NET

PDF file Generation using XSLFO and FOP in .NET

This article describes how to create a PDF document using XSLFO and Apache FOP. In the example I will be exporting datatable to pdf, which we need frequently.
While developing a .NET based applications, we often come to a requirement to create a PDF document. There are lots of tutorials available for exporting to Excel, Word, etc. I decided to use XSLFO and FOP for creation of PDF document.
XSLFO is XSL Formatting Objects and can be used for formatting XML data. XSL Formatting Objects, or XSL-FO, is a markup language for XML document formatting which is most often used to generate PDFs. XSL-FO is part of XSL (Extensible Stylesheet Language), a set of W3C technologies designed for the transformation and formatting of XML data. Refer
Apache FOP (Formatting Objects Processor) is a print formatter driven by XSL formatting objects (XSL-FO) and an output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output. Output formats currently supported include PDF, PS, PCL, AFP, XML (area tree representation), Print, AWT and PNG, and to a lesser extent, RTF and TXT. The primary output target is PDF. Download the latest version of FOP from the following link

Flow Diagram

I have also included the example of producing Datatable in PDf file. You can get the complete project @ my skydrive

Tagged with: , ,
Posted in ASP .NET, Microsoft .NET, XML

XML Content formatting with CSS

As we all are aware of the power of XML technology. Even though the XML language doesn’t inherently include any mechanism for defining how a document looks, CSS (Cascading Style Sheets) makes it possible to add a view to XML documents.  CSS allows us to format the XML content so that it can be displayed in the browsers. CSS styles are stored in style sheets, which contain style rules that apply styles to elements of a given type. Style sheet are usually placed in external style sheet documents with the filename extension .css.

The application of CSS style rules is determined by selectors, which are constructs that identify portions of an XML document. A selector establishes the link between a document and a style or set of styles. There are three kind of selectors used in CSS :

  1. Element type : Selects an element of a given type
  2. Attribute class : Selects an element of a certain class that is identified by a special attribute.
  3. Attribute ID : Selects an element with an ID that is identified by a special attribute.

Though we have lots of properties to deal with. I am explaining only the basics. Let’s take an example :

XML document

<?xml version=”1.0″ ?>
<?xml-stylesheet type=”text/css” href=”message.css” ?>
I am element type.
<messageb class=”msg”>
I am attribute class.
<messagec id=”imsg”>
I am attribute ID.

Save the following document with name message.xml. Now we need to create a style sheet file as message.css and save it in the same location as message.xml.




Tagged with: , , ,
Posted in XML
%d bloggers like this: