Monday, November 23, 2009

5 simple steps to execute unit testing using

5 simple steps to execute unit testing using NUNIT


Introduction and Goal

Unit testing is validation and verification
methodology where the developers test the individual units of source code. In
this tutorial we will try to understand how we can do unit testing using NUNIT
framework. This tutorial we will try to understand the 5 important steps to do
unit testing using NUNIT.
Please feel free to download by 400 .NET interview question free EBook from
http://www.questpond.com which
covers sections like basic .NET, Design patterns,3.5,SQL Server,UML and lot of
other sections.
The example which we will test Below is a simple class ‘clsInvoiceCalculation’
which calculates total cost by taking per product cost and number of products as
input.
public class clsInvoiceCalculation

{

public int CalculateCost(int intPerProductCost, int intNumberOfProducts)

{

return intPerProductCost * intNumberOfProducts;

}

}

Let’s say we want to execute the below test
case on the above class using NUNIT.














Per product cost

Number of products
Expected
output
10 20 200 ( test case passed)


The 5 basic steps to execute the unit test using NUNIT

Step 1:- The first step is to download
to the NUNIT software from
http://nunit.org/index.php?p=download

Step 2:- Create a new C# class project and add reference to “C:\Program
Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll”. We also need to
add reference to the class project which we are testing i.e. the invoice
project.



Step 3:- Add reference to the NUNIT and
your invoice project in your code.


using NUnit.Framework;
using Invoice;

Step 4 :- We need to create a simple
class with ‘TestFixture’ as attribute. We then to create a method attributed
with ‘Test’ which will have our test.


You can see in the above figure how the
‘TestInvoiceCalculation’ method creates an object of ‘clsInvoiceCalculation’ ,
passes the values and checks if the returned values have the expected results.
‘Assert’ command is used to check if the expected output and the results return
match.



Step 5:- Once we are finished with our
test case we need to compile the same to create a DLL. Once the DLL compilation
is done go to program files – nunit and click on nunit. Now the nunit user
interface will open. Click on file – open project and select your test DLL.
Once you select your DLL you will get a screen as shown below. On the right hand
side you can see your test class with test function which has the test case.
Check the test function and hit run. Now if the test case passes you will see a
full green color or else you will see a red color with details of why the test
case fails.



Screenshot when the test case fails.

Monday, October 12, 2009

.NET 4.0 FAQ Part 1 -- The DLR

Introduction
Where do I get .Net 4.0 from?

What are the important new features in .NET 4.0?

What’s the most important new feature of .NET 4.0?
What is DLR in .NET 4.0 framework?
Can you give more details about DLR subsystem?

How can we consume an object from dynamic language and expose a class to dynamic languages?

Can we see a sample of ‘Dynamic’ objects?

What’s the difference between ‘Dynamic’, ‘Object’ and reflection?

What are the advantages and disadvantage of dynamic keyword?

What are expando objects?

Can we implement our own ‘Expando’ object?

What is the advantage of using custom ‘Expando’ class?

What are IDynamicMetaObjectProvider and DynamicMetaObject?

Can we see performance difference between reflection and dynamic object execution?

Thanks, Thanks and Thanks
.NET 4.0 detail list of new features



Introduction

In this article we will discuss about what new features are provided by .NET framework 4.0. We will then take up the DLR feature and discuss about ‘dynamic’ and ‘expando’ objects. We will also create a custom ‘expando’ class and see what benefits we can get from the same. Many developers mistake ‘dynamic’ objects where made to replace ‘reflection’ and ‘object’ type, we will try to remove this misconception also.
Sorry for the repost. I have deleted the old article due to image upload issues and uploaded again.

Please feel free to download my free 500 question and answer eBook which covers .NET 4.0 , ASP.NET , design patterns, silver light, LINQ, SQL Server , WCF , WPF, WWF@
http://www.questpond.com/

Where do I get .Net 4.0 from?

You can download .NET 4.0 beta from
http://www.microsoft.com/downloads/details.aspx?FamilyID=ee2118cc-51cd-46ad-ab17-af6fff7538c9&displaylang=en

What are the important new features in .NET 4.0?

