How to enable HTTPCompression at IIS6

Last week, I was working on performance improvement of one of my projects. So I read several Articles on Internet and found that we can configure HTTPCompression on IIS. It compress the response sent to the browser and the size of the response get reduced dramatically i e major improvement in performance. So I wanted to share you all.

I’ll discuss it point wise.

1: Why do we need HTTP compression?

Nowadays, we are building Rich Internet Applications, which is increasing the size of  Pages heavily. Means the more page size, more time it’ll take to load. But, IIS provides a feature to compress the responses and most common browsers support the HTTP Compression.

Means you can configure, HTTP compression at your web server, and browsers will understand it.

2: How much page size will be reduced.

Normally there are two algorithm supported. One is gzip and other one is deflate. I used Gzip in my website and found that the Page size was reduced by 60 to 70%.

3: When we don’t need compression.

If your page size are very less by default less than 60 to 70k. Then I think you don’t need this. Also if your users are having very high speed Internet then also you can ignore it. Because obviously the compression/decompression is a overhead if you are not gaining much.

4: How HTTPCompression works:

When a browser send a request to IIS, it also the send the information that what all kind of encoding supports. You can see the request header by many tools (One is Firebug that is available as a plugin for Firefox). You will be able to see following line in the request header.

Accept-Encoding: gzip,deflate

It says that this browser accepts gzip and deflate encoding

Now when IIS receives the request and find that that the requester can understand the given encoding. Based on the configuration, it encodes the response.

Now you can see the Response header. There it is mentioned, in what encoding is done on response as you can see it in header as

Content-Encoding: gzip

It means the response was encoded with gzip.

Here I am showing you all an example of Gmail.

Here I am showing the request header sent by the Firefox 3.5

It says it can accept encoding : gzip,deflate

Now let’s see the  response header

As you can see, the response is sent is gzipped format

5: What will happen if Browser does not understand any encoding?

Actually when browser sends a request to the server it tells the server what all encoding it supports and that is available in Request Header. If it does not support,  it may not send the Accept-Encoding tag.

Now when IIS receives the request and if it does not find any encoding mechanism supported by Requester, It does not apply any compression/encoding mechanism and the response is not encoded and sent it in normal format.

So you don’t need to worry about, it any browser does not understand gzip or deflate, then what will happen. IIS takes care, IT only encodes when it is supported by the requester.

6: How to configure HTTPCompression at IIS,

There are two types of Compression that can be configured.

First one: Static ( for static files like some css, javascript file etc.)

Other one: Dynamic (means for for dynamic generated page/response) .

There is no console available to configure to Configure HTTPCompression.

So there are two ways to configure HTTP compression at IIS.

First: Update the IIS metabase files directly.

Second: Use some commands to update it.

Here I’ll discuss the second one and will discuss the commands that can be used to configure it.

Here you need to do two things.

First: Configure the IIS for HTTPCompression

Second: Configure what all types/extension will be encoded

So for that you need to run the following commands at your web server:

Configure the IIS6 for HTTP Compression-

First Open command prompt and go to your IIS root folder, normally it would be “c:\inetpub\adminscripts\” then follow the below steps.

Static Compression:

To see whether Compression is enabled or not:

cscript adsutil.vbs get w3svc/filters/compression/parameters/HcDoStaticCompression

Enable/Disable Static Compression

adsutil.vbs set w3svc/filters/compression/parameters/HcDoStaticCompression true/false

To view what all files will be encoded:

cscript adsutil.vbs get W3SVC/Filters/Compression/gzip/HcFileExtensions (for gzip)

cscript adsutil.vbs get W3SVC/Filters/Compression/deflate/HcFileExtensions (for deflate)

To add more files for Compression

cscript adsutil.vbs set W3SVC/Filters/Compression/gzip/HcFileExtensions “js” “css” “png” “bmp” “swf” “doc” “docx” (for gzip)

cscript adsutil.vbs set W3SVC/Filters/Compression/deflate/HcFileExtensions “js” “css” “png” “bmp” “swf” “doc” “docx” (for deflate)

Dynamic Compression:

To see whether Compression is enabled or not:

cscript adsutil.vbs get w3svc/filters/compression/parameters/HcDoDynamicCompression

