Jatin kacha's Blog

Archive for the ‘ASP.NET’ Category

You can use following function to remove HTML links or say HTML anchor tags from a string.

Well its not my own algorithm to do so. I referred following HTML parser to do this. You can download it from here.

It is a an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT.

Here is the function for your assistance.


Function WrapOutAll_A_Tag_From_HTML(ByVal description As String) As String

Dim doc As New HtmlAgilityPack.HtmlDocument()
Dim stream As New System.IO.StringReader(description)

Dim _return As String = “”

Dim all_A As New System.Collections.Generic.List(Of String)
Dim node As HtmlAgilityPack.HtmlNode

For Each node In doc.DocumentNode.Descendants(“a”)

Dim s As String
For Each s In all_A.ToArray()
If Not doc.DocumentNode.SelectSingleNode(s) Is Nothing Then
End If

_return = doc.DocumentNode.InnerHtml()
Catch ex As Exception
_return = description
End Try

Return _return
End Function

Using this function, you can remove HTML links/HTML anchor tags from your string content.


One of the requirement during the maintenance for one of the project was to call a web page iteratively on a scheduled time.

I find one interesting article posting script how to run scheduled task to call a web page using task scheduler in windows.

All you have to do is save following script in a .vbs file, and schedule it to run on windows scheduler.

Here it is:

Call LogEntry()

Sub LogEntry()

‘Force the script to finish on an error.
On Error Resume Next

‘Declare variables
Dim objRequest

Set objRequest = CreateObject(“Microsoft.XMLHTTP”)

‘Put together the URL link appending the Variables.
URL = “http://localhost:82/image-sitemap-generator.aspx”

‘Open the HTTP request and pass the URL to the objRequest object
objRequest.open “POST”, URL , false

‘Send the HTML Request

‘Set the object to nothing
Set objRequest = Nothing

End Sub

You can find more detail from here for implementation of this:


In this article, I will explain you how to read email from POP3 server or read emails from POP3 server which require SSL. Although I have not developed my own library, I prefer to utilize the available resource.

Well, while being in the development, you have very limited time constraint to go and research on POP3 and then develop your own component.

It is sometime wise decision to go and do the Googling and find out your requirement.

After all we, as developer should “do smart work, not hardwork” J

Anyway, for those who have kind of requirement like reading emails from POP3 server from asp.net, reading email from email server in asp.net etc. Here is the article that you probably find it useful.

Well I had requirement in couple of project where I need to collect emails that are there in particular email’s Inbox. Earlier I was used to with component “Indy.Sockets” component, which really help me to achieve my task.

You may find it from here.


It is an open source socket library. It supports may protocols like SMTP, POP3, NNTP, HTTP, and many more.

Then in one of the module that I come to develop, I need to read Inbox of a Gmail account…!

Well as you know, Gmail requires SSL.

But the drawback with component is it does not support SSL.

So I discover Mailsystem.NET.

MailSystem is a suite of .NET components that provide users with an extensive set of email tools.

I will not explain more in detail on this, rather I will rather just explain how to integrate it and use it.

You can find more information from here..


Once you download it and extract it, you will require to do following steps..

  1. Navigate to “Release” folder in extracted folder.
  2. Find these DLLs: ActiveUp.Net.Mail.dll, ActiveUp.Net.Common.dll, ActiveUp.Net.Dns.dll, ActiveUp.Net.Pop3.dll.
  3. Add reference of these DLLs into your file.

Hurray… are almost done with you configuration.

Now, you only just need to develop your script that fetched and read emails from POP3 server.

So for that, here is the readymade script for you J.

public string[] GetDeliveryFailureEMailsAddress()


Pop3Client pop = new Pop3Client();

System.Collections.Generic.List<string> emails = new System.Collections.Generic.List<string>();