Rather than walking through the 100 new features list, let’s concentrate on the top 3 features which we think are important. If you are interested to see the detail list of new features click here.
• Windows work flow and WCF 4.0:- This is a major change in 4.0. In WCF they have introduced simplified configuration, discovery, routing service, REST improvements and workflow services. In WWF they have made changes to the core programming model of workflow. Programming model has been made more simple and robust. The biggest thing is the integration between WCF and WWF.
• Dynamic Language runtime: - DLR adds dynamic programming capability to .NET 4.0 CLR. We will talk more about it as this FAQ moves ahead.
• Parallel extensions: - This will help to support parallel computing for multi-core systems. .NET 4.0 has PLINQ in the LINQ engine to support parallel execution. TPL (Task parallel library) is introduced which exposes parallel constructs like parallel ‘For’ and ‘ForEach’ loops, using regular method calls and delegates.
We will be talking in more details of the above features in the coming sections.


What’s the most important new feature of .NET 4.0?

WCF and WWF new features are one of the most interesting features of all. Especially the new programming model of WWF and its integration with WCF will be an interesting thing to watch.
DLR, parallel programming and other new features somehow just seem to be brownie points rather than compelling features. Kathleen Dollard's talks about it in more details
http://msmvps.com/blogs/kathleen/archive/2009/01/07/the-most-important-feature-of-net-4-0.aspx
We will be seeing more of these features as we continue with the FAQ.

What is DLR in .NET 4.0 framework?

DLR (Dynamic language runtime) is set of services which add dynamic programming capability to CLR. DLR makes dynamic languages like LISP, Javascript, PHP,Ruby to run on .NET framework.


There are two types of languages statically typed languages and dynamically typed languages. In statically typed languages you need to specify the object during design time / compile time. Dynamically typed languages can identify the object during runtime. .NET . DLR helps you to host code written in dynamic languages on top of your CLR.


Due to DLR runtime, dynamic languages like ruby, python, JavaScript etc can integrate and run seamlessly with CLR. DLR thus helps to build the best experience for your favorite dynamic language. Your code becomes much cleaner and seamless while integrating with the dynamic languages.


Integration with DLR is not limited to dynamic languages. You can also call MS office components in a much cleaner way by using COM interop binder.
One of the important advantages of DLR is that it provides one central and unified subsystem for dynamic language integration.


Can you give more details about DLR subsystem?

DLR has 3 basic subsystems:-

• Expression trees: - By this we can express language semantics in form of AST (Abstract syntax tree). DLR dynamically generates code using the AST which can be executed by the CLR runtime. An expression tree is a main player which helps to run various dynamic languages javascript, ruby with CLR.
• Call site caching: - When you make method calls to dynamic objects DLR caches information about those method calls. For the other subsequent calls to the method DLR uses the cache history information for fast dispatch.
• Dynamic object interoperability (DOI):- DOI has set of classes which can be used to create dynamic objects. These classes can be used by developers to create classes which can be used in dynamic and static languages.
We will be covering all the above features in more detail in the coming FAQ sections.



How can we consume an object from dynamic language and expose a class to dynamic languages?

To consume a class created in DLR supported dynamic languages we can use the ‘Dynamic’ keyword. For exposing our classes to DLR aware languages we can use the ‘Expando’ class.
So when you want to consume a class constructed in Python , Ruby , Javascript , COM languages etc we need to use the dynamic object to reference the object. If you want your classes to be consumed by dynamic languages you need to create your class by inheriting the ‘Expando’ class. These classes can then be consumed by the dynamic languages. We will be seeing both these classes in the coming section.


Do not forget to download help document for library authors regarding how to enable the dynamic language across platform using DLR
http://dlr.codeplex.com/Wiki/View.aspx?title=Docs

Can we see a sample of ‘Dynamic’ objects?

We had already discussed that ‘Dynamic’ objects helps to consume objects which are created in dynamic languages which support DLR.The dynamic keyword is a part of dynamic object interoperability subsystem.
If you assign an object to a dynamic type variable (dynamic x=new SomeClass()), all method calls, property invocations, and operator invocations on ‘x’ will be delayed till runtime, and the compiler won't perform any type checks for ‘x’ at compile time.
Consider the below code snippet where we are trying to do method calls to excel application using interop services.
// Get the running object of the excel application
object objApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
// Invoke the member dynamically
object x = objApp.GetType().InvokeMember("Name", System.Reflection.BindingFlags.GetProperty, null, objApp, null);
// Finally get the value by type casting
MessageBox.Show(x.ToString());