Enable/Disable Dynamic  Compression

cscript adsutil.vbs set w3svc/filters/compression/parameters/HcDoDynamicCompression true/false

To view what all files will be encoded:

cscript adsutil.vbs get W3SVC/Filters/Compression/gzip/HcScriptFileExtensions (for gzip)

cscript adsutil.vbs get W3SVC/Filters/Compression/deflate/HcScriptFileExtensions (for deflate)

To add more file extension

cscript adsutil.vbs set W3SVC/Filters/Compression/deflate/HcScriptFileExtensions “asp” “exe” “dll” “aspx” “asmx” (for gzip)

cscript.exe adsutil.vbs set W3Svc/Filters/Compression/GZIP/HcScriptFileExtensions “asp” “exe” “dll” “aspx” “asmx” (for deflate)

Now reset the IIS. Now you web server is ready to compress the responses based on incoming Requests.

I’ll suggest to all configure it at IIS6 and see/analyze the performance.

Note: I have explained above the settings for IIS6.

Please share you feedback:

Thanks,

Brij

Javascript Dictionary

Might be some of you already know about Dictionaries in JavaScript. But recently I, worked on JavaScript dictionary. And that was really interesting and helpful for me. So I wanted to share my findings to you all. Please share your feedback for my posting.

JavaScript provides us a way to make a Dictionary object and use it as a C# dictionary. Although we would not be having all the properties that is supported by C# dictionary, but we will be able to use it as a normal dictionary i.e. in key value format.

Let’s see one simple example:

I have stored list of all week days as keys and assigned some numbers to these as values. Let’s see the code.

function CreateDayDictionary() {
var days = new Array();
days['Sunday'] = 1;
days['Monday'] = 2;
days['Tuesday'] = 3;
days['Wednesday'] = 4;
days['Thursday'] = 5;
days['Friday'] = 6;
days['Saterday'] = 7;
}

Now to fetch the values at any point of time, we can fetch as per the code given below. Here I have made a function to alert some data. It can be as

 function ShowDays() {
        alert(days['Sunday']);
        alert(days['Thursday']);
        alert(days['Saterday']);
    }

It will show three alerts, first 1 then 5 and lastly 7.

So we can store some global data in our page. And this data we can access, at different events, we require.

Similarly we can store objects in the dictionary in same way. Let’s see the code

 function CreateDictionarywithObject() {
        var objDictionary = new Array();
        // Creating a dictionary which is holding five objects
        for (var i = 0; i < 5; i++) {

            var obj= new myClass();
            obj.member1 = 'member1data' + i;
            obj.member2 = 'member2data' + i;
            obj.member3 = 'member3data' + i;

            objDictionary['Obj' + i] = obj;
        }
        //Fetching third Object
        var fetchedObj = objDictionary['Obj3'];
        alert(fetchedObj.member1);
        alert(fetchedObj.member2);
        alert(fetchedObj.member3);

    }

Now, one more thing if you want to pass the data from server to client as a JSON data, you can serialize a C# dictionary at server side, and again when you will desterilize at client side you will be getting the dictionary as we discussed above. Let’s see the magic.

Here I have made one class Employee as

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public int Age { get; set; }
}

Now, on the page load, I created a dictionary with some data, like below

List<Employee> employees= new List<Employee>()
        {
            new Employee{ Id=1000, Name="Brij", Age=27, Salary=800000},
            new Employee {Id=1001, Name = "Rahul", Age=28,Salary=500000},
            new Employee {Id=1002, Name = "Anoop", Age= 29 ,Salary = 60000}
        };
Dictionary<string, Employee> employeeData = employees.ToDictionary(em => em.Id.ToString(), emp => emp);

Now serialize the data using JavaScriptSerializer and assigned it in a hidden variable

JavaScriptSerializer ser = new JavaScriptSerializer();

hfData.Value = ser.Serialize(employeeData);

Now I have a textbox and a button to show employee details. My aspx code looks like this

<body>
    <form id="form1" runat="server">
    <div>
        <span>Id: </span> &nbsp;<input id="idName" type="text" /><br  />
        <input id="Button2" type="button" value="Displaydetail" onclick="show();"/>
        <asp:HiddenField ID="hfData" runat="server" />
    </div>
    </form>
