Jatin kacha's Blog

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.

www.indyproject.org/

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

http://www.agilecomponents.com/

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

pop.Disconnect();

}

}

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.
Advertisements
Tags:

How to convert a value into Enum?

In project, we sometime come across a kind of situation where we need to convert some value to Enum and an Enum object into certain value.

One solution to this is we can write chunk of switch-case statement and return the desired result.

But is there any rationalize method to achieve this? Yes here is the piece of code that you may find it useful. I have implemented it in many of my project and it really helps me reduce some overloaded work for me.

So here is that code for you in which I demonstrate how you can convert a value into Enum object.

using System;

using System.Collections.Generic;

using System.Linq;

public
static
class
EnumsConverter

{


public
static T ConvertValueToEnum<T>(object value, T defaultValue)

{


Type enumType = Reflection.ExtractEnumType(typeof(T));


if (enumType == null)

{


throw
new
ArgumentException(“Type T is not an enumeration”, “T”);

}


try

{


return (T)Enum.Parse(enumType, value.ToString());

}


catch (ArgumentException)

{


return defaultValue;

}

}


public
static T ConvertValueToEnum<T>(object value)

{


Type enumType = Reflection.ExtractEnumType(typeof(T));


if (enumType == null)

{


throw
new
ArgumentException(“Type T is not an enumeration”, “T”);

}


return (T)Enum.Parse(enumType, value.ToString());

}

}

Here there are two overloaded methods. All you have to do is pass your desired enumeration object. The method itself will identify and return attached valued to that particular Enum object.

Happy programming…

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.

http://webcodeblog.com/2010/04/24/obtain-latitude-and-longitude-co-ordinates-for-an-address-using-asp-net-and-the-google-maps-api/

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;

try{

string xmlString = GetUrl(url);

XmlDocument xd = new XmlDocument();

xd.LoadXml(xmlString);

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

}

///
<summary>

/// 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…

Introduction:

  1. By definition communication means: “It is the process of passing information and understanding from one person to another. It is essentially a bridge of meaning between people. By using the bridge of meaning, a person can safely cross the river of misunderstanding that separates all the people.

    History of communication says that it comes from a Latin word: “communicare”, which as three meaning imminent from it:

    1. “To make common”, which is probably can be derived from 2 or 3.
    2. “Cum + munus”, its like having a gift to share in mutual donation.
    3. Building together a defence.

    From the developer point of view (I hope reader is somewhere involved programming J ), communication is real important factor to improvise one’s potentiality. A good leader has to be a good communicator. It’s not so that communication skills means the way you talk, the way you present your idea to others. Communication skill involves many other areas. Like: Verbal communication, Non verbal communication, written communication, Gesture communication etc.

    All these are nuts & bolts for being a good communicator.

    Communication makes you perfect in demonstrating your ideas to front end people. Let’s take few examples that give you glimpse why communication skill is so important for a developer/leader.

    1. Think what if you are a technical leader and your client has given you a task. You are supposed to present him technical feasibility report or say you wanted to explain him/her flow of your system. If you are not have a good command over your English, collections vocabulary, you are not used to prepare & utilize MS word, then?
    2. In number of different occasions, we as developer/leader need to talk with different users. These users may be end users of system, stack holders, clients who have given as project to work on. Different people have different emotions and different style of communication. In these cases, you need to communicate in a balanced view.
    3. When I was a fresher, digging into the word of programming. We were instructed that when any CRUD operation is performed, you need to show users a message that operation successfully completed. When in an application someone create a PO from their site, I say them “operation successfully completed.” But what operation? J

    Well, there are many many many other points that can be put here in list, but in that case you may avoid to read my article. And I don’t want to make that happen J.

    So let’s take a took some important characteristics of a good communication.

    1. It’s a two way process – It’s quite understandable. In any communication system there are two parties involved. One is Transmitter another is receiver. Overall motto of communication is to delivery your message to other parties. It may be comprising of debate, discussion etc.
    2. It’s continuous process
      Communication process continues to the extent that ideas and messages are communicated and received. Like for e.g. if we are at system analysis stage for any project. Continues discussion is very important. As a analyst, we have to be in contact with stack holder to understand their requirement. We have to identify end user who is going to use the software/application.
    3. It can be in formal way or informal way, though it may be in different medium.

    Elements of communication

    Why communication is so important for us?

    It is important because….

    1. Making enterprise run smoothly.
    2. Quick decision and implementation.
    3. Project planning & coordination.
    4. Maximizing productivity.
    5. Morale building/Motivation tool and developing your democratic leadership style.

    Properly recorded communication documents, system analysis docs., technical specification, ER diagrams, these are the documents that we generally prepare so that it make ease for any new comer in organization to get settle with his project. This makes organization to run smooth.

    Moreover, properly maintained documents allow you to make quick discussion in hurry.

    For proper co-ordination and maintenance, developer can utilize different project management tools. To name few here are some of them.

    1. www.mantisbt.org – MantisBT is a popular free web-based bug tracking system.
    2. Basecamp
    3. Central Desktop
    4. 5pm

    You can get more information for such tools from this article.

    http://tomuse.com/top-10-best-free-online-project-management-application-services/

    There are different kinds of communication methods. Like…

  • Verbal or oral communication
  • Written communication
  • Formal communication, informal communication