The same code we now write using ‘dynamic’ keyword.
// Get the object using
dynamic objApp1 = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
// Call the
MessageBox.Show(objApp1.Name);

You can clearly notice the simplification of property invocation syntax. The ‘invokemember’ is pretty cryptic and prone to errors. Using ‘dynamic’ keyword we can see how the code is simplified.


If you try to view the properties in VS IDE you will see a message stating that you can only evaluate during runtime.


What’s the difference between ‘Dynamic’, ‘Object’ and reflection?

Many developers think that ‘Dynamic’ objects where introduced to replace to ‘Reflection’ or the ‘Object’ data type. The main goal of ‘Dynamic’ object is to consume objects created in dynamic languages seamlessly in statically typed languages. But due to this feature some of its goals got overlapped with reflection and object data type.
Eventually it will replace reflection and object data types due to simplified code and caching advantages. The main goal of dynamic object was never introduced in the first place to replace ‘reflection’ or object data type, but due to overlapping features it did.


What are the advantages and disadvantage of dynamic keyword?

We all still remember how we talked bad about VB6 (Well I loved the language) variant keyword and we all appreciated how .NET brought in the compile time check feature, well so why are we changing now.
Well, bad developers will write bad code with the best programming language and good developers will fly with the worst programming language. Dynamic keyword is a good tool to reduce complexity and it’s a curse when not used properly.

So advantages of Dynamic keyword:-

• Helps you interop between dynamic languages.
• Eliminates bad reflection code and simplifies code complexity.
• Improves performance with method call caching.
Disadvantages:-

• Will hit performance if used with strongly typed language.

What are expando objects?

‘Expando’ objects serve the other side of interoperability i.e. enabling your custom classes to be consumed in dynamic languages. So you can create an object of ‘Expando’ class and pass to dynamic languages like ruby, javascript, python etc. ‘Expando’ objects helps to add properties on fly. It’s an efficient implementation of dynamic property bag. In order to use ‘ExpandoObject’ we first import ‘System.Dynamic’ namespace.
using System.Dynamic;
We then create the object of ‘ExpandoObject’ and assign it to an object which created from ‘Dynamic’ class type. Please note if we have used ‘Dynamic’ objects and not expand objects as we still do not know what properties are going to be created during runtime.

dynamic obj = new ExpandoObject();

For creating dynamic property we just need to write the property name and set the value.

obj.Customername = "Some Customer Name";

Finally we display the value.
MessageBox.Show(obj.Customername);


Can we implement our own ‘Expando’ object?

‘Expando’ object internally is nothing but properties added to a collection. So you can create your own version of ‘Expando’ object.
The first thing we need to do is inherit from ‘DynamicObject’ class.
public class clsMyExpando : DynamicObject
{
}

As said previously we need to define a collection where we can save properties. In the second step we have created a dictionary object to maintain the properties in the collection.
public class clsMyExpando : DynamicObject
{
Dictionary items= new Dictionary();
}

We can now use the ‘TryGetMember’ and ‘SetGetMember’ to define our get and set properties.
public class clsMyExpando : DynamicObject
{
Dictionary items = new Dictionary();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return items.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
items[binder.Name] = value;
return true;
}}

We can now create object of our customer ‘expando’ class and assign the same to the dynamic class reference. In the below code snippet we have assigned a dynamic property called as ‘Name’.
dynamic obj = new clsMyExpando();
obj.Name = "Dynamic Property";


What is the advantage of using custom ‘Expando’ class?

Custom ‘Expando’ object can be used to gain performance. In case your class has some static properties and some dynamic properties, then you can create static properties in the custom expand class itself as shown in the below code. So when the static properties of the object are called it will not make calls to the dictionary collection thus increasing performance. DLR engine first tries to call the property names rather than calling the ‘TryGetMember’ or ‘TrySetMember’.

First thing avoid ‘expando’ custom classes if you do not have dynamic property requirement and you do not want to communicate with dynamic languages. In case you have dynamic property requirement ensure that properties which you are very sure are added to the class and dynamic properties are implemented by inheriting the dynamicobject class.
public class clsMyExpando : DynamicObject
   {
Dictionary items
       = new Dictionary();
  
       private string _Name;
       public string Name
       {
           get
           {
               return _Name;
           }
           set
           {
               _Name = value;
           }
       }
       public override bool TryGetMember(
           GetMemberBinder binder, out object result)
       {
           return items.TryGetValue(binder.Name, out result);
       }

       public override bool TrySetMember(
           SetMemberBinder binder, object value)
       {
           items[binder.Name] = value;
           return true;
       }

   }


