Tuesday, April 28, 2009

4 Liquid Stages of Life


The bitter truth...

Friday, April 24, 2009

ClientID feature of ASP.NET 4.0

One of the new features being added to ASP.NET 4.0 is the ability to control the client side IDs that are generated by the framework. Previously the framework use to generate unique ClientID's for the controls. These ClientID's were generated by combining "ctl00" with the parent container's name like "ctl00_ContainerDIV_ctl01_Textbox1".


The Problem
In the earlier versions of .NET framework, the ClientID's were generated uniquely by the framework. It was much frustratingto use these ClientID's in the JavaScript of asp.net web page. If by some mean the develop hard codes the ClientID in the JavaScript and another developer changes the Controls ID, then the JavaScript use to throw error, since it does not recognize the old ClientID which was hard coded. To avoid such scenarios, developers started using server tags for Control.ClientID in JavaScript as shown in the below section.


Old Solution
Each control has a property called ClientID that is a read only and supplies the unique client side ID. This can be used in code behind for dynamically adding client side ID's to scripts. One such example is shown below:

<script type="text/javascript">
function ShowMessage(){
alert('<%= Control.ClientID %>');
}
</script>

ASP.NET 4.0 Solution
There is not really a clean way to use the ClientID property with lots of controls and lots of external script files. With the increase in use of client side scripting and ajax, it became important to make the ClientID property writable. The solution to this problem was found by introducing ClientIDMode property to each control. Depending on various modes the developer will have full control over the client side Id's of a control.

Client ID Modes
There is now a new property on every control (this includes pages and master pages as they inherit from control) called ClientIDMode that is used to select the behavior of the client side ID.

<asp:Label ID="Label1" runat="server" ClientIDMode="[Mode Type]" />

Mode Types
Legacy: The default value if ClientIDMode is not set anywhere in the control hierarchy. This causes client side IDs to behave the way they did in version 2.0,3.0 and 3.5 of the framework. This mode will generate an ID similar to "ctl00_ContainerDIV_ctl01_Textbox1."

markup:

<asp :TextBox ID ="txtEcho" runat ="server" Width ="65%" ClientIDMode ="Legacy" />

output:

<input id="ctl00_MasterPageBody_ctl00_txtEcho" style="width: 65%"
name="ctl00$MasterPageBody$ctl00$txtEcho" />

Inherit: This is the default behavior for every control. This looks to the controls parent to get its value for ClientIDMode. You do not need to set this on every control as it is the default, this is used only when the ClientIDMode has been changed and the new desired behavior is to inherit from the controls parent.

Static: This mode does exactly what you think it would, it makes the client side ID static. Meaning that what you put for the ID is what will be used for the client side ID.
[Warning, this means that if a static ClientIDMode is used in a repeating control the developer is responsible for ensuring client side ID uniqueness.]

markup:

<asp:TextBox ID="txtEcho2" runat="server" Width="65%" ClientIDMode="Static" />

output:

<input id="txtEcho2" style="width: 65%" name="ctl00$MasterPageBody$ctl00$txtEcho2" />

Predictable: This mode is used when the framework needs to ensure uniqueness but it needs to be done so in a predictable way.The most common use for this mode is on databound controls. The framework will traverse the control hierarchy prefixing the supplied ID with it’s parent control ID until it reaches a control in the hierarchy whose ClientIDMode is defined as static. In the event that the control is placed inside a databound control a suffix with a value that identifies that instance will also be added to the supplied ID. The ClientIDRowSuffix property is used to control the value that will be used as a suffix. This mode will generate an ID similar to "Gridview1_Label1_0".

1. With no ClientIDRowSuffix defined, this is also the behavior for databound controls without a datakeys collection e.g. Repeater Control. Notice that the framework has traversed the control hierarchy and prefixed the ID with the parent’s ID and suffixed the ID with row index.

markup:

<asp:GridView ID="EmployeesNoSuffix" runat="server" AutoGenerateColumns="false"
ClientIDMode="Predictable" >
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="EmployeeID" runat="server" Text='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="EmployeeName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

output:

