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