Exploring Action Delegate

We used delegate a lot in some or other way. Like as we know, the event base model that we use in windows as web programming, is based on delegate only. I am in the habit of using delegates often. In last few days, I found a very elegent way to use the delegate.I was in the habit of of using only generic delegates that allows us type safety and lot more flexibility.

In our traditional programming, we use the delegate as in the following steps.

  1. Declaring the delegate
  2. Creating object of the delegate and assigning it to appropriate function
  3. Calling the delegate

Lets see the code

 public class Program
    {
        //Declaring an delegate
        public delegate void MyDelegate<R, S>(R r, S s);
        public static void Main(string[] args)
        {
            //Creating an Action variable and assigning it to a function
            MyDelegate<int, int> m1 = Multiply;
            //Calling the method
            m1(3, 4);
            Console.ReadKey();
        }

        public static void Multiply(int i, int j)
        {
            Console.WriteLine(i * j);
        }
    }

.NET 2.0 introcuced one generic delegate Action which takes a single parameter and returns nothing. Its declaration is
-Public delegate void Action<T1>(T1 t1) // Takes 1 parameter and returns nothing
This is a very much elegatent way to use the delegate.

And C# 3.0, introduced 4 delegates which are as

  1. Public delegate void Action() // Takes no parameter and returns nothing
  2. Public delegate void Action<T1,T2>(T1 t1,T2 t2) // Takes 2 parameters and returns nothing
  3. Public delegate void Action<T1,T2,T3>(T1 t1,T2 t2,T3 t3) // Takes 3 parameters and returns nothing
  4. Public delegate void Action<T1,T2,T3,T4>(T1 t1,T2 t2,T3 t3),T4 t4) // Takes 4 parameters and returns nothing

Lets see them running

public class Program
{
public static void Main(string[] args)
{
//Creating an Action variable and assigning it to a function
Action myAction = Multiply;
//Calling the method
myAction(3, 4);

//Also can be called as
myAction.Invoke(3, 4);
}

public static void Multiply(int i,int j)
{
Console.WriteLine(i * j);
}
}

As from the code, we can also see that Action delegate also provide a method invoke to call the method.

These Action delegate also can be used with Anonymous Methods as

public class Program
{
public static void Main(string[] args)
{
//Creating an Action variable and assigning it to a function
Action myAction = delegate(int i, int j) { Console.WriteLine(i * j); };
//Calling the method
myAction(3, 4);

Console.ReadKey();
}
}

Also can be used with lambda function. Lets see

public class Program
    {
        public static void Main(string[] args)
        {
            //Creating an Action variable and assigning it to a function
            Action<int> myAction = s => Console.WriteLine(s * 5);
            //Calling the method
            myAction(3);

            Console.ReadKey();
        }
    }

So code delegently and efficiently.

Note: The ForEach and ForEach<T> methods each take an Action<T> delegate as a parameter. The method encapsulated by the delegate allows us to perform an action on each element in the array or list.

Happy .Neting….

Cheers,
Brij

Client Ids generation with ASP.NET 4.0

From last sometimes, I started exploring ASP.NET 4.0 webforms enhancement. I really found some exciting enhancements in ASP.NET 4.0 and am sure, this all going to be make web development simple and will provide more flexibility to us.So I started picking the most exciting features of the ASP.NET 4.0 one by one.Earlier I wrote on URL Routing, you can go through to the link as below.

URL Routing with ASP.NET 4.0 [^]

As form the Title, you know that here I am going to discuss how we can control over generation of Client Ids of ASP.NET Server controls in ASP.NET 4.0. This Client Ids was another thing that was earlier mystery for me but later I identified the algorithm that is used to generate the the ClientIds for the server controls by the .NET engine,but they never been user friendly.

Why Client Ids:

Client Ids were always been problem for us.But as now a days, in new age application we are moving more towards the client side programming in new Rich Interent applications. Many new technologies and the way of programming has been evolved in last few years to make very rich UI like JQuery,JSon,Dojo.

In DOM, to access a a control client id play pivotal role.So Microsoft also trying to make our life easier by providing the capability to control over the client id generation which will ensure easy simple and less error prone RIA development.

Client Ids earlier:

So lets discus, how the ClientIds were generated earlier. First I’will statrt with normal control say textbox control or a label. So here the client Ids that are generated, was starting with prefix of all the naming containers from top to bottom with separated as underscore. And actually this was a good idea to generate the unique id at client side. But as I discussed ClientIds are key part of new age development. Lets look at the example for a simple textbox server control.My aspx looks like

So from the above picture we can see that my label and textbox are inside a contentplaceholder. Now lets look at the ClientId

Now here client Id is ctl00_ContentPlaceHolder1_myTextBox.If we go one by one the ctl00 is the counter ,next one is ID of contentplaceholder and next id of textbox.

So one thing as you move the control to some other part the Client Id will get changed as well.

So although we know the ID is going to be unique on the page but still you dont have any control over itFrown . .Net engine will generate the ClientIds according to its algorithm for you ).