Developers are used to choose from these methods according to availability of resources and situation. Mostly verbal or written communication is widely popular among us. Formal communication has special delegation of authority, which means a project leader has given sufficient rights to make certain decision without asking to their superiors. Where in informal communication, there is no authority defined. It is conveyed by simple gesture, glance, smile, silence.

Effective communication

  1. While you are in presentation, instructing to group of developers, doing video conferencing with other peers on remote location, Clarity of Thoughts
    is really important.
  2. Something just can’t be explained by words. You have to react with your body. It is important to attach importance to actions rather than words.
  3. Participation – as said earlier, it’s a two way process which require involvement of all the parties. If you are not involved mentally in communication process, you are not going to perform your task well. Your presence is must. If your leader informed you about coding standard to be maintained, and if you don’t remember those, you will in trouble.
  4. What to communicate? – Prepare the agenda that you need to talk about before you initiate. Collect all the required documents, technical specifications, proof reports, different analysis report before you talk with your superior or clients.
  5. When to communicate? – Mutually decide timing with your parties involved in. You can either initiate or let your parties to initiate and decide when to communicate. You can place meeting request in outlook, send them emails, take care of geographical difference in timing, ask for the availability and long will be the meeting etc.
  6. How to communicate? – Choose the medium that you want to communicate through. If discussion matter to be explained to a technical person, chat or peer to peer method can be best suited. If talking with non technical person, you have to represent your ideas to your parties in such a way that he can understand your thoughts. You may explain them using different diagrams, preparing documents and go through documents while you discuss, giving them references about what are trying to demonstrate him. There are no. of collaboration tools are there in market which you can use for this purpose. Like we have google wave, Webex, Skype voice chat, video conferencing through different tools etc.
  7. How often to communicate? – As I said that it’s a continuous process. You can’t make sure that having discussion for 5-6 hours, you will come out with your objective. It’s an iterative process. You should try to divide your agenda into groups. Discuss them at different time interval. Make all agenda clear step by step. Try to identify issues relating to each other and communicate them as well.
  8. What is the objective of communication? – It is almost similar to identifying communication goal/agenda. But the objective of communication here is in the term of what is the outcome we are expecting to come from it. When project is running out of time, meeting by team leader is to motivate developers to encourage them to get it done at right time.
  9. Keep the channel alive
  10. Cordial superior – Once finished communication, it should be conveyed to your superior that what was the outcome? What where the agenda? What are clients new requirements? What do you suggest for different points to client? How was the response from client etc.
  11. Get the feedback – Generally when you dial in to customer care of your cellular provider, right after you finish your talk with them, you receive message regarding feedback for the person you talked with. This is the process of evaluation. It’s not to make garbage employees collection. It’s about gathering customer’s response how they like customer care person to be behaved. So gathering those feedback we can evaluate and enhance process.

To make such effective communication, what should you do? Or what should you have? Here is answer for you.

  • Develop a positive attitude.
  • Bad feelings should not hamper discussion – Human is social animal. Different people have different mentality. All have different approach to grow and perform tasks. When we are working in organization, we work in a team. It is sometime obvious that different group member have conflict with other peers. When working as team, it is must that team show their team effort rather than individuals. So your bad feeling with others should not hinder communication.
  • Use logic to manage difficult situations
  • Develop Harmonious interpersonal relationships. It is secret of business relationship.

And for effective oral communication, you should have..

  • Understanding and use of appropriate language.
  • Organize and sequence of thoughts properly.
  • Vocabulary power.
  • Command over illustrations, examples.
  • Proper pronunciation.
  • Proper use of sound system/equipments.
  • Listening ability.
  • Effective telephonic talk.

And for written communication….

  • Command over the language.
  • Word power and spelling.
  • Correct grammar.
  • Proper structuring of the written message
  • Use of appropriate channels like courier, e-mail, etc.
  • Attention to hand writing, typing, printing.

