Tuesday, June 4, 2013

Crystal Reports

This is actually a delayed post. Somehow it skipped me to post it earlier. Here goes the story and the details....

In early 2011 had to work on Crystal reports for 2-3 applications that we were converting from Excel to Web apps. 

Being afresh to Crystal reports, we wanted to learn the tool but did not have the time to go to a class room. Hence taking Google as our teacher we researched and learned the tool in a couple of weeks, while simultaneously working on a project.

Sharing our findings below(which i think are pretty neat) in case it is helpful to anyone else with a similar need and situation. 

There are links and videos, arranged in order, to give a newbie good jump start to using the tool.
         
Articles:
1.    Crystal reports articles

http://www.beansoftware.com/ASP.NET-Tutorials/Using-Crystal-Reports.aspx : Gives a good introduction to the tool (though not really convinced of PUSH and PULL model).


http://www.c-sharpcorner.com/articles/articlelisting.aspx?sectionid=1&subsectionid=61 : Good repository of various Crystal articles based on your situation e.g: How to pass parameters programmatically to Crystal reports; Crystal reports with Dynamic columns

http://www.c-sharpcorner.com/UploadFile/uditsingh/CR1111022006055359AM/CR11.aspx : Really NEAT on how the author uses Import pick list and simple formula fields to create dynamic columns on a Standard report


          Videos:
          http://www.youtube.com/watch?v=_CsgT4kVHPU:
         Use the design view in Crystal Reports by Business Objects at www.teachUcomp.com


          http://www.youtube.com/watch?feature=player_detailpage&v=_CsgT4kVHPU:    
          Crystal reports tutorial data


          http://www.youtube.com/watch?v=sX_BZfhlROI&feature=view_all&list=PL9A1A04C5CAEC695C&index=1 
         Crystal Reports XI Using the Section Expert (27 videos in sequel)

          http://www.youtube.com/watch?v=T-6Whh0jwHE&feature=view_all&list=PL9A1A04C5CAEC695C&index=2 
         Crystal Reports XI On-Demand Sub-reports (27 videos in sequel)

          http://www.youtube.com/watch?v=zLvModCDx9A&feature=view_all&list=PL9A1A04C5CAEC695C&index=6 
          Formula Field tutorial

          http://www.youtube.com/watch?v=jDhAUtbj4xM&feature=view_all&list=PL9A1A04C5CAEC695C&index=14 
          How to create a C# Asp.Net Crystal Report (Part 1)



Precaution:
2.    The link below gives you view of all the CR products, their  assemblies version and supported VS.Net.
It is interesting and an important chart, as the successive CR products do support similar to their predecessors e.g. Crystal 10.5 supports .Net 2008 while CR 11.5 does not.

To be on a safer side, You should ASSUME that Crystal Reports is NOT compatible with new versions of Visual Studio


3.    The 3 links below from a blog give a good idea of using Crystal reports in embedded format versus using them via Servers.
Using Crystal report engine in embedded state, restricts it to 3 simultaneous threads, with the 4th thread kept waiting. (though for certain vendors and OEMs the thread count is higher, as per comments by the author in response to questions)

Wednesday, April 18, 2012

Instagram - Value of Innovation

Many of you may have read or heard about Face book buying out Instagram for $1bn. Interesting deal!


I was reading some blogs on this and thought of consolidating and sharing some of the interesting insights to this deal.



What is Instagram:-


Simply put it is a mobile application which allows users to do some tricks on their photographs and share on Facebook, Twitter, etc. Another interesting fact is that it is an organization of only 12 developers.



Some basic financials:-


Facebook IPO is valued at $ 80bn. With a user base of 800mn, that means $100 per user.


Instagram has a user base of 33mn. So with a buyout of $1bn, it means that it is valued at $30 per user.



Questions:-


So why is Facebook paying $1bn for Instagram? Can’t Facebook develop the Instagram Application? Each of the 12 developers of Instagram would get approx $100mn; would they really be interested in working after that much money?



Answers:-


In all likelihood the 33mn users of Instagram are already part of Facebook. And Facebook definitely has the resources & power to build an application like or even much better than Instagram. But successful consumer product takes more than great technology.


The first product on the market has a big advantage; People get used to the product, invite friends and the growth cycle starts exponentially. And once the user community starts to grow exponentially they are not likely to switch to another product...even if it is better.


Technology can be replicated but not the timing and luck.


Mobile is the future and photos are core to Facebook. And Instagram is better than Facebook in both. And hence the deal is worth the price to Facebook.. though mathematically or numerically it may not make all that sense.


In a similar way, Google video did everything like hosting/sharing a video, but it could not really replicate YouTube. And eventually it had to buy YouTube for $1.6bn though technically it had everything in its Goggle Video.

Monday, July 4, 2011

CSS Sprites and the ASP.NET Sprite and Image Optimization Library

The following link points to an article of Scott Mitchell on using inline Images and CSS sprites to improve the download time of page.

http://dotnetslackers.com/articles/PrintArticle.aspx?ArticleId=612

The number of HTTP requests a browser makes to download a page can be reduced by usingf either of the two techniques: Inline images and CSS. But the primary challenge in using these techniques lies in creating the sprites and CSS rules.
The ASP.NET Sprite and Image Optimization library is a free, open-source library from Microsoft that simplies working with inline images and CSS sprites by automatically creating the sprites and CSS rules. This above article showed how to get started with the Sprite and Image Optimization library in WebForms and MVC applications.

Tuesday, June 7, 2011

Ways to define a JavaScript class

Following article gives a good overview of ways to define JavaScript class.

Though the author seems to have dthe point of effectiveness of using prototypes compared to other methods, the reponses by quite a few folks in the article drive home that point quite convincingly.
http://www.phpied.com/3-ways-to-define-a-javascript-class/

Overriding/Wrapping/Extending ActiveX and XMLHttpRequest object

Sometimes a special or a custom behaviour may be desired whenever an Ajax call is made from the Javascript code in the page.

In Internet Explorer 6 and earlier, XMLHTTP was implemented as an ActiveX object provided by Microsoft XML (MSXML). Beginning with Internet Explorer 7, XMLHTTP is also exposed as a native scripting object.

The native implementation of the XMLHTTP object is designed with cross-browser compatibility in mind. With just a bit of script, it is easy to build a function that works with either version of Internet Explorer, or any browser that supports XMLHTTP
Also it is more efficient to create a native scriptable object than to create an ActiveX object.