</body>

Here I will be entering the Id of the employee, and on clicking the button “Show details”, I am displaying the data as JavaScript alerts. So let’s see the JavaScript code

function parseEmployeeData() {
        //for parsing the data
        employees = JSON.parse(document.getElementById("<%= hfData.ClientID%>").value);

    }

    function show() {
        parseEmployeeData();
        var key = document.getElementById('idName').value;
        var emp = employees[key];
        if (typeof (emp) != 'undefined') {
        // If key is found then dispaly the details
            alert(emp.Name);
            alert(emp.Age);
            alert(emp.Salary);
        }
        else {
        // key not found
            alert('No data found');
        }
    }

As you can see, first I am parsing the data using JSON, and then finding the value in the dictionary using some key and displaying the details as a JavaScript alert.
This sample is just for an example, to show how we can use JavaScript dictionary in our daily life.

Here, I have used namespace System.Web.Script.Serialization for serializing the data at C#. Also, I have included JSON JavaScript file in my application to parse the data at Client Side.

Happy Client Scripting

Thanks,

Brij

Looking in Func Delegates

This is an extension of my earlier blog post. I myself, find delegates as one of  the most powerful type to use in C#. It helps in writing very flexible and scalable program.

As I already discussed in my last blog that in the traditional way, we need to write more code.There I also discussed, One predefined delegate Action delegate that is provided by the framework.There are four flavors of Action delegate is provided.

One more type of predefined delegate that is provided by .NET that is counterpart Action delegate  . As we saw that it always returns void. But Func returns a value instead of void as Action does.

There is also 5 flavours of the Func delegate is provided.These are

- Public delegate TResult Func<TResult>()

– Public delegate TResult Func<TResult>()  // Take no parameter and returns a value

-  Public delegate TResult Func<T, TResult>(T t)  // Take one input parameter and returns a value

- Public delegate TResult Func<T1, T2, TResult>(T1 t1, T2 t2)  // Take 2 input parameter and returns a value

- Public delegate TResult Func<T1, T2, T3, TResult>(T1 t1, T2 t2, T3 t3)  // Take 3 input parameter and returns a value

- Public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 t1, T2 t2, T3 t3,T4 t4)  // Take 4 input parameter and returns a value

If we see the declaration, TResult is put at last, this is just a convention. One can put it wherever s/he wants.

First lets see first one , with no parameter and returning a value

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable and assigning it a function
Func<string> myFunc = SayHello;

//Calling function using Func Delegate
string returnedString = myFunc();

Console.WriteLine(returnedString);

Console.ReadKey();
}

private static string SayHello()
{
return "Hello Dude!!";
}
}

Now lets move to code to another overload of Func Delegate. It takes two input parameter and resturns a value.

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes two input parameters and returns a value) and assigning it a function
Func<double, double, double> myFunc1 = Add;

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5);

Console.WriteLine(sum);

Console.ReadKey();
}

private static double Add(double first, double second)
{
return first + second;
}
}

It is also same as Action delegate. i e It can also be used with Anonymous functions and Lambda functions. Lets have a quick look on both

Anonymous Function:

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes three input parameters and returns a value) and assigning it an Anonyomus function
Func<double, double, double, double> myFunc1 = delegate(double d1, double d2, double d3)
{
return d1 + d2 + d3;
};

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5, 5.5);

Console.WriteLine(sum);

Console.ReadKey();
}
}

Lambda Function:

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
static void Main(string[] args)
{

Func<Employee,string> checkEmployee = s=>{
if (s.Id > 11)
return s.Name;
else
return "Employee is not with the given Criteria.";
};

Console.WriteLine(checkEmployee(new Employee() {Id=12, Name="Brij"}));
Console.WriteLine(checkEmployee(new Employee() {Id=10, Name="Abhijit"}));

Console.ReadKey();
}
}

Hope you all must have enjoyed the delegates.

We use delegates a lot. But most of us, use the traditional way in programs. When I learnt first these Action and Func delegates few weeks back, I found it very useful. It helps us writing better and well organised code, also less error prone code. I talked to lot of developers, they didn’t have any idea about these predefined delegates. So I thought of sharing to you all.

Please share your valuable feedback.

Cheers,

Brij