<table id="EmployeesNoSuffix" style="border-collapse: collapse" cellspacing="0" rules="all" border="1">
<tbody>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
</tr>
<tr>
<td><span id="EmployeesNoSuffix_EmployeeID_0">1</span></td>
<td><span id="EmployeesNoSuffix_EmployeeName_0">EmployeeName1</span></td>
</tr>
...
<tr>
<td><span id="EmployeesNoSuffix_EmployeeID_8">9</span></td>
<td><span id="EmployeesNoSuffix_EmployeeName_8">EmployeeName9</span></td>
</tr>
</tbody>
</table>

2. With a ClientIDRowSuffix defined, this looks in the control’s datakeys collection for the value and then suffixes the ID with that value.

markup:

<asp:GridView ID="EmployeesSuffix" runat="server" AutoGenerateColumns="false"
ClientIDMode="Predictable" ClientIDRowSuffix="ID" >
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="EmployeeID" runat="server" Text='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="EmployeeName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

output:

<table id="EmployeesSuffix" style="border-collapse: collapse" cellspacing="0" rules="all" border="1">
<tbody>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
</tr>
<tr>
<td><span id="EmployeesSuffix_EmployeeID_1">1</span></td>
<td><span id="EmployeesSuffix_EmployeeName_1">EmployeeName1</span></td>
</tr>
...
<tr>
<td><span id="EmployeesSuffix_EmployeeID_9">9</span></td>
<td><span id="EmployeesSuffix_EmployeeName_9">EmployeeName9</span></td>
</tr>
</tbody>
</table>

3. With a ClientIDRowSuffix defined, but instead of just one value a compound value will be used. Exhibits the same behavior as one value but it will suffix both values onto the ID.

markup:

<asp:GridView ID="EmployeesCompSuffix" runat="server" AutoGenerateColumns="false"
ClientIDMode="Predictable" ClientIDRowSuffix="ID, Name" >
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="EmployeeID" runat="server" Text='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="EmployeeName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

output:

<table id="EmployeesCompSuffix" style="border-collapse: collapse" cellspacing="0" rules="all" border="1">
<tbody>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
</tr>
<tr>
<td><span id="EmployeesCompSuffix_EmployeeID_1_EmployeeName1">1</span></td>
<td><span id="EmployeesCompSuffix_EmployeeName_1_EmployeeName1">EmployeeName1</span></td>
</tr>
...
<tr>
<td><span id="EmployeesCompSuffix_EmployeeID_9_EmployeeName9">9</span></td>
<td><span id="EmployeesCompSuffix_EmployeeName_9_EmployeeName9">EmployeeName9</span></td>
</tr>
</tbody>
</table>

Thanks to Microsoft ASP.NET Team for adding this valuable feature!

Thursday, April 23, 2009

Tech-Ed India 2009 Top Architect Contest

Microsoft has launched a Top Architect Contest in India. There are fabulous prizes along with entry to Tech-Ed 2009 which is going to be held at Hyderabad from 13-15 May 2009. This contest will evaluate your architectural skills. The problem statement is given as "India Election Pedia – A DIGITAL MESH". The evaluation of the design will be done by a team of senior architects at Microsoft.


Contest Prizes:

  • The Architects with the TOP-10 entries will receive a MICROSOFT-branded WATCH each.
  • The Architects with the TOP-3 entries will be invited to attend Tech.Ed-India 2009 – scheduled to be held at Hyderabad on 13-15 May, 2009 – for FREE. Benefits will include:
  • Reimbursement of Travel & Stay; and
  • FREE entry to Tech.Ed-India 2009.
  • The two (2) Contest Runners-Up will each receive a WINDOWS MOBILE PHONE.
  • The Contest Winner will receive the Grand Prize of a WINDOWS VISTA LAPTOP.
Details of this contest can be found at here.

Tuesday, April 14, 2009

C# 4.0 New Exciting Features!

New exciting features of C# 4.0. C# has always been an exciting language. In each version of C# we find many exciting and new features that made our life simpler and easier. C# 4.0 brings us exciting features such as:

  • Dynamically typed objects
  • Named and Optional function parameters
  • Covariance and Contravariance
Architecture

Dynamically Types Objects
Today, in C# we may have the code to get the instance of class Calculator and then invoke the Add() method on that instance to return an integer.

Calculator calc = GetCalculatorInstance();
int sum = calc.Add(10, 20);