What are IDynamicMetaObjectProvider and DynamicMetaObject?

‘Dynamic’ objects implement ‘IDynamicMetaObjectProvider’ and return ‘DynamicMetaObject’. Both these interfaces are core classes which implement interoperability between dynamic languages. So when should we use it:-

  • If we want to implement our custom logic for fast dynamic property retrieval we can implement ‘IDynamicMetaObjectProvider’ and ‘DynamicMetaObject’. For instance you would like to provide a fast algorithm to retrieve the most used properties. So you can plug-in the algorithm using ‘IDynamicMetaObjectProvider’.


Can we see performance difference between reflection and dynamic object execution?

Coming soon….

Thanks, Thanks and Thanks


http://tomlev2.wordpress.com/category/code-sample/
has sample code which
shows how to implement dynamic objects.

http://dlr.codeplex.com/Wiki/View.aspx?title=Docs%20and%20specs
:- Codeplex
link for the DLR project.

http://msmvps.com/blogs/kathleen/archive/2009/01/07/the-most-important-feature-of-net-4-0.aspx

:- Discusses about the most important feature of .NET 4.0

http://blogs.msdn.com/brada/archive/2008/10/29/net-framework-4-poster.aspx

:- A nice 4.0 complete posture , ensure you have silver light plug-in to take
advantage of the zoom in feature.

http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx

:- Sir Hansel talks about the dynamic keyword.
http://www.codeproject.com/KB/cs/dynamicfun.aspx
:- Dynamic example
implementation.

http://en.wikipedia.org/wiki/Dynamic_Language_Runtime
:- Wiki link for DLR.
http://msdn.microsoft.com/en-us/library/dd233052(VS.100).aspx
:- Download
link for 4.0 and VS 2010 .

http://www.developerfusion.com/article/9576/the-future-of-net-languages/2/

:- Discusses about new language features of 4.0 , I have not seen anything
simpler than this on the web.

http://www.gotnet.biz/Blog/file.axd?file=2009%2F6%2FHow+I+Learned+to+Love+Metaprogramming+-+CodeStock+2009.pdf

:- Nice PDF by Kevin MVP for meta programming.

.NET 4.0 detail list of new features

Thanks to
http://blogs.msdn.com/brada/archive/2008/10/29/net-framework-4-poster.aspx publish a detail poster of .NET 4.0 features.

Tuesday, September 29, 2009

Best Practices No 5: - Detecting .NET application memory leaks





Introduction

Memory leaks in .NET application have always being programmer’s nightmare. Memory leaks are biggest problems when it comes to production servers. Productions servers normally need to run with least down time. Memory leaks grow slowly and after sometime they bring down the server by consuming huge chunks of memory. Maximum time people reboot the system, make it work temporarily and send a sorry note to the customer for the downtime.

Please feel free to download my free 500 question and answer eBook which covers .NET , ASP.NET , SQL Server , WCF , WPF , WWF@ http://www.questpond.com .


Avoid task manager to detect memory leak

Using private bytes performance counters to detect memory leak

3 step process to investigate memory leak

What is the type of memory leak? Total Memory = Managed memory + unmanaged memory

How is the memory leak happening?

Where is the memory leak?

Source code

Thanks, Thanks and Thanks



Avoid task manager to detect memory leak

The first and foremost task is to confirm that there is memory leak. Many developers use windows task manager to confirm, is there a memory leak in the application?. Using task manager is not only misleading but it also does not give much information about where the memory leak is.


First let’s try to understand how the task manager memory information is misleading. Task manager shows working set memory and not the actual memory used, ok so what does that mean. This memory is the allocated memory and not the used memory. Adding further some memory from the working set can be shared by other processes / application.


So the working set memory can big in amount than actual memory used.

Using private bytes performance counters to detect memory leak