var xmlHttp = null;
if (window.XMLHttpRequest) {
// If IE7, Mozilla, Safari, and so on: Use native object.
xmlHttp = new XMLHttpRequest();
}
else
{
if (window.ActiveXObject) {
// ...otherwise, use the ActiveX control for IE5.x and IE6.
xmlHttp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
//Msxml2.XMLHTTP.6.0 ; Msxml2.XMLHTTP.3.0 ; Microsoft.XMLHTTP
}

Overriding ActiveX object: Following link gives the details of overriding Activex object:-
http://stackoverflow.mobi/question797960_Extending-an-ActiveXObject-in-javascript.aspx


The code first stores the instance of the actual ActiveXObject in a variable ActualActiveXObject.
Then the actual ActiveXObject's constructor is overridden with a custom constructor.
The custom constructor creates an instance of the Actual (or the overriden) Activex object.


If the arguement passed to constructor is not "msxml2.xmlhttp", then the instance of the actual Activex object is returned; Else, the rest of the code in the custom constructor is executed which creates a custom object O with certain variables and functions like Open(), Send, ReadyStateChanged(), etc. These custom functions contain user code and eventually call the respective function of the actual instance of the ActiveXObject.



Overriding XMLHttpRequest object: It is on almost similar lines to above code.
The following link and comments in it give details on overriding XMLHttpRequest object.
http://stackoverflow.com/questions/3596583/javascript-detect-an-ajax-event
http://blog.monstuff.com/archives/000252.html

MVC, MVP and MVVM

MVC, MVP and MVVM are patterns, or more specifically architectural patterns, which specify guidelines (or recommended practises) for defining layers within an application and their communication styles for effectively maintaining, scaling, testing, etc the application and its layers.

MVC - Defines 3 layers i.e. Model, View and Controller. Controller receives the UI events and accordingly guides the model and/or view to update themself. And in case the Model is updated from other sources too, it can notify the View(s) to refresh themselves via the observer pattern.
For more details, please refer the following MSDN link:-
http://msdn.microsoft.com/en-us/library/ff649643.aspx

MVP:- is a variant of MVC, with the primary difference that there is no interaction between View and Model. And the Presenter interacts with the View via an interface.
For more details, please refer to following article by Dino Esposito:-
http://msdn.microsoft.com/en-us/magazine/ff955232.aspx

MVVM: Model ,View and View Model is very similar to MVP pattern. Or it is some sort of specialized form of MVP pattern. Here Presentator is known as ViewModel.
Model communicates with ViewModel with notification and ViewModel communicates with View with data binding and command .
Following article gives idea of MVVM at high level:-
http://www.codeguru.com/cpp/cpp/cpp_managed/general/article.php/c18913


Also the following link, too gives decent links to various details about MVC and MVP (some video links too are referrred):-
http://social.msdn.microsoft.com/Forums/en-US/modelingandtools/thread/eecc7b01-cee0-4c20-9086-b1c4cafa6709

Saturday, February 12, 2011

Basic Instincts: Virtual Method; New; Override

Ever wondered how defining a function as virtual impacts its working at run time and how is it intervowen with the access modifiers NEW and OVERRIDE.

The following sample chapter from Vijay Mukhi will make things very clear. The chapter is in form of explanations of snippets of code, but it is very effective

http://www.vijaymukhi.com/documents/books/csbasics/chap9.htm

Essentially to summarize the chapter: Defining a function as virtual gives the power of deciding at run- time which method will be called based upon the assigned object i.e if you have a base class A which is inherited by class B and class C as shown below

Class A
{
public virtual One()
{......
......
}

public Two()
{......
......
}

public virtual Three()
{......
......
}
}


Let's assume that class B inheriting from Class A overrides methods One and Three. Now if an object of class B is assigned to a variable of type A; then on calling a.One() and a.Three(); the implementation of these methods in class B will be called.
Since Two() is not virtual, there is no question of overriding it in B and hence a.Two() will always results in calling the implementation of the method within class A.

Also if a virtual method is not overriden in inherited class; by default the access modifier NEW is assumed thus breaking the chain of the virtual method in inherited classes from thereonwards.

But even if the chain is broken, down the line a new chain can be established if any of the inheriting class down the line, defines the same method as virtual and other classes under it override the implementation of the method. But as specified this would be a new chain.

Sunday, February 6, 2011

Dependency Properties

Somewhat bewildered on my first encounter with this property, I started on a small journey to discover it and hence putting down my findings below for future reference as well as if it helps anyone.

Dependency Property Overview
Primarily to support the functionalities in WPF and Silverlight, designers at Microsoft invented something called as Dependency properties.

In regular .NET code, when you create a property, you typically back it by a private field in the containing class and by defining its getter and setter.
Dependency property is used very much like a normal property but differs significantly in the way it is implemented to support its additional features like
a. Setting via data binding, style, theme;
b. Change Notification;
c. ValidateValueCallBack: Callback to accept or reject new values and returns a Boolean
d. CoerceValueCallback: Can change new values into something more acceptable
The value of the property is determined using certain well-defined values precedence rules.(explained below)
Basic principle of the dependency property - it's an object oriented property i.e. and hence you need to define it within a class. But it can't be any class. It needs to inherit the methods needed to work with a dependency property and this means it has to inherit from DependencyObject or one of its descendants.
(C# only supports single inheritance, so it is important that you choose the correct class to inherit from if you also want properties and methods of a particular control.)
public class MyClass:DependencyObject
{
public static readonly DependencyProperty MyDPProperty =
DependencyProperty.Register("MyDP",typeof(double), typeof(MyClass));
}
And we can't just create an instance of DependencyProperty. The framework needs to know about it to allow it to take part in the common behaviors and hence the solution employed by its designers is to use a static method of Dependency property to create an instance and register it:
public static readonly DependencyProperty MyDPProperty =
DependencyProperty.Register("MyDP",typeof(double),typeof(MyClass));

The DependencyProperty object above is set up to store a value of type double, with name MyDP and to act as a property belonging to MyClass.

This is how all dependency properties are created and they have to be public static readonly fields. The reason is that the property belongs to the class and it’s the implementation that sorts out the instance being used. That is there is only one property object shared among all of the instances of the class that uses it.

There are a number of overloaded Register methods but at the very least you have to specify:-
• the name of the property as a string "MyDP" in the example
• the type of the property typeof(double) in the example
• the type of the class the property belongs to typeof(MyClass) in the example.

Two ways of referring to the property either by its name i.e. MyDP or by the variable MyDPProperty. You can also register a range of metadata values and callbacks but this is the minimum you need to create a custom dependency property.

Value precedence
Dependency properties obtain their value from a variety of inputs. What follows is the order the Silverlight property system uses when assigning the runtime values of dependency properties, with the highest precedence listed first:
a. Animations: If an animation is currently running, and that animation is changing the property value, Silverlight uses the animated value.
b. Local value: If you've explicitly set a value in XAML or in code, Silverlight uses the local value. If you set a property using a resource or data binding, it's considered to be a locally set value.
c. Styles: Silverlight styles allow you to configure multiple controls with one rule. If you've set a style that applies to this control, it comes into play now.
d. Property value inheritance: Silverlight uses property value inheritance with a small set of control properties, including Foreground, FontFamily, FontSize, FontStretch, FontStyle, and FontWeight. That means if you set these properties in a higher level container (like a Button or a ContentControl), they cascade down to the contained content elements (like the TextBlock that actually holds the text inside).
e. Default value: If no other property setter is at work, the dependency property gets its default value. The default value is set with the PropertyMetadata object when the dependency property is first created.

One of the advantages of this system is that it's very economical. For example, if the value of a property has not been set locally, Silverlight will retrieve its value from the template or a style. In this case, no additional memory is required to store the value. Another advantage is that different property providers may override one another, but they don't overwrite each other. For example, if you set a local value and then trigger an animation, the animation temporarily takes control.

References
Couple of resources where you can get decent information on the subject:
1. Pro WPF in Vb 2010: Chapter 4 Dependency Properties
2. http://www.i-programmer.info/programming/wpf-workings/443-inside-dependency-properties-.html - A useful link explaining the subject in a very easy manner (and much of what I have stated below is from this link)

Viewstate

Viewstate is probably one of the most used features of Asp.Net present since its inceptions i.e Asp.Net 1.0. But it is a widely misunderstood feature too. Most consultants whom I have to spoken to have a very jumbled up or mixed concept of ViewState, with most believing that disabling the ViewState will not show up the values typed in the controls by the user.

Therefore I am attempting to throw some light on this topic and for more details please refer to the references stated below.

Viewstate – What is it?
Viewstate represents the state of the page (or rather controls on the page) on the server before the generated output (i.e HTML and Javascript) is sent to the client. Viewstate is stored as a base 64 encoded hidden field on the page.
Also every control has a ViewState property. Surprised! Read the next para ViewState Internals.

Broadly speaking functions of the Viewstate are:
a. Maintain the values per control basis in the StateBag
b. Keep track of the values that have changed in the ViewState/StateBag(more on this dirtying business later)
c. Persist the dirty Viewstate values from each control into the hidden Viewstate form field
d. On postback load the Viewstate value sin to the viewstate/statebag of each control

Now a natural question that springs to the mind is – Well if you have the controls definitions defined in the .aspx file, why do we need to have this state of the controls persisted in a hidden field? Can’t it be build at the server side using the control definitions in the .aspx or .ascx files? Good question, if you thought about it.

Viewstate Internals
Let us try to understand what exactly is a view state. Every control ( as well as page) derives from the Control object which has a Viewstate property which is nothing but a Statebag collection, something like a dictionary object into which you can store data in key, value format.

Now every control uses this Viewstate to store its properties i.e. rather than defining the property in the control as instance variables like Int, String etc; instead every .net control stores its properties as a key-value pair in the Viewstate.

String _text;
Public string Text {
get { return _text;}
set { _text = value;}
}
I.E. instead of the above code, you will mostly find the following code in the control

Public string Text {
get { return (string)ViewState[“Text”];}
set { ViewState[“Text”] = value;}
}

Page Structure
It is important to also understand how does each page is represented in memory. Well, once compiled the page is represented in memory as a tree structure with the ASPC page itself as the root of that tree and all the controls declared at the top level in the ASPX page form the 2nd level of controls, basically 3 controls; a literal control representing all data till the form tag; the form control ; and again a literal control representing all data beneath the form control. Each control which is part of the form control is represented as a child of the form control. And any controls within the parent control are held as their children. In this way the entire page is represented as a tree structure.

ViewState tracking
Now when a page is requested by the client; it is first created on the server as a tree structure. Each control on the page is created as per its definition in the .aspx file and the properties of the controls are persisted in the Viewstate. When the OnInit() function is fired on the page, it fist recursively fires on each of the child control i.e. this method is executed in the BOTTOM UP manner beginning with the child controls and ending with the page. Immediately after the execution of this OnInit function on each control, TRACKING of view state for that control is set ON. What does this mean?

This is where viewstate/statebag differs from a plain dictionary/hashtable object. Once the tracking property of the ViewState is set; any further change to any of the values OR any additions to the StateBag are marked as dirty. Why?

So that at the time of persisting the ViewState on the HTML page as a base64 encoded property, only the key-value pairs (in each control’s viewstate) which are marked as dirty will be persisted Again we may wonder why?

Because properties of the control which can either be simply recreated from the control definition in the .aspx/.ascx file OR the property which is changed prior to OnInit event, can always be recreated from the definition and/or by the common code which runs during the execution of the page.

Now if any property or data of the control in Viewstate is changed after the Init event, it would be marked as dirty and hence would be persisted on the html page and send to client. When the ViewState is received back, in the LoadViewState event which occurs after the OnInit Event, the properties from the form’s ViewState field are applied back to appropriate control’s ViewState/StateBag collection.

So what does this mean? This means that the data applied to each control’s viewstate will be again marked as dirty, and will be persisted back to the page’s HTML in the next cycle.

Why do I need to understand these intricacies of ViewState?
For various reasons; Primarily it helps us to understand when to set or not set control’s property and when will it be persisted in the ViewState:
1. If we apply default value to a control’s property in the Load Event, the control will always show only the default value. And also setting the property in Load event will always mark it as dirty, since it occurs after the OnInit event ( rougly speaking the event cycle is PreInit; Init;InitComplete; LoadViewState; LoadPostBackData;Load,….,PreRender,Render)
Public Class TestControl: WebControl
{
protected override void OnLoad (EventArgs args)
{
if (!this.IsPostback)
this.Text = Session[“TestSessionKey”] as string;
base.OnLoad(args);
}
}

2. So if we wish to apply a default value, it should be done at the stage of property definition:
Public string Text
{
get
{
return this.ViewState[“Text”] == null ?
Session[“SomeSessionKey”] :
this. ViewState[“Text”] as string;
}
set { ViewState[“Text”] = value;}
}
OR
Declare a handler for the OnInit event on the control definition itself and put the intilization code in the control’s OnInit event.
OR
You can put initialization code in the PreInit Event but unlike Init; Load and PreRender, this is not recursive and is called only on the page.
OR
You can create a custom control by inheriting from any of the existing controls as its base control and then put the initializing code in the constructor of the custom control. 

3. For dynamically created controls, they can be added to their parent controls at any event till PreRender (though it is obviously not the best place to add dynamic controls).
So when is Tracking enabled for the ViewState of these controls? The tracking is obviously enabled after the Init event for the control is fired. And for dynamically created controls, ASP.NET plays a “catch-up” with the event sequence in that control ie. OnInit(); OnLoad(); etc (and any controls it may contain). And this catch-up of events starts as soon as the control is added to the control collections of the page’s tree structure.

Conclusion:-
I would like to end the discussion on ViewState with a question. Why do we need to persist or send the ViewState data onto the page? This ise xtra load on the network twice; once will sending to client and then receiving it on server. What if the ViewState was persisted in the session?
A user views only one page at a time and if we assume that at a given time there are about 100-200 active users and each page has on an average ViewState size of 1MB; then the additional load on the server will be only 100-200MB. Will it be better than persisting the ViewState on the page?
Couple of quick points; from version 2.0 even if viewstate is disabled some mandatory details required for the proper working of the control are kept in the ControlState property and presisted to client in the ViewState hidden field.
Also from release of .Net framework ver 4.0, ViewStateMode property is also introduced; using which the ViewState can be disabled for a page but enabled for certain controls in it.

References:
1. TRULY Understanding ViewState - Infinities Loop - http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx
2. ASP.NET Internals: Viewstate and Page Life Cycle - http://www.codeproject.com/KB/aspnet/aspnetviewstatepagecycle.aspx

DataGrid, DataList and Data Repeater

There is a lot of documentation on each of these controls. I thought of presenting a quick and concise summary explaining the differences between these 3 controls. Ofcourse there is detailed article on the subject by Scott Mitchel on MSDN.

Essentially all the three i.e. DataGrid, DataList and Repeater controls are used to represent repetitive data in a suitable manner to the users. Also data is bound to these controls in same manner simply by specifying the datasource (an IEnumerable one) and calling the DataBind() method on the control.

While DataGrid and Datalist inherit from WebControl; Repeater control inherits from Control class itself.

DataGrid represents data in a tabular manner with each datarow represented as a "tr" in a "table" and each column is represented as a "td" in a row. There is very little flexibility here except that the user can define what type of column to represent data i.e. button; link; label, etc.
But though the flexibility is low; a lot of out-of-box functionality is available via DataGrid i.e Sorting, Paging, Editing etc with little or practically no custom coding.

DataList too represents data inside a table but gives more flexibility than DataGrid. It can display more than one datarows inside a table row "tr"; it provides many more templates for defining your own custom HTML output; instead of table, data can be represented using a span tag.
But the freedom comes at a price. For sorting; paging as well as editing data rows, much more custom code needs to be written by the developers.

Repeater control gives the maximum flexibility, there is not default HTML output but there are numerous templates from header to almost every item that the developer can use to emit desired HTML. In one sense a complete freedom to define your own output but again at a cost of huge development time for any of the desired features.

So in summary use the control that gives you the functionality you desire but also keep in mind the performance. DataGrid makes heavy use of ViewState and hence performance is least compared to other two. While repeater makes practically no use of it and hence it’s performance is the best.

Google Map Controls for ASP.Net 2.0

I was going through articles by ScottGu and came across the following links to Google Map in ASP.Net. The first link is publicized by Scott himself and remaining links are from comments by various users on his site. I have not gone through these links but just publishing the repository in case I or someone else needs it in future.

http://dotnet.sys-con.com/read/171162.htm -
describes how to build and use an ASP.NET Server Control that makes Google Map integration easy within ASP.NET applications.

http://www.codeproject.com/aspnet/LatLaysFlat-Part1.asp
http://www.codeproject.com/aspnet/LatLaysFlat-Part2.asp
http://www.codeproject.com/aspnet/LatLaysFlat-Part3.asp
http://www.codeproject.com/aspnet/LatLaysFlat-Part4.asp
http://pietschsoft.com/product/ve3 - Open Source ASP.NET Virtual Earth mapping control
http://stephenjohnstone.com/blog/?p=24 - Open Source ASP.NET Virtual Earth mapping control

Preventing Hot-Linking or Leeching

There is a well known phenomenon called as hot-linking or leeching in which pages/content of a particular site refer to content like images, videos, etc from some other sites causing wasted bandwidth and increased server load on the victim site.

This can however be prevented using the REFERER header which the browser uses to specify the original URL from where the request were made. A component/code could check this header to see if the request was made from some other website or from own website or any approved partnering website. Requests from non-approved websites can be blocked by this code.

Assuming that we have a asp.net site in which we would like to prevent the leeching of the static content: How do we do this? Well the answer to tackle this issue is different for IIS5, IIS 6 and IIS7 web-servers.

IIS basically has in built capability to handle requests for static content like HTML; JPEG; etc. And for handling additional resource types like ASP and ASP.Net files, ISAPI extensions can be plugged-in to the IIS server. These ISAPI extensions are mapped to resource types like .asp, .aspx, .ascx and whenever request for these resource types comes to IIS, the handling is designated to the appropriate ISAPI extension dll.

If we have a .Net module which prevents leeching or hot-linking from our website, following are the tasks that we would need to do in the IIS servers based upon their versions.

IIS 5.0:- In IIS 5.0, if we wish to prevent hot-linking or leeching for the static content, we can register these static content types with the ASP.NET ISAPI extension. ASP.Net has the ability to serve certain static content but not all like CGI, ASP or other ISAPI extensions. Care must be taken to ensure that only the content types that can be served by ASP.Net is mapped to the asp.net ISAPI extension dll.

IIS 6.0:- This server allows creating a wild card mapping so that all requests are passed through ASP.NET extension and whichever ones cannot be handled by it, are passed back to IIS to handle either by itself or via any of the ISAPI extensions.

IIS 7.0:- With its integrated pipeline, this version of IIS offers the best service. You can register your .net module with IIS 7.0 and in the integrated mode all the requests will be passed through this module, before being handled either by IIS itself or any of the ISAPI extensions.

That’s it.

For more details on how to prevent leeching with screen shots, along with the source code as well as impact on performance if all request are routed through asp.net (i.e. in case of IIS 6.0), please refer to the following article by Mike Volodarsky, the program manager/Lead for the IIS development
http://mvolo.com/blogs/serverside/archive/2006/11/10/Stopping-hot_2D00_linking-with-IIS-and-ASP.NET.aspx

Thursday, September 23, 2010

Exception handling in .Net

Overview

In Win32 API as well as COM, whenever an exceptional condition occurred during the execution of code, there was no explicit notification send to the caller to notify about the problem. Instead it was left to the caller to check if the call made was successful or not e.g. most Win 32 API functions return FALSE to indicate that something is wrong and then the caller needs to call GetLastError to find the details of the problem. And similarly in COM, if the first bit of HRESULT is 1 then the remaining bits would give you details of the violation. Thus it is up to the caller to make explicit checks to find out any violations and if the caller forgets to do so, the state of the application could be in-deterministic down the line.

.Net has changed the scenario around this. If any assumption is violated in a method, it throws an appropriate Exception which needs to be caught either in the calling method OR somewhere in the call stack. Else if there is no handler for the Exception, the CLR terminates the application rather than leaving it as it is with unpredictable results down the line.

Define Exception

How do you define Exception? Most common answer would be that Exception is an error or response to an error. That means if we are calling a method and the method throws an Exception, something went wrong in the execution of the method. To exemplify, let us say we have a method

Public Int Divide (int a, int b)
{
Return a/b;
}

Now if the caller of this method passed the value Zero or Null for b, the method would throw a DividebyZeroException (). Is this error due to some execution fault by the method OR incorrect value passed to it. Likewise CLR too throws some Exceptions like OutofMemoryException; StackOverflowException; etc which are not due to errors in code.

Now how would you define Exception? I found a definition by Jeffrey Richter to be very appealing. "Exception is defined as non conformance to an assumption implied by the programmatic interface". In above method, Divide(), it was assuming b to be non-zero and non-null and when the caller violated that assumption, the appropriate exception was thrown back to the caller.

Exception handling in .Net

Exception handling in .Net is done via try...catch and finally blocks of code i.e. place the code that you expect or anticipate an exception in Try block and Catch those Exceptions in Catch block for the necessary action you may wish to take on those exceptions.

Finally block contains code (mostly some sort of clean up code) that is executed irrespective whether the Exception occurs in try block or no.

Public Void SomeMethod()
{

FileStream fs = null;

try {

fs = new FileStream(pathname, FileMode.Open)

……

}

catch (FileLoadException fle) {

//put the code here to handle FileLoadException or any exception derived from FileLoadException

}

catch (FileNotFoundException fnfe) {

//put the code here to handle FileNotFoundException or any exception derived from FileNotFoundException

}

catch (IOException ioe) {

//put the code here to handle IOException or any exception derived from IOException

}

catch (Exception e) {

//put the code here to handle any CLS compliant Exception.

}

catch {

//put the code here to handle any Exception, whether CLS compliant or not.

}

finally () {….

…..

}

}

The above shows a method which has a try block followed by few Catch blocks and one Finally block. Any Exception that originates in the Try block will be matched with the Catch blocks for the matching Exception or any of derivatives of the stated Exception. If not found, it goes to the next catch block and so on. After all the catch blocks are compared, if none caters to the Exception thrown then the Exception is passed to the next method up the call stack and the same procedure is repeated.

If any of the Catch blocks of the methods in the call stack can handle the thrown Exception, then all the Finally blocks from where the Exception was thrown up till the matching Catch block are executed and then the code in the matching Catch block filter is executed. Then the code in Finally block corresponding to the Catch block which handled the Exception is caught, is executed.

If the code in the Catch block does not throw/rethrow the exception and also no exception occurs in the code in the Finally block, the execution will fall to the code immediately after Finally block (or after Catch block, if there is no Finally block). Also if exception is thrown while executing code in Final block, it is treated as if thrown at end of the final block.

The last catch block does not specify any exception. It is meant for catching any exception, not catered by any of the catch blocks above it, not even catch(Exception e) block– which catches any CLS compliant exception. Generally this catch block is meant for catching any non-cls compliant exception, though there is no way of knowing what the exception was.

To know how exception handling impacts performance of the code, you can use PerfMon.exe or System Monitor ActiveX control that comes with Windows NT 4, Windows 2000, Windows XP, and the Windows .NET Server product family. Various exception related counters get installed when .Net Framework is installed.

Hierarchy of Catch Blocks

Catch blocks with specific exceptions need to be first, followed by the catch blocks with the generic exceptions. The reason for this is because if the catch block catch(Exception E) is the first one, then since every exception is derived from Exception class, this block would be the only one to catch all CLS compliant exceptions and none of the catch blocks below it would be ever executed.

Should all methods have Exception Handling?

Unfortunately it is a common practice to have catch blocks at end of most, if not all, methods.
Not only is this detrimental to performance but is also grossly incorrect and conceives the truth .

Exception handling should be put only in places where:

1. The exception can be handled by the code and efforts can be made to work around the
exception.

2. The exception needs to be wrapped into a more meaningful one and then re-thrown.
Example would be if a type provides facility of finding Phone Numbers to its users. Now if
the Phone numbers are being maintained in Files and if there is a FileException, it would
not be prudent to throw the file exception back to the user, as it may not make sense to
them. Better would be to wrap these exceptions in a more meaningful custom exception
and then re-throw it.

3. If a message is to be displayed to the user on occurrence of the Exception.

Just catching an Exception without any purpose and swallowing it would not only hurt the performance but also leave the application in an unpredictable state, as some assumption/condition failed and nothing has been done about it.

Also note that not all exceptions can be handled by the application. If the CLR finds that it is OutofMemory for its internal purpose, it will display a message on Console and just terminate the application. None of the handlers will be called. Similarly if the StackOverflowException occurs in the internals of CLR, this exception will not be caught by code and none of the Finally blocks will be executed, and the process would be killed. But if the StackOverflowException occurs in the code of the application, this exception can be caught by the application but the code in the Finally blocks will not execute as there is no space to execute the Finally block on the Stack.

StackTrace in Exceptions

The Exception class from which all exception classes inherit has a public read-only property called StackTrace. Accessing this property actually access code in CLR; the property doesn’t simply return a string. If you create a Custom Exception derived from Exception and try to access this property, you will get NULL. When an Exception is thrown CLR records the point where the exception was thrown. When a catch filter accepts the thrown Exception, CLR records where the exception was caught. And now inside the catch filter if exception’s StackTrace property is accessed, the code implementing this property calls into the CLR which using the recorded start and end points of the thrown exception builds a string listing all the methods between the place where the exception was thrown to the place where it was caught.

If an exception is thrown i.e.throw e, the exceptions StackTrace is reset But if the exception is re –thrown i.e. throw e; the StackTrace property is not reset.

The StackTrace property only includes Method Names till the point where the exception is caught by the catch filter; none of the above methods in the call stack from the point where the exception is caught are included in the StackTrace property. To include the methods from the call stack above the catch point, use System.Environment.StackTrace() (static method) and merge the two strings.

Sometimes not all the methods of the call stack appear in the StackTrace property. This is because the JIT compiler may optimize and inline some of the methods to avoid the overhead of calling and returning from a separate method. Many compilers offer a /debug command line switch, which when turned ON makes the compiler embed information in the assembly that tell the JIT compilers not to inline the method so that the stack trace are more complete and useful to the developer debugging the application.

Applying the attribute System.Runtime.CompilerServices.MethodImplAttribute on top of the method forbids the JIT complier from in lining the method for both debug and release builds.

Exception Hierarchy and Custom Exceptions

All CLR compliant exceptions inherit from the class Exceptions. Initially Microsoft was advocating the strategy that all System Exceptions would inherit from the class System.Exception while all application Exception should inherit from ApplicationException. And both these exceptions would inherit from the base class Exception.
But in the course of building the FCL (Framework Class Library) Microsoft violated their own strategy, some reflection-related exception types are derived from ApplicationException instead of SystemException.

Checking against SystemException or ApplicationException may not be very practical. At the same time checking for individual exceptions too may be impractical. This where the Exception hierarchy kicks in and may be more useful. For e.g. ArgumentNullException; ArgumentOutOfRangeException; DuplicateWaitObjectException; all these inherit from ArguementException.

Checking against the ArguementException rather than each of the derived exceptions may be more helpful.

To define a custom Exception you would either need to inherit from Exception base class OR take any of the existing exception classes in the hierarchy and derive the custom exception from it. Whether to choose Exception class or one of the existing classes as base, depends entirely upon the policy and decisions of the Exception design of the application. If you derive a new Exception from ArguementException, then all the places in the code where ArguementException is being caught may need to consider handling this new exception type, unless you have thought and designed/coded with this consideration.

Exception class has 3 constructors, Blank; Accepting a string (which sets a descriptor) ; Accepting a string and an inner exception. In cases where the thrown exception is wrapped by a new or custom exception, the inner exception of this new exception class is set to the original thrown exception.

A custom exception can have its own data fields too besides the one provided by Exception class. But the caveat to watch here is that in case the Exception needs to be Serialized, serialization code for such additional fields in the custom exception classes needs to be coded. To provide serialize facilities to such custom exceptions class, annotate the class with Serialize attribute and also inherit the class from ISerialize interface and implement the methods for Serialization and Deserialization().

Unhandled Exceptions (AppDomain)

Exceptions which are not handled by the method propagate all the way up. These exceptions may be CLS compliant i.e. derived from Exception class or may be non-CLS compliant. These exceptions can be handled by attaching an event to AppDomain as shown below

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionCallbackMethod);

This callback receives a System.UnhandledExceptionEventArgs object which has two public read-only properties: ExceptionObject (System.Object) and IsTerminating (type System.Boolean). Check Exception.IsTerminating to know whether CLR is going to kill the Appdomain.

Normally, for manual threads, pool threads, and the finalizer thread, the CLR swallows any unhandled exceptions and either kills the thread, returns the thread to the pool, or moves on to call the Finalize method of the next object. If an unhandled exception occurs in any of these kinds of threads, the IsTerminating property will be false.

But if an application’s main thread or an unmanaged thread has an unhandled exception, IsTerminating will be true.

There is also Registry Entry whose value influences the handling of these Unhandled Exceptions. The registry entry is
HKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\ DbgJITDebugLaunchSetting.

Value 0: Displays a dialog box asking the user whether he would like to debug the process.

Value 1: No dialog box is displayed to the user and CLR fires the AppDomain’s UnhandledException event.

Value 2: No dialog box is displayed to the user and AppDomain’s UnhandledException event doesn’t fire. The CLR just spawns the debugger attaching it to the application.

Unhandled Exception (Winforms)

To handle unhandled exceptions in Winforms define a method that matches the System.Threading.ThreadExceptionEventHandler delegate and register it with the Application type’s static ThreadException event.

Windows Forms deals only with CLS-compliant exceptions; non-CLS-compliant exceptions continue to propagate outside the thread’s message loop and up the call stack. To display or log both CLS-compliant and non-CLS-compliant exceptions, define two callback methods and register one with the Application type’s ThreadException event and register the other with AppDomain type’s UnhandledException event.

Unhandled Exceptions (ASP.Net)

Unhandled exception in ASP.Net can be handled for a particular Web page or for all Webpages.

To register a callback method that will receive notifications for unhandled exceptions for each WebPage, register the callback method using the Error event offered by the System.Web.UI.TemplateControl class; this class is the base class of the System.Web.UI.Page and System.Web.UI.UserControl classes.

To register a callback method that will receive notifications of unhandled exceptions on any page, register the application-wide callback method using the Error event offered by the System.Web.HTTPApplication class in the Global.asax file.

Unhandled Exceptions (WebServices)

ASP.NET catches the exception and throws a new SoapException object (System.Web.Services.Protocols). A SoapException object is serialized into XML, representing a SOAP fault. This SOAP fault XML can be parsed and understood by any machine acting as an XML Web service client. This allows for XML Web service client/server interoperability.

Tuesday, September 21, 2010

Automatic Memory Management - Garbage Collection


Overview:

Memory management is essentially a topic that requires objects to be clean/cleared when their usage is complete. And obviously freed memory should not be referred.

But this seemingly simple task has been the major source of programming errors. Programmers either forget to free memory when it is no longer needed OR use memory that has already been freed up. Numerous tools have been designed to help programmers deal with these kinds of issues. All of this though helpful but still require additional efforts to solve these issues rather than focusing on the real problem. This is where Garbage Collection comes into play: It totally abstracts the programmers from worrying about freeing memory.

Application programmers create object/types and use them in their programs. And when the object/type goes out of scope, that is, it is not reachable by the application; it will automatically be collected and recycled by Garbage Collector, at the appropriate time.

So why is there no Garbage Collector for C++?

Because in C++ object pointer can be type caste to any other object, hence making it impossible to determine what is the object that the object pointer is pointing to. If the object that the object pointer is pointing to cannot be determined, how can garbage collection be done in C++ environment!

Working of Garbage Collector:

CLR (Common Language Runtime) mandates that resources be allocated from a heap, called managed heap. (Primitive types like int, string, etc are allocated on stack and not heap). The managed heap maintains a distinct pointer called NextPtr, from where the next object is allocated. And then the Nextptr is advanced by the number of bytes of the newly allocated object. This mechanism ensures that consecutive objects are contiguous in memory, which gives performance gains due to locality of reference.

In C, to allocate a resource/object, a linked list would needed to be traversed to find an appropriate memory chunk and allocate it and make the necessary changes in the linked list. Not only this required additional time but there was no guarantee that consecutive objects would be continuous in memory.

Thus managed heap is superior to C-runtime heap, in ways described above.

But, managed heap would need to reclaim memory as it cannot just keep on allocating memory infinitely. In order to reclaim memory, garbage collector needs to keep tracks of all resources/objects on heap that are not reachable i.e. It is no longer being used by the application and then reclaim the memory for these objects. Keeping track of the reach ability of the objects is done via a mechanism called roots, where the JIT compiler maintains besides each method offset the list of objects associated with it. Thus with the help of these method roots as well as global variables, GC can walk through the stack trace and find out the list of all reachable objects.

For the Garbage Collector (GC) to start there needs to be some kind of a threshold to start it. Let’s say at a particular point, the allocated memory on the managed heap reaches a threshold and starts the GC. The GC will look at the objects in the Heap (not all objects but based upon generations, which we will talk later) and identifies the objects that are not being used by the application. (it determines this by looking at the roots for all the methods on the stack trace to find out which objects are being used and which are not). Then the objects that are not being used are garbage collected i.e. their memory is reclaimed and if there is a need to compress the Heap, a decision that GC takes based on fragmentation of memory, it compresses the heap by removing unreachable objects and shifting the addresses of the other objects to make the heap continuous, as shown below. If the objects are moved, the GC obviously corrects all the references to the object, to point correctly.

Generations

If Garbage collector has to scan the entire heap i.e. all the allocated objects in heap, it would be very time consuming and inefficient too. Hence the garbage collector works on the assumption that newly allocated objects have shorter lifetime compared to older objects on heap. Numerous studies have been done to validate this assumption.

When an application starts, it is allocated a managed heap. Objects are allocated memory on this heap by the application tread(s). Up till now all the objects on the heap are termed as Generation 0. If the memory threshold defined for Generation 0 triggers in (which may when the Generation 0 reaches the size of 512KB), the GC will start scanning the objects in the managed heap to check if they are reachable by the application. All the objects that are reachable will be left as they are, and those that are not reachable will be takenoff/ cleaned up from managed heap by GC. If any compression needs to be done, the GC takes the call and moves the object in the heap so that they are continuous and the NextPtr points after all the object in heap. GC takes care to reset the object references wherever required, if the objects have been moved in the Heap.

Now the objects which were not garbage collected become Generation 1. And henceforth all the objects that would be allocated memory on heap, form a part of Generation 0, which will be blank currently. Again if the threshold on Generation 0 is reached, the GC will kick in to do the cleaning activity for the managed Heap.

What about objects in Generation 1? Well, there is a threshold for Generation 1 too, i.e. let us say that when Generation 1 reaches the size of 1 MB which may the defined Threshold limit for it, the GC will kick off looking into Generation 1 to find non-reachable objects. And the objects which survive Generation 1, will be promoted up to Generation 2 and likewise surviving objects from Generation 0, will form part of Generation1.

That is the generation theory of GC, where objects from Generation 0, i.e. newer objects are always scanned first for garbage collection, and then generation 1 and at last generation 2 is scanned. There is no further generation than generation 2.

Generations and Thread Hijacking and Suspension

Before GC can run for collecting memory, it will need to suspend all the existing threads running managed code till the GC completes its activities and resets any object pointers if required due to the movement of objects. After GC completes its activities, the threads resume their activities from the point onwards where they were suspended. But GC does not just suspend a thread just like that. It checks whether the Inst Ptr of the thread is at the offset address of the method specified in the method table produced when the IL code is JIT compiled. If yes, the thread can be easily suspended as it is at a safe point.

If not, the thread is hijacked and the return address points to a function implemented inside the CLR. The thread is then resumed with the hope that when the currently executing method returns, it will execute the special function inside CLR and thus suspend the thread. But the thread may not return for quite some time. The CLR waits for 250 milliseconds and if the method does not finish (and enter into the special method implemented inside CLR), the thread is suspended again and hijacked i.e. the stack is modified so that the current method’s return address is into the special method inside CLR for suspending the thread. The thread again resumes till it enters into the CLR method for suspension OR 250 milliseconds expire. The process continues till all threads are suspended and then the GC kicks in.


Multiprocessor

In a multiprocessor environment, the managed heap is partitioned into multiple memory arenas, one for each thread so that exclusive access to single managed heap is not required by various threads. The server version of the execution engine (MSCorSvr.dll), in the multiprocessor environment, initiates the garbage collection per thread per CPU thus allowing parallel garbage collection for each memory arena.

Concurrent collections

In a multiprocessor environment, a concurrent garbage collector thread can be initiated, of normal priority, which works in the background while the application thread runs, and it builds a graph of unreachable objects. Thus when the garbage collection actually takes place, since the graph of unreachable objects is already build, the GC process takes less time. For more interactive GUI applications, concurrent collection may be a good option.

Concurrent option needs to be turned ON in the configuration file via the attribute

Large Objects

Objects larger than 85,000 bytes are allocated in special part of the managed heap and are treated as Generation 2, simply because these objects are heavy and taking them off and compacting 85,000 bytes from the heap each time these objects are garbage collected will waste too much time. So in case these heavy objects are short lived and used frequently, these may cause generation 2 to be collected more frequently and this hurt the performance.

In case your application does have large objects that are collected frequently, try and see if they can be broken or composed of smaller objects such that only few of them need to be collected frequently OR try and circumvent the situation of having to collect these large objects frequently.

Finalize and Dispose

Most of the object types manipulate bytes in memory and hence their memory is reclaimed when they are garbage collected by the garbage collector. So why do we need a finalize method on object types and what does it do?

Finalize method is called when the object is actually garbage collected by the garbage collector. This is required when the memory of the type cannot be reclaimed by the garbage collector itself i.e. when the object/type uses an unmanaged resource like Filehandle, Mutex Kernel object, etc. for such types, the Finalize method is required to execute code to free the unmanaged resources which cannot be claimed by the GC.

The usual and the good practice is to encapsulate these unmanaged resources within a managed object type, for e.g.: the FileStream type encapsulates the windows FileHandle and exposes methods to do various operations on the unmanaged resource like Create, Read, Write, etc. When object of FileStream type becomes unreachable by the application, it is garbage collected and the finalize method on it is automatically called by the GC. The code in the finalize method then does the needful to release the unmanaged resource.

When exactly is the finalization method called is not deterministic, as it based upon when GC kicks in. So if we need to release the unmanaged resource deterministically, we can do so by implementing the Dispose pattern/interface. The dispose method is a public method. It first suppresses the calling of Finalize method by GC and then it calls a Boolean Dispose method, which is protected and virtual. This method synchronizes thread access by placing all code inside the code construct Lock() {…} and it releases/closes the unmanaged resource.

The Boolean Dispose method is called from the Dispose method as well as from Finalize method with the Boolean value indicating whether it is called from Dispose method OR Finalization method. Why? Because if the Boolean Dispose method is called from Finalize(), it is not advisable to access any other managed object. (there is no order in which the Finalize methods are called by GC i.e. an inner/contained object’s Finalize method may be called earlier than the containing object).

When the Boolean Dispose method is called from the Dispose method, it is free to call any managed object, and this indicated by passing true. Code below will clarify more.

----------------------------------------------------------------------

Public Void Dispose()

{

….

GC.SupressFinalize(this);

Dispose(true);

}

----------------------------------------------------------------------

Protected Virtual Void Dispose (Boolean Disposing)

{

Lock (this)

{

If (Disposing)

{…. Can Access other Objects….

}

If (Handle Valid)

{ Close(Handle)

Handle = Invalid

}

}

}

----------------------------------------------------------------------

Finalize TypeName()

{

Dispose(true);

}

----------------------------------------------------------------------

If a new type derives from this type which implements the dispose pattern, all it would need to do is override the Boolean Dispose method and provide it’s own implementation of clean up activity and ultimately call the base class’s Boolean Dispose method. And if this new derived type does not need to do any clean up, it need not override the Boolean Dispose method.

Finalization method and GC

For a type that implements Finalization, as soon as it is allocated in heap, GC marks that this type has a finalization method and stores a reference to such objects. When this object becomes unreachable, GC takes this object and places a reference to it in the FreeReachable Queue. At this point there is a reference to this object and technically it cannot be garbage collected. CLR spawns separate threads, other than the application threads, to run the finalize methods of these objects in FreeReachable Queue. And as the Finalize method is RUN, the entry for that object is taken off from the queue making it completely unreachable and can be garbage collected by the GC in its next run. (Please mark that the order in which the Finalize methods of the objects would run is not deterministic and hence any use of managed objects within the Finalize methods could led the application to in-deterministic state).

Thus an object having a Finalize method requires two GC turns for it to be garbage collected. Hence unless the type is using an unmanaged resource, it is strongly recommended not to use Finalize method.

Also a dispose method allows the clean up to happen before the Finalize method is called. This means that the type will not be used anymore down the line; something which is impossible to enforce. Hence it is advisable not to implement the Dispose interface, as when the type is unreachable GC will automatically call the Finalize method and the desired clean up would be done. But if the Dispose interface needs to be implemented for some reason, then before using the TYPE it should be checked whether the object of the TYPE is still Alive or has it been Cleaned up.

Weak-References

In cases when large objects are allocated but used sparingly, then instead of holding a strong reference to the object, a weak reference to the object can he held. A weak reference allows the object to be garbage collected, if there is a need for memory. Else the weak references are kept intact and the code, if required, can use the object in weak reference.

The code below demonstrates how to hold a weak reference. But please bear in mind that for weak reference to work, there should be no strong reference to that object anywhere in the stack trace. Else the weak reference would not work

WeakReference wkRef;

Protected Void WeakReference()

{

StrongRefObject StrngObj = new StrongRefObject();

wkRef = new WeakReference(StrngObj);

StrngObj = null; // Remove strong reference to the object

}

Protected Void RestoreStrongReference()

{

StrongRefObject StrngObj = wkref.Target;

If (StrngObj == null)

/// the object has been garbage collected

Else

/// the object has not been garbage collected and can be used

}

Resurrection and Object Pooling

Resurrection means bring back to life. When an object’s Finalize method is run, it means that the object is dead, there are no references to it and its memory will be reclaimed in the next cycle of GC. But what if the object in it’s Finalize method hooks itself to some global static variable. In that case, the object cannot be garbage collected as it is being referenced by the application. That means it is back to life, resurrection. And also you could register with GC to run the Finalize method for this object, if it is garbage collected again with the help of following code: GC.ReRegisterForFinalize(this);

When would you want to implement Resurrection?

Object Pooling. If there is a class of object that you would like to POOL, you could use Resurrection. First, create a pool of that object type. Then when an object from the pool is allocated, it’s reference from the pool structure holding the object collection is removed. When the object’s Finalize method runs, it cleans the object and reattaches itself to the pool structure and also re-register’s, its Finalize method with GC. Thus the object is cleaned and available for

Programmatic Control of Garbage Collector

You can force garbage collection by calling out any of the 2 static methods; though it is best to the let the GC run on its own accord as it also fine-tunes the generation threshold value/trigger based on the application behavior.

GC.Collect();

GC.Collect(Int32 GenenerationNumbertoCollectFrom); // Generation 2 will cause Gen 1 and Gen 0 to be collected too.

GC.WaitForPendingFinalizers(); //This method suspends the calling thread, till the FreeReachable queue is empty.

Int32 GetGeneration(Object obj);// Gives you which generation the object is currently in.

Monitor Garbage Collection

.Net Framework installs a number of performance counters that gives real time statistics about the CLR’s operations. These statistics can be viewed via the PerfMon.exe. Various GC related counters can be viewed and monitored.

Conclusion

The above should provide some insight into memory management and garbage collection in .Net. It also gives pointers on using Finalize and Dispose methods and their impact on performance; also where are Large objects allocated in heap and their impact on performance; and finally multiprocessor and their use by GC and how can concurrent collection be done in multiprocessor environment.

References

1. Applied Microsoft .Net Framework Programming – Jeffrey Ritcher; this is by far the best resource that I have come across on this subject.

2. CLR via C#, 2nd Edition – Jeffrey Ritcher. (I have not read this book but still including it because i have every reason to believe it must be a good read and add a lot of value on this topic in more detail).