try {

// Connect to the pop3 client

pop.ConnectSsl(SMTPHost, Port, SMTPUserId, SMTPPass);

MessageCollection mc = new MessageCollection();

for (int n = 1; n <= pop.MessageCount; n++) {

Message newMessage = pop.RetrieveMessageObject(n);

//do your stuffs here using newMessage object.


} catch (Pop3Exception pexp) {

} finally {

if (pop.IsConnected) {




return emails.ToArray();


One important part in this script is object initialization.

// Connect to the pop3 client

pop.ConnectSsl(SMTPHost, Port, SMTPUserId, SMTPPass);

As per Gmail, you need to set:

Host: pop.gmail.com

Port: 995

As I told earlier, I want to read email from POP3 server that requires SSL in asp.net.

There are different overloaded constructors that you can use to connect to POP3 server from asp.net.

The library itself is very rich. You can achieve following functionality with POP3 server.

  • Read/Read email from POP3 server in asp.net with CRAM authentication.
  • Retrieve/Read email from POP3 server in asp.net asynchronously.
  • Retrieve/Read email from POP3 server in asp.net with secure connection, like SSL in Gmail.
  • Retrieve/Read only email count from POP3 server in asp.net.
  • Retrieve/Read only email header from POP3 server in asp.net.
  • Retrieve/Read full emails from POP3 server in asp.net.
  • Retrieve/Read full emails to a file from POP3 server in asp.net.

How the necessities arise?

Necessity is mother of invention.

I was assigned a task to develop a restaurant portal.

The basic aim behind creation of this project is to have a marketplace for all restaurant owner or hotel business, and provide end user with integrative google map services so that they visualize realtime.

If we are supposed to insert a simple google map, then we just have to insert a piece javascript code, and boom you are done.

But in my project, I have requirement where different restaurant/hotel owner register and give us their details and addresses.

So, What is Google Map API?

The Google Maps API lets you embed Google Maps in your own web pages with JavaScript. The API provides a number of utilities for manipulating maps and adding content to the map through a variety of services, allowing you to create robust maps applications on your website.

All map related functionalities can be achieved as seen on http://maps.google.com/

Then what was hurdle for me in using Map API?

These are the pure JavaScript code..!! You can develop whatever rich Map application you wanted to develop by writing piece of JavaScript codes.

Actually to host a map on your page, you need to have two parameters, Latitude & Longitude. But how do I get lat. and long. from server side scripting?

But I had no idea how to call Google Map API from C#/VB.NET.

So for my project, as usual, I start googling to find out my piece of sweet.

After searching for couple of hours, I come across this good article.


Here the author explained the how to obtain the latitude and longitude co-ordinates for an address using the Google Maps API.

But again here, it is pure JavaScript that utilize Google Map API to get lat & long of any address. But my problem is still there?

Hurrray….. I found the solution

Then accidently I come to across Google Maps API Web Services.

It is basically Maps API Web Services, a collection of HTTP interfaces to Google services providing geographic data for your maps applications.

In the documentation (http://code.google.com/apis/maps/documentation/webservices/),

I see that you can utilize Google Map API web service by making HTTP request to a specific URL, providing necessary parameters with URL. Which in return, gives a response in desired format.

You can get response inform of JSON or XML.

Say for e.g. it can be called like this URL

http://maps.google.com/maps/geo?q=khandala, maharashtra&output=xml&key=xxxxxxxxxxxxxx

Paste it into your browser and you will receive a XML response.

Immediately, I get one “Mantos (Dimag ki batti jala de)” and found a clue J

I thought why not to develop a library that make a call to this URL and parse the returned output to get lat & long…!!?

So for that purpose I write this library.

Obviously, before doing all these, you will need to register with Google Map API and get a key so that you can utilize their API.

Sign up and get a Google Maps API Key.  You will need one for the domain name of where you will be hosting the map.  You can get your API Key from here (http://code.google.com/apis/maps/signup.html)

Following is the complete code that I used to call Google Map Geocoding API from Asp.net.

All you have to do Is to just create a class file and paste the following code. And you are ready to call Google Map Geocoding API.

How to call Geocoding API from Asp.net?

Step 1

/// Resolve addresses into latitude/longitude coordinates using Google MAP API webservices

public static class Geocoder{

private static string _GoogleMapsKey = Config.getAppSetting(“GoogleMapsKey”);

/// Google.com Geocoder

/// Url request to

/// http://maps.google.com/maps/geo?q=your address&output=xml&key=xxxxxxxxxxxxxx

public static Geolocation? ResolveAddress(string query)


if (string.IsNullOrEmpty(_GoogleMapsKey))

_GoogleMapsKey = ConfigurationManager.AppSettings[“GoogleMapsKey”];

string url = http://maps.google.com/maps/geo?q={0}&output=xml&key=” + _GoogleMapsKey;

url = String.Format(url, query);

XmlNode coords = null;


string xmlString = GetUrl(url);

XmlDocument xd = new XmlDocument();


XmlNamespaceManager xnm = new XmlNamespaceManager(xd.NameTable);

coords = xd.GetElementsByTagName(“coordinates”)[0];


catch { }

Geolocation? gl = null;

if (coords != null){

string[] coordinateArray = coords.InnerText.Split(‘,’);

if (coordinateArray.Length >= 2)


gl = new Geolocation(Convert.ToDecimal(coordinateArray[1].ToString()), Convert.ToDecimal(coordinateArray[0].ToString()));



return gl;


public static Geolocation? ResolveAddress(string address, string city, string state, string postcode, string country)


return ResolveAddress(address + “,” + city + “,” + state + “,” + postcode + ” “ + country);



/// Retrieve a Url via WebClient

private static string GetUrl(string url)


string result = string.Empty;

System.Net.WebClient Client = new WebClient();

using (Stream strm = Client.OpenRead(url))


StreamReader sr = new StreamReader(strm);

result = sr.ReadToEnd();


return result;



public struct Geolocation


public decimal Lat;

public decimal Lon;

public Geolocation(decimal lat, decimal lon)


Lat = lat;

Lon = lon;


public override string ToString()


return “Latitude: “ + Lat.ToString() + ” Longitude: “ + Lon.ToString();


public string ToQueryString()


return “+to:” + Lat + “%2B” + Lon;



Step 2

Now, you just need to put a key in AppSetting section that hold your Google Map API key.

Step 3

I have provided 2 overloaded methods to call Geocoding Map API Webservice, named ResolveAddress.

Say for e.g. you can call method like this.

Geocoder.ResolveAddress(“University road”,”rajkot”,”gujarat”,””,”India”)

I hope this will solve your purpose, those who wanted to develop Geocoding application, those who want to access Google Map Webservice API from c#/vb.net.

Happy programming…

Combine/Compress/Minify JavaScript, CSS in Asp.net


When we design and develop the website, the performance is in the core of development. The system you are developing must produce the result with high speed. For the web development perspective, website load performance is very essential thing to take care of. You need good working layout, easy layout and easy navigation.

Here with this article I m not going to talk about of all the aspects of web application performance improvements. But I am specifically targeting the topic when it comes to the CSS and JavaScript faster loading in the client browser. In fact Google is also counting the speed of your website site when indexing to your website.

The goal was to improve overall performance on the client side. At the same time, it will show how we can force a client side script to be coached at the browser, so that in subsequent visit, it will take those scripts from the cache. This becomes increasingly important when using AJAX techniques within an application that introduce new features and functionality.

First of all I will outline the requirements and essential steps that this project is made of. So that if you want to implement the same in your development, it become easy for you to set up project.

To download complete project, click here


To begin with, we will have following list of files to be created in the development studio.

  1. 2 XML files, first one to hold source of JS files for each page and second to hold CSS files for each page.
  2. A generic class that implement IHttpHandler, that will be used to delivery combined and compressed JavaScript/CSS at the client.
  3. And at last your .ASPX file that will be used to serve combined and compressed Javascript/CSS at client side.

Step by Step Implementation:

Now let’s get dig into the actual development. To summarize, let’s say we have a page default.aspx that has following no. of JavaScript files and CSS files. Think of these file that we wanted to combine them and deliver at one go at the client browser.

  1. jquery.js
  2. script-file-1.js
  3. style-1.css
  4. style-2.css

As you can see, we have 2 different JavaScript file & 2 CSS files. So what basically we will do in the next is to create a utility which can combine given JavaScript and compress it, then send it to client browser. Next the same process will be done for the CSS. Both the CSS files will be combined and compressed and send to client browser.

Now it’s time to take a look at into actual stuff that does this underlying work.

First of all we will create a CS class file that will hold the programming stuffs.

So perform the following steps to create & configure that CS class file.

  1. Create CS class file with the name ScriptCombiner.cs and put the following code in that.

ScriptCombiner : IHttpHandler


TimeSpan CACHE_DURATION = TimeSpan.FromDays(1);

HttpContext context;

void ProcessRequest(HttpContext context)



bool IsReusable


get { return
true; }



As you can see, we are implementing the IHttpHandler interface.

You can write custom HTTP handlers to process specific, predefined types of HTTP requests in any Common Language Specification (CLS) compliant language. Executable code defined in the HttpHandler classes, rather than conventional ASP or ASP.NET Web pages, responds to these specific requests. HTTP handlers give you a means of interacting with the low-level request and response services of the IIS Web server and provide functionality much like ISAPI extensions but with a simpler programming model.

We are also implementing IsReusable properly as it is compulsory to implement as a part of inheritance of IHttpHandler interface.

Now, let’s put the nuts & bolts inside the ProcessRequest function. I will also explain you the step by step each execution that is inside this function.

  1. We will also create another CS class file that is used to compress JavaScript. That file is named as “JavaScriptMinifier.cs”. Please take a look at the attached project solution file. As it is contain long lines of code, I can’t put it here.
  2. Complete your class file with following functions.

void ProcessRequest(HttpContext context)


string xStrType, xStrSet, xStrVer, xStrpagecode;

Boolean xBlnCanCompress;

this.context = context;

HttpRequest request = context.Request;

xStrType = (!String.IsNullOrEmpty(request[“type”])) ? request[“type”] : null;

xStrSet = (!String.IsNullOrEmpty(request[“s”])) ? request[“s”] : null;

xStrVer = (!String.IsNullOrEmpty(request[“v”])) ? request[“v”] : null;

xStrpagecode = (!String.IsNullOrEmpty(request[“pcode”])) ? request[“pcode”] : null;

//first check if client browser can support compressions

xBlnCanCompress = CanClientGZip(request);

using (MemoryStream memStream = new


Stream writer;

//if browser is supporing GZip compression then create a new object using ICSharpCode.SharpZipLib.GZip

//library which allow the compressed respose to send to client

if (xBlnCanCompress)

writer = (new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(memStream));


writer = memStream;

using (writer)


//now its time to read all the script/css files into a StringBuilder object.

StringBuilder combinedSource = new

foreach (string file in GetFileNames(xStrSet, xStrpagecode, xStrType))

combinedSource.Append(System.IO.File.ReadAllText(context.Server.MapPath(file), Encoding.UTF8));

//Upto now we have combined all css/javascript based on request.

//its now time to remove extra white spaces and other unwanted characters from respose.

//compression will take place now.

string minified;

//use the YUI Javascript/CSS minifier to compress all js files

if (xStrType == “js”)

minified = combinedSource.ToString();


minified = CompressCSS(combinedSource.ToString());

// Send minfied string to output stream

byte[] bt = Encoding.UTF8.GetBytes(minified);

writer.Write(bt, 0, bt.Length);


//cache the respose so that in next request it can be reused

byte[] responseBytes = memStream.ToArray();

//context.Cache.Insert(GetCacheKey(xStrSet, xStrType, xStrVer, xBlnCanCompress), responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration, CACHE_DURATION);

// Generate the response

this.WriteBytes(responseBytes, xBlnCanCompress, xStrType);



bool CanClientGZip(HttpRequest request)


string acceptEncoding = request.Headers[“Accept-Encoding”];

if (!string.IsNullOrEmpty(acceptEncoding) &&

(acceptEncoding.Contains(“gzip”) || acceptEncoding.Contains(“deflate”)))




// helper method that return an array of file names inside the text file stored in App_Data folder

string[] GetFileNames(string setName, string pagecode, string type)


System.Xml.XPath.XPathDocument doc2;

System.Xml.XPath.XPathNavigator navigator;

System.Xml.XPath.XPathNodeIterator iterator;

System.Collections.Generic.List<string> scripts = new System.Collections.Generic.List<string>();

string key;

if (type == “js”)

key = “scriptfile”;


key = “cssfile”;

if (System.Web.HttpContext.Current.Cache[key] != null)


doc2 = (System.Xml.XPath.XPathDocument)System.Web.HttpContext.Current.Cache[key];




string filename;

filename = System.Web.HttpContext.Current.Server.MapPath(String.Format(“~/App_Data/{0}.xml”, setName));

doc2 = new System.Xml.XPath.XPathDocument(filename);

System.Web.HttpContext.Current.Cache.Insert(key, doc2, new System.Web.Caching.CacheDependency(filename), DateTime.Now.AddMinutes(60), TimeSpan.Zero);


navigator = doc2.CreateNavigator();

if (type == “js”)

iterator = navigator.Select(“/scripts/page[@pagecode='” + pagecode + “‘]/script”);


iterator = navigator.Select(“/styles/page[@pagecode='” + pagecode + “‘]/style”);

while (iterator.MoveNext())


return scripts.ToArray();


string GetCacheKey(string type, string setName, string version, bool cancompress)


“HttpCombiner.” + setName + “.” + type + “.” + version + “.” + cancompress;


void WriteBytes(byte[] bytes, bool isCompressed, string type)


HttpResponse response = context.Response;

response.AppendHeader(“Content-Length”, bytes.Length.ToString());

if (type == “js”)

response.ContentType = “application/x-javascript”;


response.ContentType = “text/css”;

if (isCompressed)

response.AppendHeader(“Content-Encoding”, “gzip”);


response.AppendHeader(“Content-Encoding”, “utf-8”);




response.ContentEncoding = Encoding.Unicode;

response.OutputStream.Write(bytes, 0, bytes.Length);



string GetScriptTag(string setname, string pageid, string type, string ver)


string result = “”;

if (type == “js”)

result += String.Format(“<script type=\”text/javascript\” src=\”/” + Web.Utility.Functions.GetURLPrefix() + “ScriptCombiner.axd?s={0}&v={1}&type=js&pcode={2}\”></script>”, setname, ver, pageid);


result += String.Format(“<link link href=\”ScriptCombiner.axd?s={0}&v={1}&type=css&pcode={2}\” rel=\”stylesheet\” type=\”text/css\”/>”, setname, ver, pageid);

return result;


string CompressCSS(string body)


body = Regex.Replace(body, “/\\*.+?\\*/”, “”, RegexOptions.Singleline);

body = body.Replace(” “, string.Empty);

body = body.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine, string.Empty);

body = body.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);

body = body.Replace(Environment.NewLine, string.Empty);

body = body.Replace(“\\t”, string.Empty);

body = body.Replace(” {“, “{“);

body = body.Replace(” :”, “:”);

body = body.Replace(“: “, “:”);

body = body.Replace(“, “, “,”);

body = body.Replace(“; “, “;”);

body = body.Replace(“;}”, “}”);

body = Regex.Replace(body, “/\\*[^\\*]*\\*+([^/\\*]*\\*+)*/”, “$1”);

body = Regex.Replace(body, “(?<=[>])\\s{2,}(?=[<])|(?<=[>])\\s{2,}(?=&nbsp;)|(?<=&ndsp;)\\s{2,}(?=[<])”, string.Empty);

return body;


You are now almost done with 50% of work for your project.

Now let’s take a look at the few of important execution steps that are in this function.

First of all we are declaring four different string variables:

string xStrType, xStrSet, xStrVer, xStrpagecode;

They will be used to get the Querystring passed in to this handler. This is utilized later on the code.

Moving next, you will find these function call:

//first check if client browser can support compressions

xBlnCanCompress = CanClientGZip(request);

This is basically to check does client browser support GZip compression.

Gzip compression, otherwise known as content encoding, is a publicly defined way to compress textual content transferred from web servers to browsers. HTTP compression uses public domain compression algorithms, like gzip and compress, to compress XHTML, JavaScript, CSS, and other text files at the server. This standards-based method of delivering compressed content is built into HTTP 1.1, and most modern browsers that support HTTP 1.1 support ZLIB inflation of deflated documents. In other words, they can decompress compressed files automatically, which saves time and bandwidth.

In the next step it is preparing the stream object used to hold the response output. We will not take dipper look into that code. As I expect that the a beginning developer even must be able know about next few line of code. J

Let’s move to the line of code:

//now its time to read all the script/css files into a StringBuilder object.

StringBuilder combinedSource = new

foreach (string file in GetFileNames(xStrSet, xStrpagecode, xStrType))

combinedSource.Append(System.IO.File.ReadAllText(context.Server.MapPath(file), Encoding.UTF8));

As you can see in the foreach loop, it is calling to method GetFileNames, by passing 3 different parameters. Here this is also core and important part of this project. Let me outline you first what this function basically do. This function will read to the “script.xml” file that hold content of script file that we want to load. Please look inside the attached project solution to understand it better. The function will read xml file and return array of string object containing JavaScript files to read.

In the subsequent line of code, it iterate through each file name and read it. Each content of read file is placed inside a StringBuilder object.

Please take look at the code inside the GetFileNames function to understand what is actually happening inside it. It fetches the JavaScript/CSS based on the parameter passed. And return either the JavaScript file name array or CSS file name array.

So now we have a combined script/CSS with us. It’s a time to minify JavaScript/CSS now.

Following line of code will minify respective JavaScript/CSS based on type of client script requested.

//use the YUI Javascript/CSS minifier to compress all js files

if (xStrType == “js”)


JavaScriptMinifier minifier = new

minified = minifier.Minify(combinedSource.ToString());




minified = CompressCSS(combinedSource.ToString());


The JavaScriptMinifier has been created in the 2nd step. Please refer to the attached solution project for more detail regarding this class file. I have adopted this class file from one of the article

You will also see function CompressCSS that is used to compress CSS file. The compressor of CSS file is done through just few regular expression. JavaScript compression has different algorithm.

After that it is calling to WriteBytes function that will prepare the combined & compressed JavaScript & CSS response and send it to the client.

Hurray… as part of implementation we are done.

Now it’s time to check that in action. You can run the project attached here with and check it In live action.

To download complete project, click here

Let’s compare the result of two different pages. The first one is with the compressed JavaScript & CSS. The second one is with the normal JavaScript & CSS. We will also see the difference in load time and size of content received.

Response time with compressed JavaScript & CSS.

Response time without compressed JavaScript & CSS.

As you can see from given statistics

With Combined & Compressed JavaScript and CSS ..

Total request: 3

Response size: 16.3 KB

Without Combined & Compressed JavaScript and CSS ..

Total request: 5

Response size: 96 KB

You can clearly see the difference between these two request.

To get more idea open and run the project yourself. That will give you better idea.

Hope you will find it very useful.

Happy coding…. J

Date: Monday, February 01, 2010

The new .net 3.5 has significant improved features. This feature makes the .net programming concept more sophisticated. You will now be able to write less code and build more dynamic application using those.

From all of them what the most I like is the LINQ, which allow you to query over variety of objects.

LINQ is all about queries, they returns a set of matching objects, a single object, or a subset of fields from an object or set of objects. In LINQ, this returned set of objects is called a sequence.

Basically LINQ comes in variety of flavors’ like following:

  • LINQ to Objects
  • LINQ to XML
  • LINQ to Dataset
  • LINQ to SQL
  • LINQ to Entities

Well there is a detailed discussion on LINQ further in this article. Let me first make you guys introduce to the language improvements in .net 3.5. In fact I believe that these new improvements are essential to learn before we actually get dig into the LINQ J.

To summarize quickly, here are the list of new language feature that are shipped with .Net 3.5.

  • Automatic properties
  • Object initializers, Collection initializers
  • Anonymous types
  • Extension methods
  • Query Expression

Well if you are the C# developer, I believe you will really love to have such significant improvement. Because these features puts extra wing on your programming skill.

The important is not that you learn the latest technology of .Net 3.5 like WCF, WPF, Silverlight etc. These are the core part of basic programming. Its like you should be knowing the if syntax of C programming language before you actually write your first “Hello word” program J

So let’s go through each of them step by step and try to understand what they are and how it can help the developer to create rich internet/desktop application.

  • Automatic Property

Before I explain you the concept of “automatic property in .net 3.5, can you guys first please try to go through the following code?



int _cartId;

int CartId


get { return _cartId; }

set { _cartId = value; }


int _customerid;

int Customerid


get { return _customerid; }

set { _customerid = value; }


int _billingaddressid;

int Billingaddressid


get { return _billingaddressid; }

set { _billingaddressid = value; }


int _shippingaddressid;

int Shippingaddressid


get { return _shippingaddressid; }

set { _shippingaddressid = value; }


MShippingCartItem _cartitem;

MShippingCartItem Cartitem


get { return _cartitem; }

set { _cartitem = value; }



Most of the time we are used to write such model classes. This are the most basic and popular mechanism in returning a wrapper classes. The basic purpose of writing such getter/setter property is to hide the actual private member of our classes. It has been the standard pattern to access the private method of any classes. Well you may arise with a question that why do we actually need to write such getter/setter properties. Can’t we simply expose the private member? Well the answer is YES, but I would request you to remember the fundamental of object oriented programming. J

Anyway there are basically two reason of not doing so. Following are this:

  1. You won’t be easily able to bind those private variable to controls
  2. You will not be able to modify them into property later on.

The first point is quite understandable, what do you mean by the second one? Well, say for e.g. if you need to add any business logic or validation logic when assigning value to any private variable then? You will not be able to do that.

So what if we need not to write even the private variables? Exited, yes the new version of .Net 3.5 allows you have such facility. The concept is called automatic property. All you have to do is to write the getter/setter property. You need not to worry about the private member of that property. The compiler will decide and prepare base private member for you on the fly.

See the example in the following.



int CartId





int Customerid





int Billingaddressid





int Shippingaddressid





MShippingCartItem _cartitem;

MShippingCartItem Cartitem






Now it this case when the compiler will encounter this properties while compiling your code, it will automatically expose the private variable for each of property with its associated type. For e.g. compiler automatically assume and expose the _cartid private variable of integer type. Using advantage of this is we need not to worry about the underlying private variable. In future we can add any sort of validation logic in this property.

  • Object initialization, collection initialization

I would like to explain this concept by taking the example of automatic property so that I maintain the continuity for you to understand. Say for e.g. when we want to use the “shopping cart” class that we created earlier. What we do is write following code.

MShoppingCart cart = new

cart.CartId = 1;

cart.Customerid = 1001111;

cart.Shippingaddressid = 2333;

cart.Billingaddressid = 2232;

With the feature supported by the .net framework 3.5, you can take advantage of what is called “syntactic sugar”, and that is object initializers.

Using object initializers, you can write the same code given above, in following way.

MShoppingCart cart = new
MShoppingCart {CartId =1, Customerid=1001111, Billingaddressid=2232, Shippingaddressid =23333 };

So it allows you to pass the value of all property at the time of initializing the object.

In fact it not only allow to initialize object’s property in this way, you can also have nested initialization of object within any object.

To demonstrate you, see the following example.

MShoppingCart cart = new
MShoppingCart { CartId = 1, Customerid = 1001111, Billingaddressid = 2232, Shippingaddressid = 23333, Cartitem = new
MShippingCartItem { }

If you see in the highlighted (underlined) part of above code, you can clearly see that the child object can also be initialized in the same way.

As if the new object initialization enhancements were not enough, someone at Microsoft must have said, “What about collections?” Collection initialization allows you to specify the initialization values for a collection, just like you would do for an object, as long as the collection implements the

System.Collections.Generic.ICollection<T> interface.

List<string> presidents = new
List<string> { “Name 1”, “Name 2”, “Name 3” };

foreach (string president in presidents)




  • Anonymous types

What is anonymous type?

Well, we have been familiar till date with different types. They are either custom classes or any of .net’s build in type. So what is actually the anonymous type is. The answer is that the “Anonymous type” has no type defined to it. It has no type name. Though there should be at least one type name associated in .Net. In anonymous type, the type name is specified by the developer doing the programming. It is the compiler which will identify the type to associate with the declaration of any anonymous type.

There is also another significant different in anonymous type is that it is called immutable. The definition of immutable type is that the one that is declared and initialized once. It can’t be altered later on. So anonymous type has the same characteristic. Once you declared and initialized, you can’t alter the anonymous type afterward.

This is also why anonymous types have been introduced. They allow us to create a type on the fly and therefore return only certain values of a given named type. This is very handy when only a subset of properties is needed, properties are joined together or even objects are joined together.



void Main(string[] args)


// create a list of carts with dummy data.

List<MShoppingCart> carts = new

MShoppingCart { CartId=101, Customerid=1001, Billingaddressid=20, Shippingaddressid =30});

MShoppingCart { CartId = 102, Customerid = 1002, Billingaddressid = 22, Shippingaddressid = 33 });

MShoppingCart { CartId=103, Customerid=1003, Billingaddressid=23, Shippingaddressid =34});

// query the cart collection to collect cart with id of 101

var result = from c in carts

where c.CartId >= 101

// put the result in a anonymous type

new { c.Billingaddressid };

// loop over the result.

foreach (var item in result)


// print out the name of the item.

Console.WriteLine(item.Billingaddressid );




Anonymous type are mostly used when working with the LINQ. It is utilized highly while querying to your data in LINQ. It is irrespective which flavor of LINQ you are using.

Although the anonymous type can be used in your own code also. It is especially useful when we want to combine different variables into one.

Se for e.g. following example:

// create an anonymous type instance with a name.

var anonymousType = new


Name = name,

Age = age,

Nationality = nationality


// print the name to the console.


Though the real time use of anonymous type Is when you use it with the LINQ. I need to write a separate article to demonstrate you actual usage LINQ. J

  • Extension methods

An extension method is a static method of a static class that you can call as though it were an instance method of a different class.

To make you understand the extension method, let me first re cape the class level methods (static methods) and instance methods. The primary different between these two is that the instance method can also be access by initializing object of any class. It can’t be invoked by using class name only. The exact opposite of that is class method. You can only call static class method using the name of class only. You can’t access them using the instance of same class.

I am not gonna give you any example for the above explanation as I expect from you guys that you are familiar with the different I explained.

Extension method is a way of extending existing classes for whatever additional functionality. Let me demonstrate you that by example.

namespace ExtensionMethods




bool IsNumeric(this
string str)




int i = int.Parse(str);










In the above given example, almost everything seems to be similar what we are used to in normal programming. But, the difference is clearly seen. You should be able to notice that in the “IsNumeric” static method parameter are passed using this keyword. This keyword tells the compiler what you are going to extend for particular given type. So in this example it tells you that it extends the existing string class.

See for e.g. how to use the extension method.

string s = “someValue”;

bool bs = s.IsNumeric();

// bs is false;

string i = “7”;

bool bi = i.IsNumeric();

// bi is true;

  • Query Expression

One of the conveniences that the C# language provides is the foreach statement. When you use foreach, the compiler translates it into a loop with calls to and MoveNext. The simplicity the foreach statement provides for enumerating through arrays and collections has made it very popular and often used.

One of the features of LINQ that seems to attract developers is the SQL-like syntax available for LINQ queries. The first few LINQ examples in the first chapter of this book use this syntax. This syntax is provided via the new C# 3.0 language enhancement known as query expressions. Query expressions allow LINQ queries to be expressed in nearly SQL form. To perform a LINQ query, it is not required to use query expressions. The alternative is to use standard C# dot notation, calling methods on objects and classes.

Although it is occupy a dedicated book for detail understanding of query expression with LINQ. Just to summarize you, here is the example that shows you what actually query expression does.

For e.g.

string[] names = {

“Adams”, “Arthur”, “Buchanan”, “Bush”, “Carter”, “Cleveland”,

“Clinton”, “Coolidge”, “Eisenhower”, “Fillmore”, “Ford”, “Garfield”,

“Grant”, “Harding”, “Harrison”, “Hayes”, “Hoover”, “Jackson”,

“Jefferson”, “Johnson”, “Kennedy”, “Lincoln”, “Madison”, “McKinley”,

“Monroe”, “Nixon”, “Pierce”, “Polk”, “Reagan”, “Roosevelt”, “Taft”,

“Taylor”, “Truman”, “Tyler”, “Van Buren”, “Washington”, “Wilson”};

IEnumerable<string> sequence = from n in names

where n.Length < 6

select n;

foreach (string name in sequence)


Console.WriteLine(“{0}”, name);


Though query expression can be used by two different way. 1) is using dot notation and 2) is using expression syntax.

Hope I could make you understand what are the new improvements in the newer version of .net 3.5.

Once you are aware and familiar with this feature, you are ready to get dig into dip into the word of .net 3.5 for all new existing experience in developing rich internet/enterprise application.

Best luck J


ASP.NET Development

Performance Improvement

Among the 95% of the .NET developers that said they are
using some flavor of Ajax either in production, development or prototype, the
most used AJAX Framework is ASP.NET AJAX, with 73,7%, followed by the Ajax
Control Toolkit which is used by almost half of the .NET developer that are
using Ajax.

However ASP.NET AJAX model is showing performance problem.
The web application developed in ASP.NET AJAX makes the site slow down.

So following are the few of guideline which will help you
out to improve performance of ASP.NET AJAX application. This will basically
apply to the ASP.NET AJAX version 1.0 final release.

  1. Use HttpWatch to check the network traffic.
    1. This is one of important tool using which you can check the data returned by
      the server. There is dedicated tool available for this. Moreover to that
      you can also utilize Firebux extension of firefox to watch network
      traffic. The dedicated tool is available for the download from following
      URL: http://www.httpwatch.com/download/.

      This is a limited feature version.

  2. Use “ScriptReferenceProfile” to show Javascript reference
    1. ScriptReferenceProfiler is an open source tool on CodePlex, for analysis the JavaScript
      references of ASP.NET AJAX, we can simply add the following code to our
      page in order to show the JavaScript references imported by

      <microsoft:scriptreferenceprofiler runat=“server”>


You can obtain it from the following URL

Reference: http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=13356

  1. Web.Config Optimization
    1. To have optimized web.config file our application, all we need to do is to
      have a compression and caching is enabled in web.config file for the
      ASP.NET AJAX Includes. You can use the following code in web.config file
      to enable compression & caching for AJAX includes.



      <scriptResourceHandler enableCompression=“true” enableCaching=“true”/>



      Also check before and after result of before and after of enabling
      caching & compression in network traffic.

      Now this is limited to the compression and caching for AJAX includes. In our site we also
      generally have many other script files included. There can also be no. of
      different CSS files, JS files etc. We can also compress them so that It make fewer request in bytes.

      Basically there is no any method available in ASP.NET which allows the
      compression of JS & CSS files. We need to do it manually and
      reference those compressed file in our application.

      One very key important point to consider is related to change management
      of those files. Once you have compressed file in place and referenced in
      your different pages, If your JS file or CSS
      file need to have any modification, then you again have to recompress it
      from newer version.

      So this method should be adopted for such scripts or CSS which are less
      frequently changed.

      There are different tools available which allows your script and CSS file
      compression. Following are the different methods which can be used for
      this purpose.

      1) Yahoo compresser (http://yui.2clics.net/)

      2) http://www.vlead.in/resources/tools/minify-javascript/index.php
      (The best one which I utilized)

  2. Optimization of ScriptManager
    1. The ScriptManager control manages client script for AJAX-enabled ASP.NET Web
      pages. By default, the ScriptManager control registers the script for the
      Microsoft AJAX Library with the page. This enables client script to use
      the type system extensions and to support features such as partial-page
      rendering and Web-service calls. Following, we need to setting
      the property of ScriptManager to optimize the performance of ASP.NET

Set “scriptMode” to Release.

for e.g.

<asp:ScriptManager ID=”ScriptManager1″
runat=”server” ScriptMode=”Release”>


Moreover to this set “debug” mode in “compilation” section of web.config file
to false.

Disable partial page rendering

If we using the UpdatePanel in the page, we must set this property to true,
conversely, if the UpdatePanel is not using in our page, it would be better
that we set the EnablePartialRendering to false.

For e.g.

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”


  1. Move All Script Tags After Body Content
    1. ASP.NET ScriptManager control has a property “LoadScriptsBeforeUI”, when set to
      false, should load all AJAX
      framework scripts after the content of the page. But it does not
      effectively push down all scripts after the content. Some framework
      scripts, extender scripts and other scripts registered by Ajax Control
      Toolkit still load before the page content loads.

So these are the basic general guidelines which can be
followed one by one to have an improved ASP.NET AJAX response.

for ASP.NET Application Performance

Following, I will demonstrate some of important guideline
for the improvement of ASP.NET application. These guidelines should be
implemented carefully by taking into consideration of development needs. It is
not necessary to have all following steps followed.

  1. Removing unnecessary HTTP MODUES from site.
    1. There are several ASP.NET default HttpModules which
      sit in the request pipeline and intercept each and every request.

      For example, if you aren’t using Membership and Profile provider, you
      don’t need “FormsAuthentication” module. If you aren’t using Windows
      Authentication for your users, you don’t need “WindowsAuthentication”.

      We can remove those unnecessary references of HTTP modules from
      web.config using <remove> tag.

      Generally following are the HTTP modules which are not generally used in
      our current development architecture.

      <remove name=”WindowsAuthentication” />

      <remove name=”PassportAuthentication” />

      <remove name=”AnonymousIdentification” />

      <remove name=”UrlAuthorization” />

      <remove name=”FileAuthorization” />

  2. Removing or compressing “VIEWSTATE” from page
    1. We can override few of method of default System.Web.UI.Page class of .net

      Use the following file and include it in your project’s APP_CODE.
      Inherits rest of all your pages from this page instead of regular System.Web.UI.Page

      Ref: BasePage.vb

  3. Use caching for pages which changes less frequently
    1. There are several ways to use the cache; we’ll focus on the easiest tricks to
      get you started, then point you toward some resources that will help you
      tackle more advanced ways to utilize the cache.

      The simplest solution is to use the OutputCache directive on your pages
      or user controls.

  4. Disable VIEWSTATE for pages where no Grid related functionality.
    1. One should set the VIEWSTATE disabled in those pages where there is no grid
      level manipulation. When we have a simple page with no complex logic, it
      should be disabled.

      Moreover to that set the following pages which are not security

      1) EnableViewStateMac=”false”

      2) ViewStateEncryptionMode=”never”

  5. Use classical ASP type of page for normal pages.
    1. Another important point is to use a classical ASP type of pages which are simple.
      Those pages which do not have any complex display should be developed
      like normal ASP pages. Please check the following referenced page for
      this similar purpose.

      these are such files which do not have underlying code behind file
      attached to it.

      We can also utilize the feature of “include” file method which is there
      in classical ASP.

for structuring ASP.NET Application

In the following, I will demonstrate the basic guidelines
for the structuring of any web application.

See these guidelines are generally be best suitable for SEO
oriented sites. It can also be adopted for general site also keeping
requirement in mind.

These guidelines are prepared keeping modularized
development in mind. So there are no such tricks that by following them you
will be able to better structure your site. One should do the do modularized
development in their programming also to achieve this.

  1. Use dedicated folders for JS & CSS files.In a site generally there are different JS & CSS files for different
    functionality. These JS & CSS files should be accordingly structure
    inside your website. Please take a look at the following example for the
    better illustration of this method.

    Say for e.g. in a site few pages have functionality to display a jQuery
    zoom light box when anyone click on the image of product.

    So following should be the structure of JS & CSS files.

    In this example, assume there are also few global JS & CSS. So I will
    also demonstrate the purpose of integrating them in site.



    | |___lightbox

    | |___lightbox.js





    | |___lighbox

    | |___ lighbox.css



    This modularization can also be used to
    differentiate CSS & JS for each page of site.

    Modularization is also not limited to the CSS & JS files, one can
    follow same modularization concept across different type of files also
    like XML content, flash content, image folders etc.

  2. Use proper naming conversion in CSS files.
    1. Care full design of CSS classes and attributes provide better traceability. As
      you just shown above that the CSS & JS can be modularized. We should
      also use proper naming convention in those CSS file. If you follow these
      conventions, you can easily identify respective class.

      Say for e.g.

      you set naming abbreviation of respective CSS as per below.

      1) global.css
      = glb

      2) lightbox.css = lg

      so now you can have following CSS class/section defined in respective css

      like in global.css






      color: #7D3D0D;

      font-family: Arial;

      font-size: 20px;

      font-weight: normal;

      text-decoration: none;

      clear: both;


      in the same way, you can also different class in lighbox.css



      width: 100%;

      margin: 20px 10px 10px 10px;




      width: 700px;

      height: 600px;


  3. Configure
    APP_CODE to have two sub directories. Each sub directory can be used for
    different language. It is generally like following.



    Respective programming files should be placed in respective folders. Also
    make sure to configure code sub directory in web.config also.

before final release of site

Following, there are some important and necessary checks
that web-sites should be checked against before the official launch.

  1. Favicon
    1. A favicon icon the tab or window in which your website is open in the
      user’s browser. It is also saved with the bookmark so that users can
      easily identify pages from your website.

      for e.g.

      <link href=”images/fav_icon.ico” rel=”icon”
      type=”image/Jpeg” />

  2. Title & Meta data
    1. Your page title is the most important element for SEO and is also important so
      that users know what’s on the page. Make sure it changes on every page
      and relates to that page’s content.

      Also one should make sure that related meta data
      details are also get placed in every pages and are changes as it should
      be to different pages.

  3. Cross-Browser Check
    1. The most popular browsers to check are Internet Explorer 6, 7 and 8, Firefox
      3, Safari 3. Following are the few methods used to do cross browser check

      1) XecoCode (http://www.xenocode.com/browsers/)

      2) IETester (http://www.my-debugbar.com/wiki/IETester/HomePage)

      3) Browser shot (http://browsershots.org/)

  4. Links
    1. Don’t just assume all your links work. Click on them. You may often forget to
      add “http://” to links to external websites. There may be case when some
      URL rewriting related prefix or postfix would be forgotten.

My tweets