In order to get right amount of memory consumed by the application we need to track the private bytes consumed by the application. Private bytes are those memory areas which are not shared by other application. In order to detect private bytes consumed by an application we need to use performance counters.
Below are the steps we need to follow to track private bytes in an application using performance counters:-
  • Start you application which has memory leak and keep it running.
  • Click start à Goto run and type ‘perfmon’.
  • Delete all the current performance counters by selecting the counter and deleting the same by hitting the delete button.
  • Right click à select ‘Add counters’ à select ‘process’ from performance object.
  • From the counter list select ‘Private bytes’.
  • From the instance list select the application which you want to test memory leak for.
If you application shows a steady increase in private bytes value that means we have a memory leak issue here. You can see in the below figure how private bytes value is increasing steadily thus confirming that application has memory leak.


The above graph shows a linear increase but in live implementation it can take hours to show the uptrend sign. In order to check memory leak you need to run the performance counter for hours or probably days together on production server to check if really there is a memory leak.

3 step process to investigate memory leak

Once we have confirmed that there is a memory leak, it’s time to investigate the root problem of the memory leak. We will divide our journey to the solution in 3 phases what, how and where.
  • What: - We will first try to investigate what is the type of memory leak, is it a managed memory leak or an unmanaged memory leak.
  • How: - What is really causing the memory leak. Is it the connection object, some kind of file who handle is not closed etc?
  • Where: - Which function / routine or logic is causing the memory leak.

What is the type of memory leak? Total Memory = Managed memory + unmanaged memory

Before we try to understand what the type of leak is, let’s try to understand how memory is allocated in .Net applications. .NET application have two types of memory managed memory and unmanaged memory. Managed memory is controlled by garbage collection while unmanaged memory is outside of garbage collectors boundary.


So the first thing we need to ensure what is the type of memory leak is it managed leak or unmanaged leak. In order to detect if it’s a managed leak or unmanaged leak we need to measure two performance counters.
The first one is the private bytes counter for the application which we have already seen in the previous session.
The second counter which we need to add is ‘Bytes in all heaps’. So select ‘.NET CLR memory’ in the performance object, from the counter list select ‘Bytes in all heaps’ and the select the application which has the memory leak.


Private bytes are the total memory consumed by the application. Bytes in all heaps are the memory consumed by the managed code. So the equation becomes something as shown in the below figure.

Un Managed memory + Bytes in all helps = private bytes, so if we want to find out unmanaged memory we can always subtract the bytes in all heaps from the private bytes.
Now we will make two statements:-
  • If the private bytes increase and bytes in all heaps remain constant that means it’s an unmanaged memory leak.
  • If the bytes in all heaps increase linearly that means it’s a managed memory leak.
Below is a typical screenshot of unmanaged leak. You can see private bytes are increasing while bytes in heaps remain constant


Below is a typical screen shot of a managed leak. Bytes in all heaps are increasing.


How is the memory leak happening?

Now that we have answered what type of memory is leaking it’s time to see how is the memory leaking. In other words who is causing the memory leak ?.
So let’s inject an unmanaged memory leak by calling ‘Marshal.AllocHGlobal’ function. This function allocates unmanaged memory and thus injecting unmanaged memory leak in the application. This command is run within the timer number of times to cause huge unmanaged leak.
private void timerUnManaged_Tick(object sender, EventArgs e)
{
 Marshal.AllocHGlobal(7000);
}


It’s very difficult to inject a managed leak as GC ensures that the memory is reclaimed. In order to keep things simple we simulate a managed memory leak by creating lot of brush objects and adding them to a list which is a class level variable. It’s a simulation and not a managed leak. Once the application is closed this memory will be reclaimed.

private void timerManaged_Tick(object sender, EventArgs e)
 {
            for (int i = 0; i < 10000; i++)
            {
                Brush obj = new SolidBrush(Color.Blue);
                objBrushes.Add(obj);
            }
        }

In case you are interested to know how leaks can happen in managed memory you can refer to weak handler for more information
http://msdn.microsoft.com/en-us/library/aa970850.aspx .
The next step is to download ‘debugdiag’ tool from
http://www.microsoft.com/DOWNLOADS/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&displaylang=en
Start the debug diagnostic tool and select ‘Memory and handle leak’ and click next.


Select the process in which you want to detect memory leak.


Finally select ‘Activate the rule now’.


Now let the application run and ‘Debugdiag’ tool will run at the backend monitoring memory issues.