And for non verbal communication….

  • Observation skills.
  • Awareness about the body movement.
  • Proper interpretation of the non-verbal message.

Well no system is perfect in the world. There is always barrier in everything we do. Effective communication itself has its own. It is said that 30% communication the word are failed to success due to loss in transmission. Inaccurate translation, false impression, fear, noise etc. are the elements as barrier of communication. Though I am not going to tell you all here J.

So here I would like to conclude my article, hope I covered all skills of written communication in my article J. I also hope that I am able to convey to my message.

So see you next time till then happy communication & happy programming…

Cheers..

Emotional Quotient (EQ) refers to an someone’s ability and understanding of his or her emotions along with his or her colleagues’ emotions at the workplace to create better work coordination and environment.

Basically, Intelligence Quotient (IQ) defines the level of intelligence an employee possesses to understand, interpret and implement one’s knowledge in varied situations leading to his or her growth as well as the Company’s.

IQ is mainly used to measure one’s cognitive capabilities, such as the capacity to learn or understand new situations; reasoning through a given predicament or setting and the ability to apply one’s knowledge in current circumstances. Emotional Intelligence (EI) skills do not limit themselves to sympathy, intuition, imagination, flexibility, stress management, management, truthfulness, genuineness, intrapersonal skills and interpersonal skills but extend far beyond these.

When working in an organization, an employee with higher EI than others can convince his or her colleague(s) about a certain argument by appealing to their emotions rather than presenting facts and figures. While judging an individual’s EI, keep in mind these few points:

* An employee’s ability to comprehend and apply his or her personal emotions
* An employee’s ability to express his or her feelings, beliefs and thoughts
* An employee’s ability to recognize and appreciate his or her own potential
* An employee’s ability to manage his or her personal and professional life under stress and pressure
* An employee’s ability to adapt to different work environments and handle varied challenges that come his or her way
* An employee’s ability to possess self-confidence
* An employee’s ability to not only work towards the growth of the Company but also towards the growth of his or her co-workers

For best results, employees must develop communication and organizational skills for good decision-making as well as good inter-personal relations with co-workers. An individual’s success rate at work depends on his or her EQ as well as IQ in the ratio of 80:20.

Why 80:20? Well, because, EQ help individuals build and maintain relations with peers and superiors, increases productivity and opens up doors for clarity in communication.

While hiring, corporates look at an individual’s EQ rather than IQ. Having a high IQ will help build interpersonal and intrapersonal skills to a certain extent, unlike EQ, which talks about one’s character based on the way he or she writes or replies to mail, collaborates and networks with peers and subordinates and works towards attaining Company goals.

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

Introduction:

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

Setup:

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.

public
class
ScriptCombiner : IHttpHandler

{


private
readonly
static
TimeSpan CACHE_DURATION = TimeSpan.FromDays(1);


private
HttpContext context;


public
void ProcessRequest(HttpContext context)

{

}


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

public
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
MemoryStream(8092))

{


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


else

writer = memStream;


using (writer)

{


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


StringBuilder combinedSource = new
StringBuilder();


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();


else

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

}

}

private
bool CanClientGZip(HttpRequest request)

{


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


if (!string.IsNullOrEmpty(acceptEncoding) &&

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


return
true;


return
false;

}


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


private
static
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”;


else

key = “cssfile”;


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

{

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

}


else

{


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”);


else

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


while (iterator.MoveNext())

scripts.Add(iterator.Current.InnerXml);


return scripts.ToArray();

}


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

{


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

}


private
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”;


else

response.ContentType = “text/css”;


if (isCompressed)

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


else

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

context.Response.Cache.SetCacheability(HttpCacheability.Public);

context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));

context.Response.Cache.SetMaxAge(CACHE_DURATION);

response.ContentEncoding = Encoding.Unicode;

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

response.Flush();

}

public
static
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);


else

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;

}


public
static
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
StringBuilder();

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
JavaScriptMinifier();

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

}


else

{

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

It has been a debate from long time that who is faster, asp.net or php?

So many times I have heard php guyes claim that php is so much faster than Asp.Net and that Asp.Net is clunky and slow.

I have collected few of important resource to make it very clear.

See basically both the development are different like two side of coin. Each of it have its own purpose to choose for your development need. It highly depend how is your requirement.

Any way check from here to get more detail on this debate.

http://bit.ly/4Fdqa9

http://bit.ly/QMgQy

http://misfitgeek.com/blog/aspnet/php-versus-asp-net-ndash-windows-versus-linux-ndash-who-rsquo-s-the-fastest/

Cheers 🙂

My tweets