So this all about of the simple controls, Now lets talk about some data controls, like gridview listwiew, dropdown etc. Here in these control what we do, we just bind the datasource to the control. And at runtime based on the data, the number of rows(controls) are generated. So what about the client Ids here. Here also the Client Ids are being generated in the same way as I already discussed with prefix of rownumber. So lets have a look to the example.

My aspx code for GridView. Here I am showing ID,Book Name and Price

So in the above example, I have taken a gridview. And in this I have three label in different ItemTemplates. The gridview is in contentplaceholder.

Now look to the ClientIds

You can see the id is like ctl00_ContentPlaceHolder1_gridviewBooks_ctl02_lblID. So here if we go one by one first the counter the contentplaceholder id again rowcounter generated in sequence for every row by .Net engine to make it unique and last lebel ID.

So  it becomes very uneasy to use.

But as new era web development, when we doing lots of work at client side the Client ids become a key part in web development.

Control Client Ids generation with ASP.NET 4.0:

ASP.NET 4.0 provides the power to control Client Ids generation. For that it provide the new property ClientIDMode property to handle this.This property enables us to to specify that, how the Client Ids will be generated for the controls . This provides four options:

  • AutoID
  • Static
  • Predictable
  • Inherit

We’ll discuss one by one.

AutoID:  this property is same as earlier version of .NET.Specify this value if you dont want any changes in the Client Id genration from the earlier version.As I discussed in ClientIDs in earlier versions.

Static: Means the you want the static id of your control.You should use this property when you know the ID will be going to be unique on the page. Here .net engine will generate the Client Ids as it is, without adding any suffixes or prefixes in it. This mode is mainly used for normal single control. Lets look at the example.

Here as you seen in the picture,I set the ClientIDMode for Label AutoID and for TextBox I set it Static. Now lets see the generated Client Ids

Now if you see the client ID of Label it is same as earlier one because here I set it Auto.

But for the TextBox I set it static. So here the Client Id is same as the ID that we set it on aspx page.This is the beauty of ASP.NET 4.0 . So if we set it static the .net engine wont generate a new client id for the control it will use the ID of the control as Client ID.

Note: One thing need to make sure here, if we set the mode static then there should be no control on the page with the same id because it will have the same client id on the page and it may be disastrous when we access it from Clientside.

Predictable: This is one another mode that I liked for the ClienId generation. When you exactly dont know whether the Id is unique on the page or not, then you can use this property.This value enables us the predict the client ids on the rendered page.When you set mode to this, you need to set some more proprties according to your own choice.

Now I will take the example as above.Now here the aspx code would be like

Here One thing we are using datacontrol then we can not set it static because there going to be multiple controls generated based on the data.

So here we will be using mode as Predictable so that we can predict what will be the id of the contrl. One more property ClientIDRowSuffix we need to set it here. I set it ID meand the ID column.

Now lets look at the generated Client Ids

Now here if we look at the ClientID . So here it is MainContent_gridviewBooks_lblName_1. So if look it deeply the we find that here there is no conter like thing. Here we have first id of contentplaceholder the id of gridview the id of label the the suffix id that we set. So its really predictable Smile and similarly for other rows.

Inherit: This is also value to set the to this property.As the name suggests,it means the Id genration of the contrl will be same as parent cpntrol. This is the default behavior of the control.

Setting the property at various levels:

There are various places where we can set the ClientIDMode property.This can be set at control level, page level as well as application. The behavior will be same. We can set it at page directive as below.

To set it at Application level, we need to set it in config file as

and that will be applied across all the pages in the application.

Feedback and Suggestions:

Feedback is key for improvement. I would request to you all to share your feedback and give me some suggestions, which which would encourage and help in more and quality writing.

Failed to access IIS metabase

Few days back, I formatted my system due to some virus.. Then again installed OS and VS2008 for my learning.I am in habit of using integrated webserver with Visual studio.

But later,I thought of deploying one WCF service. So when I deployed my service and tried to access, It started barfing me.This was running smoothly prior to formatting my system.

I kept trying to resolve this issue but it took a lot of time.Finally it started running as earlier.

Root Cause: Acually after installation of my OS Windows XP, I installed .net framework and Visual studio.Then when I needed IIS, I installed it.

Cause was, ASPNET user does not had sufficient rights over IIS

Solution:Install aspnet using command aspnet_regiis -i as

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -i

then reset iis using iisreset command in command propmpt..

it should work now..

Happy .neting

Article selected as “Artcle of the day” at Microsoft Official website (www.asp.net)

It is really a great pleasure for me that one of my article got a place at Microsoft Official website (www.asp.net).My Article  is selected as “Article of the day” at http://www.asp.net.

In this Article, I have explained the common and mostly used web.config tags, their different sections and also discussed about securing the the config file.

You can view complete article at http://www.Dotnetfunda.com here.

Thanks to dotnetfunda for their support.

You can find the complete listing of my article of My articles section in right pane.

Cheers,

Brij