Once done click on start analysis and let the tool the analysis.


You should get a detail HTML report which shows how unmanaged memory was allocated. In our code we had allocated huge unmanaged memory using ‘AllochGlobal’ which is shown in the report below.


Managed memory leak of brushes are shown using ‘GdiPlus.dll’ in the below HTML report.



Where is the memory leak?

Once you know the source of memory leak is, it’s time to find out which logic is causing the memory leak. There is no automated tool to detect logic which caused memory leaks. You need to manually go in your code and take the pointers provided by ‘debugdiag’ to conclude in which places the issues are.
For instance from the report it’s clear that ‘AllocHGlobal’ is causing the unmanaged leak while one of the objects of GDI is causing the managed leak. Using these details we need to them go in the code to see where exactly the issue lies.

Source code

You can download the source code from the top of this article which can help you inject memory leak.

Thanks, Thanks and Thanks

It would be unfair on my part to say that the above article is completely my knowledge. Thanks for all the lovely people down who have written articles so that one day someone like me can be benefit.

Saturday, September 26, 2009

Best Practice No 4:- Improve bandwidth performance of ASP.NET sites using IIS compression

Introduction

Bandwidth performance is one of the critical requirements for every website. In
today’s time major cost of the website is not hard disk space but its bandwidth.
So transferring maximum amount of data over the available bandwidth becomes very
critical. In this article we will see how we can use IIS compression to increase
bandwidth performance.
Please feel free to download my free 500 question and answer videos which covers
Design Pattern, UML, Function Points, Enterprise Application Blocks,OOP'S, SDLC,
.NET, ASP.NET, SQL Server, WCF, WPF, WWF, SharePoint, LINQ, SilverLight, .NET
Best Practices @ these videos http://www.questpond.com/


Best Practice No 4:- Improve bandwidth performance of ASP.NET sites using IIS compression


How does IIS compression work?

Compression fundamentals: - Gzip and deflate

Enabling IIS compression
0, 1,2,3,4…10 IIS compression levels
3 point consideration for IIS compression optimization
Static data compression
Dynamic data compression

Compressed file and compression

CPU usage, dynamic compression and load testing

TTFB and Compression levels

IIS 7.0 and CPU roll off

Thanks, Thanks and Thanks

Conclusion

Some known issues on IIS compression

Links for further reading


How does IIS compression work?


Note :- All examples shown in this article is using IIS 6.0. The only reason we have used IIS 6 is because 7.0 is still not that common.

Before we move ahead and talk about how IIS compression works, let’s try to
understand how normally IIS will work. Let’s say the user requests for a
‘Home.html’ page which is 100 KB size. IIS serves this request by passing the
100 KB HTML page over the wire to the end user browser.


When compression is enabled on IIS the sequence of events changes as follows:-