Here all the objects are statically typed i.e. the type of the object is known at compile time. Now, let's take an exmaple where the Calculator class resides in an assembly and we want to invoke the Add() method dynamically through C#. When the phrase "dynamically invoke method" comes, we immediately think of Reflection. Yes, you are correct, we will use reflection to invoke the Add() method as shown below:

object calc = GetCalculatorInstance();
Type type = calc.GetType();
object result = type.InvokeMember("Add",
BindingFlags.InvokeMethod, null,
new object[] { 10, 20 });

int sum = Convert.ToInt32(result);

So far so good. Now what if you don't want to play with reflection?
Yes, you can do so in C# 4.0. Making the use of "statically typed dynamic object" you can achieve the same output as that of reflection. Let's look at the code first, which will make our understanding more clear:

dynamic calc = GetCalculatorInstance();
int result = calc.Add(10, 20);

In the above example we are declaring a variable, calc, whose static type is dynamic. Yes, you read that correctly, we have statically typed our object to be dynamic. We'll then be using dynamic method invocation to call the Add() method and then dynamic conversion to convert the result of the dynamic invocation to a statically typed integer.

I would still encourage you to use static types wherever possible, since they are the best for performance reason.

Named and Optional function parameters
Remember C++'s default values for function parameters that made the parameter in question optional? In C# 4.0 you will be able to do that. In previous version of the language to achieve this type of behavior we use to create overloaded methods with varying parameters. By doing this, number of methods would increase keeping the business logic almost same.

Let's assume that we have the following OpenTextFile method along with three overloads of the method with different signatures. The overloads of the primary method will call the primary method with default values for the arguments expected.

4 arguments (Primary method)
public StreamReader OpenTextFile(
string path,
Encoding encoding,
bool detectEncoding,
int bufferSize) { }

3 arguments (Overloaded method)
public StreamReader OpenTextFile(
string path,
Encoding encoding,
bool detectEncoding) { }

2 arguments (Overloaded method)
public StreamReader OpenTextFile(
string path,
Encoding encoding) { }

1 argument (Overloaded method)
public StreamReader OpenTextFile(string path) { }

In C# 4.0 the primary method can be refactored to use optional parameters as shown below:

Single primary method accepting default values
public StreamReader OpenTextFile(
string path,
Encoding encoding = null,
bool detectEncoding = false,
int bufferSize = 1024) { }

It is now possible to call the OpenTextFile method omitting one or more of the optional parameters.

OpenTextFile("foo.txt", Encoding.UTF8);

It is also possible to provide named parameters and as such the OpenTextFile method can be called omitting one or more of the optional parameters while also specifying another parameter by name.

OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4098);


Please note that named arguments must be provided last although when provided they can be provided in any order.

Covariance and Contravariance

An operator between types is said to be covariant if it orders these types from more specific to more general ones. Similarly an operator between types is said to be contravariant if it orders them in the reversed order. Whenever neither of these conditions is met, an operator is said to be invariant.
Eric Lippert has a complete 11 part article on Covariance and Contravariance which describes the matter in details with examples. This is what I was looking for since long :)

Apart from the features mentioned above, C# 4.0 is going to bring a lot more for the developers. Keep watching...

Monday, April 13, 2009

Indian Elections: Raise your voice for developing India

Parliamentary elections in India will be held in five phases between April 16 and May 13, India's Election Commission announced Monday. A new Lok Sabha, or lower house of Parliament be constituted before June 2.

These elections are crucial to the growth of India. Foreseeing the problems that India is facing today, it is important to elect a PM who is well educated and who can work towards the growth of country with respect to Education, Agriculture, Information Technology, Defense Technology etc.

When we employ house maid for cooking food, What all we expect from her?
1. She should have good character.
2. She should work dedicate.
3. She should follow clean practices.
4. She should respect time.
5. She should not have any criminal background. She should not steal anything from house.
6. Etc etc etc...

Now, when we expect so many things from a person to whom we are governing and paying a small amount of money, how much can we expect from a Prime Minister of India?

When saying this, it is up to all of us to elect a "good" PM. The elections are on up of our head and we should think of a proper candidate for donating our vote. Most of the candidates have number of court cases pending on them, some for murders, some for rape, some of financial frauds. Don't select a person who is a CRIMINAL. How can a criminal govern a country?

This time let's go ahead and select a developing PM for India!