• User requests for a page from the IIS server. While requesting for page the
browser also sends what kind of compression types it supports. Below is a simple
request sent to the browser which says its supports ‘gzip’ and ‘deflate’. We had
used fiddler (http://www.fiddler2.com/fiddler2/version.asp ) to get the request
data.



• Depending on the compression type support sent by the browser IIS compresses data and sends the same over the wire to the end browser.



• Browser then decompresses the data and displays the same on the browser.

Compression fundamentals: - Gzip and deflate

IIS supports to kind of compressions Gzip and deflate. Both are more or less same where Gzip is an extension over deflate. Deflate is a compression algorithm which combines LZ77 and Huffman coding. In case you are interested to read more about LZ77 and Huffman you can read at
http://www.zlib.net/feldspar.html .


Gzip is based on deflate algorithm with extra headers added to the deflate payload.


Below are the headers details which is added to the deflate payload data. It starts with a 10 byte header which has version number and time stamp followed by optional headers for file name. At the end it has the actual deflate compressed payload and 8 byte check sum to ensure data is
not lost in transmission.



Google, Yahoo and Amazon use gzip, so we can safely assume that it’s supported by most of the browsers.

Enabling IIS compression

Till now we have done enough of theory to understand IIS compression. Let’s get our hands dirty to see how we can actually enable IIS compression.

Step 1:- Enable compression
The first step is to enable compression on IIS. So right click on websites  properties and click on the service tab. To enable compression we need to check the below two text boxes from the service tab of IIS website properties. Below figure shows the location of both the checkboxes.


Step 2:- Enable metabase.xml edit
Metadata for IIS comes from ‘Metabase.xml’ which is located at “%windir%\system32\inetsrv\”. In order that compression works properly we need to make some changes to this XML file. In order to make changes to this XML file we need to direct IIS to gives us edit rights. So right click on your IIS server root  go to properties and check ‘enable direct metabase edit’ check box as
shown in the below figure.


Step 3:- Set the compression level and extension types
Next step is to set the compression levels and extension types. Compression level can be defined between 0 to 10, where 0 specifies a mild compression and 10 specifies the highest level of compression. This value is specified using ‘HcDynamicCompressionLevel’ property. There are two types of compression algorithms ‘deflate’ and ‘gzip’. This property needs to be specified in both the
algorithm as shown in the below figures.



We need to also specify which file types need to be compressed. ‘HcScriptFileExtensions’ help us to specify the same. For the current scenario we specified that we need to compress ASPX outputs before they are sent to the end browser.


Step 4:- Does it really work?
Once you are done with the above 4 steps, it’s time to see if the compression
really works. So we will create a simple C# asp.net page which will loop “10000”
times and send some kind of output to the browser.

protected void Page_Load(object sender, EventArgs e)
{
for (int i; i < 10000; i++)
{

Response.Write("Sending huge data" + "<br>");
}
}


In order to see the difference before compression and after compression we will run the fiddler tool as we run our
ASP.NET loop page. You can download fiddler from http://www.fiddler2.com/fiddler2/version.asp .
Below screen shows data captured by fiddler without compression and with compression. Without compression data is “80501 bytes” and with compression it comes to “629 bytes”. I am sure that’s a great performance increase from bandwidth point of view.




0, 1,2,3,4…10 IIS compression levels

In our previous section we have set ‘HcDynamicCompressionLevel’ to value ‘4’. More the compression level value, more the data size will be less. As we increase the compression level the downside is more CPU utilization. One of the big challenges is to figure out what is the optimum compression level. This depends on lot of things type of data, load etc.
In our further coming section we will try to derive which is the best compression level for different scenarios.


3 point consideration for IIS compression optimization

Many developers just enable IIS compression with below default values. But default values do not hold good for every environment. It depends on many other factors like what content type is your site serving. If you site has only static HTML pages then compression levels
will be different as compared to site who are serving mostly dynamic pages.


The above table is taken from

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/25d2170b-09c0-45fd-8da4-898cf9a7d568.mspx?mfr=true


If your site is only serving compressed data like ‘JPEG’ and ‘PDF’, it’s probably not advisable to enable compression at all as your CPU utilization increases considerably for small compression gains. On the other side we also need to balance compression with CPU utilization. The more we increase the
compression levels the more CPU resources will be utilized.

Different data types needs to be set to different IIS compression levels for optimization. In the further coming section we will take different data types, analyze the same with different compression levels and see how CPU utilization is affected. Below figure shows different data types with some examples of file types.


Static data compression

Let’s start with the easiest one static content type like HTML and HTM. If a user requests for static page from IIS who has compression enabled, IIS compresses the file and puts the same in ‘%windir%\IIS Temporary Compressed Files’ directory.
Below is a simple screen which shows the compressed folder snapshot. Compression
happens only for the first time. On subsequent calls for the same compressed
data is picked from the compressed files directory.


Below are some sample readings we have taken for HTML files of size range from 100 KB to 2048 KB. We have set the compression level to ‘0’.

You can easily see with the least compression level enabled the compression is almost 5 times.

As the compression happens only for the first time, we can happily set the compression level to ‘10’. The first time we will see a huge CPU utilization but on subsequent calls the CPU usage will be small
as compared to the compression gains.

Dynamic data compression

Dynamic data compression is bit different than static compression. Dynamic compression happens every time a page is requested. We need to balance between CPU utilization and compression levels.
In order find the optimized compression level, we did a small experiment as shown below. We took 5 files in a range of 100 KB to 2 MB. We then changed compression levels from 0 to 10 for every file size to check how much was the data was compressed. Below are compressed data readings in Bytes.


The above readings do not show anything specific, its bit messy. So what we did is plotted the below graph using the above data and we hit the sweet spot. You can see even after increasing the compression level from 4 to 10 the compressed size has no effect. We experimented this on 2 to 3 different environments and it always hit the value ‘4’ , the sweet spot.

So the conclusion we draw from this is, setting value ‘4’ compression level for dynamic data pages will be an optimized setting.



Compressed file and compression

Compressed files are file which are already compressed. For example files like JPEG and PDF are already compressed. So we did a small test by taking JPEG compressed files and below are our readings. The compressed files after applying IIS compression did not change much in size.


When we plot a graph you see that the compression benefits are very small. We may end up utilizing more CPU processor resource and gain nothing in terms of compression.

So the conclusion we can draw for compressed files is that we can disable compression for already compressed file types like JPEG and PDF.
CPU usage, dynamic compression and load testing
One of the important points to remember for dynamic data is to optimize between CPU utilization, compression levels and load on the server.

We used WCAT to do stress with 100 concurrent users. For every file size range from 100 KB to 2 MB we recorded CPU utilization for every compression level. We recorded processor time for W3WP exe using performance counter. To add this performance counter you can go to process à select processor time à select w3wp.exe from instances.

If we plot a graph using the above data we hit the sweet spot of 6. Till the IIS compression was 6 CPU utilization was not really affected.


TTFB and Compression levels

TTFB also termed as time to first byte gets the number of milliseconds that have passed before the first byte of the response was received. We also performed a small experiment on 1MB and 2 MB dynamic pages with different compression levels. We then measured the TTFB for every
combination of compression levels and file size. WCAT was used to measure TTFB.



When we plot the above data we get value ‘5’ as a sweet spot. Until the value reaches ‘5’ TTFB remain constant.


Print shot of WCAT output for TTFB measurement.


IIS 7.0 and CPU roll off

All the above experiments and conclusion are done on IIS 6.0. IIS 7.0 has a very important property i.e. CPU roll-off. CPU roll-off acts like cut off gateway so that CPU resources are not consumed
unlimitedly.

When CPU gets beyond a certain level, IIS will stop compressing pages, and when it drops below a different level, it will start up again. This is controlled using ‘staticCompressionEnableCpuUsage’ and ‘dynamicCompressionDisableCpuUsage’ attributes. It’s like a safety valve so that your CPU usage does not come by surprise.

Thanks, Thanks and Thanks

Every bit of inspiration for this article has come from Scott Forsyth's article on IIS compression. You can say I have just created a new version with more details.
http://weblogs.asp.net/owscott/archive/2009/02/22/iis-7-compression-good-bad-how-much.aspx


Thanks to Jimmie to suggest the performance counters and other details of IIS compression.
http://blogs.msdn.com/jimmiet/archive/2009/06/07/iis-6-0-compression.aspx


I also did picked up some bits from this link of Microsoft
http://technet.microsoft.com/hi-in/library/bb742379(en-us).aspx
.

Conclusion


• If the files are already compressed do not enable compression on those files.
We can safely disable compression on EXE , JPEG , PDF etc.

• For static pages compression level can be set to 10 as the compression happens
only once.

• Compression level range can be from ‘4’ to ‘6’ for dynamic pages depending on
the server environment and configuration.The best way to judge which compression
level suits best is to perform TTFB, CPU utilization and compression test as
explained in this article.

In case you want to do a sanity check please refer this article
http://weblogs.asp.net/owscott/archive/2009/02/22/iis-7-compression-good-bad-how-much.aspx

, i agree my results do not match exactly with scott but I think we are very much on the same page.


Some known issues on IIS compression


Below are some known issues of IIS compression
http://support.microsoft.com/kb/837251

http://support.microsoft.com/kb/823386



Links for further reading

http://www.zlib.net/feldspar.html

http://www.15seconds.com/Issue/020314.htm

http://blogs.msdn.com/jimmiet/archive/2009/06/07/iis-6-0-compression.aspx

http://www.fiddler2.com/fiddler2/version.asp

http://technet.microsoft.com/hi-in/library/bb742379(en-us).aspx

http://weblogs.asp.net/owscott/archive/2009/02/22/iis-7-compression-good-bad-how-much.aspx

http://www.codinghorror.com/blog/archives/000059.html

http://blogs.microsoft.co.il/blogs/yevgenif/archive/2009/02/08/web-performance-enable-data-compression-on-iis-6-0-server.aspx