javascript+how to create properties and get whether element is check or not

April 10, 2008

 document.onkeydown = myKeyDownHandler;

 function
myKeyDownHandler(e){
if(event.keyCode==13 ){alert(document.getElementById(‘<%=btnInsertRow.ClientID %>’).hasFocus);document.getElementById( ‘<%=btnInsertRow.ClientID %>’).focus();

window.onload = function() {
for (i=0; i<form.elements.length-1; i++) {
   elem = document.forms['quick_reply'].elements[i];
   elem.focused = false;
   elem.hasFocus = function() {
      return this.focused;
   };
   elem.onfocus=function() {
      this.focused=true;
   };
   elem.onblur=function() {
      this.focused=false;
   };
}
}
<style type=”text/css”>
input, select, textarea, label, button {
   background-color: #FFF;
}
input:focus, select:focus, textarea:focus, label:focus, button:focus {
   background-color: #FEFEFE;
}
</style>

 

string.format from(http://blog.stevex.net/index.php/string-formatting-in-csharp/)

April 2, 2008

String Formatting in C# I couldn’t find a quick reference to .NET string formatting using the String.Format() function, so I created this one (which has also spawned this String Formatting FAQ and strangely enough, this cartoon. When I started working with the .NET framework, one thing puzzled me. I couldn’t find sprintf(). sprintf() is the C function that takes an output buffer, a format string, and any number of arguments, and builds a string for you. For example: char szError[256]; sprintf(szError, “Error %d occurred.\n”, nError); This would write “Error 12 occurred.” into the szError buffer (assuming nError was 12). It’s a basic part of C programming and most C++ programmers still use it though better functionality is available in the STL because sprintf is simple to use and clear. The STL equivalent would be: str << “Error ” << nError << ” occurred.” << endl; Or something close to that. It’s type-safe, and more OO than sprintf, but not as easy to read and not as easy to localize. The .NET framework handles strings very nicely – but it takes some getting used to. The rough equivalent of sprintf in .NET is the static String.Format function, which takes a format string and some arguments, and generates an output string. (This is a nice improvement over sprintf since there’s no chance you’ll overflow the output buffer). For example: string errorString = String.Format(”Error {0} occurred.”, nError); Teeming with metadata, the .NET environment doesn’t need the format string to say what type of data you’re formatting, just where you want it. (A common sprintf bug is supplying the wrong data type – there’s no protection from using %s instead of %d and having your program crash when sprintf is called). The {0} in the string above is replaced with the value of nError, but what if you want to specify the number of digits to use? Or the base (hexadecimal etc)? The framework supports all this, but where it seemed confusing is that it’s not the String.Format function that does the string formatting, but rather the types themselves. Every object has a method called ToString that returns a string representation of the object. The ToString method can accept a string parameter, which tells the object how to format itself – in the String.Format call, the formatting string is passed after the position, for example, “{0:##}” The text inside the curly braces is {index[,alignment][:formatString]}. If alignment is positive, the text is right-aligned in a field the given number of spaces; if it’s negative, it’s left-aligned. Strings There really isn’t any formatting within a strong, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call. Sample Generates String.Format(”->{1,10}<-”, “Hello”); -> Hello<- String.Format(”->{1,-10}<-”, “Hello”); ->Hello <- Numbers Basic number formatting specifiers: Specifier Type Format Output (Passed Double 1.42) Output (Passed Int -12400) c Currency {0:c} $1.42 -$12,400 d Decimal (Whole number) {0:d} System.FormatException -12400 e Scientific {0:e} 1.420000e+000 -1.240000e+004 f Fixed point {0:f} 1.42 -12400.00 g General {0:g} 1.42 -12400 n Number with commas for thousands {0:n} 1.42 -12,400 r Round trippable {0:r} 1.42 System.FormatException x Hexadecimal {0:x4} System.FormatException cf90 Custom number formatting: Specifier Type Example Output (Passed Double 1500.42) Note 0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes. # Digit placeholder {0:(#).##} (1500).42 . Decimal point {0:0.0} 1500.4 , Thousand separator {0:0,0} 1,500 Must be between two zeroes. ,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000. % Percent {0:0%} 150042% Multiplies by 100, adds % sign. e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available. ; Group separator see below The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious: Dates Note that date formatting is especially dependant on the system’s regional settings; the example strings here are from my local locale. Specifier Type Example (Passed System.DateTime.Now) d Short date 10/12/2002 D Long date December 10, 2002 t Short time 10:11 PM T Long time 10:11:29 PM f Full date & time December 10, 2002 10:11 PM F Full date & time (long) December 10, 2002 10:11:29 PM g Default date & time 10/12/2002 10:11 PM G Default date & time (long) 10/12/2002 10:11:29 PM M Month day pattern December 10 r RFC1123 date string Tue, 10 Dec 2002 22:11:29 GMT s Sortable date string 2002-12-10T22:11:29 u Universal sortable, local time 2002-12-10 22:13:50Z U Universal sortable, GMT December 11, 2002 3:13:50 AM Y Year month pattern December, 2002 The ‘U’ specifier seems broken; that string certainly isn’t sortable. Custom date formatting: Specifier Type Example Example Output dd Day {0:dd} 10 ddd Day name {0:ddd} Tue dddd Full day name {0:dddd} Tuesday f, ff, … Second fractions {0:fff} 932 gg, … Era {0:gg} A.D. hh 2 digit hour {0:hh} 10 HH 2 digit hour, 24hr format {0:HH} 22 mm Minute 00-59 {0:mm} 38 MM Month 01-12 {0:MM} 12 MMM Month abbreviation {0:MMM} Dec MMMM Full month name {0:MMMM} December ss Seconds 00-59 {0:ss} 46 tt AM or PM {0:tt} PM yy Year, 2 digits {0:yy} 02 yyyy Year {0:yyyy} 2002 zz Timezone offset, 2 digits {0:zz} -05 zzz Full timezone offset {0:zzz} -05:00 : Separator {0:hh:mm:ss} 10:43:20 / Separator {0:dd/MM/yyyy} 10/12/2002 Enumerations Specifier Type g Default (Flag names if available, otherwise decimal) f Flags always d Integer always x Eight digit hex. Some Useful Examples String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, value); This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero. String.Format(”{0:(###) ###-####}”, 8005551212); This will output “ (800) 555-1212 ″.

manually save image file

February 24, 2008

Stream s = File.OpenRead(HFilePath.Value);byte[] buffer = new byte[s.Length];s.Read(buffer, 0, (

int)s.Length);FileStream fs = new FileStream(filePath + fileName + fileExtension,FileMode.Create);fs.Write(buffer,0,(Int32)s.Length);// Code to save a File

Bitmap bmp = new Bitmap(fs);bmp.Save(fs, ImageFormat.Gif);// if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(“.gif”))

// {

// bmp.Save(fs, ImageFormat.Gif);

// }

// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(“.jpg”))

// {

// bmp.Save(fs, ImageFormat.Jpeg);

// }

// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(“.jpeg”))

// {

// bmp.Save(fs, ImageFormat.Jpeg);

// }

// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(“.bmp”))

// {

// bmp.Save(s, ImageFormat.Bmp);

// }

//else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(“.png”))

// {

// bmp.Save(s, ImageFormat.Bmp);

// }

Delegates and Events

February 23, 2008

http://www.codeproject.com/KB/cs/delegates-part1.aspx

Introduction

All of us have been exposed to event driven programming of some sort or the other. C# adds on value to the often mentioned world of event driven programming by adding support through events and delegates. This article is a part of a series that aims at understanding fully the way in which delegates and events operate. Part1 helps you understand the role of multicast delegates in the context of UI interaction. The emphasis of this article would be to identify what exactly happens when you add an event handler to your common UI controls. A simple simulation of what could possibly be going on behind the scenes when the AddOnClick or any similar event is added to the Button class will be explained. This will help you understand better the nature of event handling using multi cast delegates. All the examples provided are in C#.

Events

An event is the outcome of an action. There are two important terms with respect to events. The event source and the event receiver. The object that raises the event is called event source and the object that responds to the event is called event receiver. Did you observe a hitch in the above explanation? O.K. my event source raises the event and my event receiver receives it, but what is the communication channel between them. Take the instance of you talking with a friend of yours over the telephone. Now you are the event source and your friend is the event receiver and the telephone cable is the communication channel. Similarly the communication channel between an event source and an event receiver is the delegate. The internals of events and their relationship to delegates would be dealt with in a later article. The explanation of events here is just to help the reader understand and visualize what exactly events are.

Delegates

Forget computers for a moment. Just think about delegates in the real world. Who are delegates? Delegates are people who represent a particular country or region or state in another country or region or state. Extend this same definition now to C#. In C#, delegates act as an intermediary between an event source and an event destination.

To be even precise delegates are similar to function pointers. They can be called as type safe function pointers. Delegates have other uses in addition to event handling. But this article would focus on describing delegates with respect to event handling. A delegate class used as an intermediary between an event source and event receiver is called an event handler.

Types of Delegates

There are basically two types of delegates. Single Cast delegate and Multi Cast delegate. Let us first understand at the broader level the definition of both these delegates. A single cast delegate can call only one function. A multi cast delegate is one that can be part of a linked list. The multi cast delegate points to the head of such a linked list. This means that when the multi cast delegate is invoked it can call all the functions that form a part of the linked list. Assume that i have several clients who would like to receive notification when a particular event occurs. Putting all of them in a multi cast delegate can help call all the clients when a particular event occurs.

To support a single cast delegate the base class library includes a special class type called System.Delegate. To support multi cast delegates the base class library includes a special class type called SystemMultiCastDelegate.

Single Cast delegate

The signature of a single cast delegate is shown below. The letters in italics can be replaced with your own names and parameters.

public delegate Boolean  DelegateName (parm1, parm2)

When the compiler compiles the statement above, it internally generates a new class type. This class is called DelegateName and derives from System.Delegate. Just to make sure just check the ILDisassembler code to check that this is happening.

As an example let us create a single cast delegate named MyDelegate which would point to a function MyFunction. The code appears as below,

public delegate Boolean MyDelegate(Object sendingobj, Int32 x);  public class TestDelegateClass {      	Boolean MyFunction(Object sendingobj, Int32 x)  	{            		//Perform some processing            		return (true);   	} 	        	public static void main(String [] args) 	{ 		//Instantiate the delegate passing the method to invoke in its constructor 		MyDelegate mdg = new MyDelegate(MyFunction);              		// Construct an instance of this class 		TestDelegateClass tdc = new TestDelegateClass();                 		// The following line will call MyFunction 		Boolean f = mdg(this, 1);         	} }

How does the above code work?

The System.Delegate contains a few fields. The most important of them are Target and Method.

The Target field identifies an object context. In the scenario above this would point to the TestDelegateClass being created. If the method to be invoked is a static method then this field will be null.

The Method field identifies the method to be called. This field always has some value. It is never null.

To the intelligent reader, if you observe the IL Disassembler code you would see that the constructor for MyDelegate contains two parameters. But in our case we are passing only one parameter? Any guesses on how this is done? Yeah you are right! It gets done internally by the compiler. The compiler resolves the call above to a call passing in the two parameters required. If you observe in C++ with managed extension, the object and the address of the function have to be passed explicitly. But in VB and C# we have done away with this with the compiler filling in the necessary details.

In the code sample above we saw,

Boolean f = mdg(this, 1);

When the compiler comes across this line, this is what happens,

  1. The compiler identifies that mdg is a delegate object.
  2. The delegate object has the target and method fields as described above.
  3. The compiler generates code that calls the Invoke method of the System.Delegate derived class i.e MyDelegate.
  4. The Invoke method internally uses the MethodInfo type identified by the delegate’s Method field and calls the MethoidInfo‘s invoke method.
  5. The MethodInfo‘s invoke method is passed the delegates Target field which identifies the method and an array of variants which contains the parameters to the method to be called. In our case, the array of variants would be an Object and an Int32 value.

The above discussion would have made you clear about what happens internally when a method gets called through a Single Cast delegate.

Multi Cast delegate

The signature of a mutli cast delegate is shown below. The letters in italics can be replaced with your own names and parameters.

public delegate void DelegateName (parm1, parm2)

Whatever has been explained with respect to Single cast delegate holds good even in the context of a Multi Cast Delegate. There is a small addition here. Since a multi cast delegate represents a linked list, there is an additional field called prev which refers to another Multi Cast Delegate. This is how the linked list is maintained.

The return type if you have observed has changed from Boolean to void. Have you guessed the reason as to why it happens? The reason is that since several multi cast delegates get called consecutively we cannot wait to get the return value from each of these methods being called.

The code shown in the example for single cast delegate will work in the case of multi cast delegate too. The only difference is that the delegate signature needs to be changed, the method signature needs to be changed to return void instead of Boolean.

The power of multi cast delegates come in when you combine delegates to form a linked list. The Combine method is available in the System.Delegate class as a static method. The function signature as follows.

public static Delegate Combine(Delegate a, Delegate b);

What the above method does is that it combines the two delegates a and b and makes b’s prev field point to a. It returns the head of the linked list. This in turn has to be type casted to our delegate type.

Similar to the Combine method we have a remove method which removes a delegate from the linked list and gives you the modifies smaller linked list with a pointer to the head. The signature of the remove method is as follows,

public static Delegate Remove(Delegate source, Delegate value);

Here’s a small sample that illustrates the use of a multi cast delegate,

Collapse
using System;  class MCD1 {     public void dispMCD1(string s)     {         Console.WriteLine("MCD1");     } }  class MCD2 {      public void dispMCD2(string s)     {         Console.WriteLine("MCD2");     } }     public delegate void OnMsgArrived(string s);  class TestMultiCastUsingDelegates {     public static void Main(string [] args)     {         MCD1 mcd1=new MCD1();         MCD2 mcd2=new MCD2();         // Create a delegate to point to dispMCD1 of mcd1 object         OnMsgArrived oma=new OnMsgArrived(mcd1.dispMCD1);          // Create a delegate to point to dispMCD2 of mcd2 object         OnMsgArrived omb=new OnMsgArrived(mcd2.dispMCD2);           OnMsgArrived omc;         // Combine the two created delegates. Now omc would point to the head of a linked list         // of delegates         omc=(OnMsgArrived)Delegate.Combine(oma,omb);           Delegate [] omd;          // Obtain the array of delegate references by invoking GetInvocationList()         omd=omc.GetInvocationList();            OnMsgArrived ome;         // Now navigate through the array and call each delegate which in turn would call each of the         // methods         for(int i=0;i<omd.Length;i++)         {             // Now call each of the delegates             ome=(OnMsgArrived)omd[i];             ome("string");         }     } }

The examples in this article would revolve around Multi Cast Delegates. It is essential that you have understood the basics of single cast and multi cast delegates before you proceed further.

Problem Scenario

The code below shows an example of adding a button to a Form. The button is associated with an event handler that handles whatever happens when the button is pressed. When the form is displayed and the button is pressed a message box showing “Button Clicked” will appear.

Compilation directions: Compile using

csc /r:System.DLL;System.WinForms.DLL;Microsoft.Win32.Interop.DLL FormTest.cs
Collapse
/* Creating a form and adding a button to it and associating the button with an event handler */ using System; using System.WinForms; public class FormTest : Form {     //Create a button     private Button button1 = new Button();     public static void Main (string [] args)     {         //Run the application         Application.Run(new FormTest());     }          public FormTest()     {         //Set up the Form         this.Text = "Hello WinForms World";         //Set up the button         button1.Text = "Click Me!";         //Register the event handler         button1.AddOnClick(new System.EventHandler(buttonClicked));         //Add the controls to the form         this.Controls.Add(button1);     }       //The event handling method     private void buttonClicked(object sender, EventArgs evArgs)     {         MessageBox.Show("Button clicked");     } }

The topic of our discussion would be the routing of calls between the time when the click event is raised and the time when the method displaying “Button clicked” is displayed.

Components of the Exercise

This section will talk about the components that would complete the architecture,

1. Delegate Event Handler

A delegate event handler that routes the call to the appropriate method. Let us call it ButtonEventHandler. The declaration of this delegate should follow that the same for declaration of multicast delegates. The declaration is as follows.

public delegate void ButtonEventHandler(object sender, ButtonEventArgs e);

Parameters

sender – Identifies the origin of the event

ButtonEventArgs – Identifies the Event Arguments. This class is derived from EventArgs. EventArgs is the base class for event data. The data with respect to the event generated is going to be held in this class. The reason why I have made use of a seperate class is that i am going to use a string member variable in the derived class which identifies the the action.

2. EventArgs derived class

The reason for using a derived class for EventArgs has been mentioned in the previous point. The class looks like this:

public class ButtonEventArgs : EventArgs {       	public string msg; //identifies the action 	public ButtonEventArgs(string message) 	{ 		msg=message;   	} }

3. A button class

This class is the simulation of the NGWS SDK Button Class. A control class such as a button class must be able to generate events when actions such as clicking on it are performed. Now think logically, the button is pressed and a message indicating the same should be displayed. The button here is the event source. Forget for a moment about the event receiver. Now what is required in between? Yeah! you guessed it right, a delegate to forward the calls to the appropriate event receiver. Now if, you want to add a delegate to your button you do it through Add methods in your button class. Similarly if you want to remove a delegate you do it through a Remove method in your button class. These methods must be named AddOn<Event Name> and RemoveOn<Event Name> according to the NGWSSDK documentation. Our button class will respond to click and press events. Thus the methods in our class should be AddOnPress, RemoveOnPress, AddOnClick and RemoveOnClick. The signature of the above methods will be as follows,

public void AddOnClick(ButtonEventHandler handler); public void RemoveOnClick(ButtonEventHandler handler); public void AddOnPress(ButtonEventHandler handler); public void RemoveOnPress(ButtonEventHandler handler);

At the end of this we have added the methods which add and remove delegates corresponding to Click and Press events in the button class.

Now what is required? The most important part, methods that raises the events. The naming conventions followed for such methods are On<Event Name>. Thus the methods in our class should be OnClick and OnPress. These methods are passed the event data. The method raises the events by invoking the delegates.

The signature of the mehods will be as follows,

protected virtual void OnPress(ButtonEventArgs e); protected virtual void OnClick(ButtonEventArgs e);

Why are the above two methods declared as protected? To help the subclasses override this event without attaching a delegate to it.

What happens in the SDK Button class. When the button is pressed, an event data gets created, the OnClick method gets called passing in the event data as the parameter. The OnClick method in turn calls the event receivers through the delegates. Do you observe a missing link above? If the OnClick method gets passed the event data, who creates the event data? The answer is that the event data could be created by the SDK. For our purposes since we cannot tap onto the SDK let us simulate what the SDK does by creating two methods whose only purpose is to create the event data and call the appropriate OnClick or OnPress methods. The signature of these methods is as follows,

public void click(); public void press();

Now let us take a look at the whole button class,

Collapse
class button {     private ButtonEventHandler beh=null; // For click     private ButtonEventHandler bep=null; // For press       public void AddOnClick(ButtonEventHandler handler)     {         Console.WriteLine("Adding click event handler");         beh=(ButtonEventHandler)Delegate.Combine(beh, handler);     }       public void RemoveOnClick(ButtonEventHandler handler)     {         Console.WriteLine("Removing click event handler");         beh=(ButtonEventHandler)Delegate.Remove(beh, handler);     }       protected virtual void OnClick(ButtonEventArgs e)     {         if (beh!=null)         {         beh(this, e);         }     }       public void AddOnPress(ButtonEventHandler handler)     {         Console.WriteLine("Adding Press Event handler");         bep=(ButtonEventHandler)Delegate.Combine(bep, handler);     }       public void RemoveOnPress(ButtonEventHandler handler)     {         Console.WriteLine("Removing Press Event handler");         bep=(ButtonEventHandler)Delegate.Remove(bep, handler);     }       protected virtual void OnPress(ButtonEventArgs e)     {         if (bep!=null)         {         bep(this, e);         }     }       public void click()     {         ButtonEventArgs bea=new ButtonEventArgs("clicked");         OnClick(bea);     }       public void press()     {         ButtonEventArgs bea=new ButtonEventArgs("pressed");         OnPress(bea);     } }

Now let us begin a line by line walkthrough of the above code,

private ButtonEventHandler beh=null; // For click private ButtonEventHandler bep=null; // For press

The above two lines declare two delegates. Both these delegates are multicast delegates. They represent the series of method calls that have to take place when an event occurs. They are initialized to null to indicate that they point nowhere when the class is first instantiated. I am using two delegates here because I assume that separate delegates are used to track separate events. In the code snippet above, the delegate beh would handle click calls and the delegate bep would handle press calls.

public void AddOnClick(ButtonEventHandler handler) {    Console.WriteLine("Adding click event handler");        beh=(ButtonEventHandler)Delegate.Combine(beh, handler); }

The AddOn methods are used to add a list of methods that need to get called when an event occurs. Thus it is natural that it receives a delegate as a parameter which in turn points to a function. Depending on the number of methods that needs to be invoked when an event occurs, this method is invoked multiple times passing the appropriate delegate parameter. The situation can be better explained with the help of a figure,

beh ------> ButtonEventHandler1 -----> &Fn1()                               ButtonEventHandler2 -----> &Fn2()             ButtonEventHandler3 -----> &Fn3()             ButtonEventHandler4 -----> &Fn4()

As the figure above shows, the beh pointer points to a delegate which in turn points to a function. In the case of multicast delegate, there is a prev field which gets initialized to null when the delegate is constructed. Now when you invoke the combine method as shown in the code snippet above, the prev field of handler points to beh. Thus when many delegates are combined using a Combine method, what internally happens is that a linked list gets created. That is why when we invoke the delegate from the OnClick or OnPress methods we find that all the functions combined get called. This makes it possible for multiple clients to receive notification about an event. This is the funda behind multi cast delegates.

The same explanation applies to RemoveOn methods.

4. The Form Simulation

In our form example explained in the beginning of the article we had a form class derived from Form which constructed a button and attached event handlers. We are going to simulate the same but the only difference would be that we would not be creating a GUI but would instead have a client which adds our simulated button class and attaches event handling methods to it. For a change, instead of explaining the source code in bits and pieces let me put in explanations in the source code itself.

The code for the client class is as follows,

Collapse
public class DelegatesAndEvents {     //Declare the simulated button class     private button button1=new button();       //Have a private constrcutor     private DelegatesAndEvents()     {         /*         Now start adding onclick and onpress events on the button class by passing the appropriate         methods to which calls should be routed. What is being done below is that three methods         are being added to the same OnClick event so that when the Click event is raised the         delegate would call all the methods         */         button1.AddOnClick(new ButtonEventHandler(ClickEventHandler1));         button1.AddOnClick(new ButtonEventHandler(ClickEventHandler2));         button1.AddOnClick(new ButtonEventHandler(ClickEventHandler3));         button1.AddOnPress(new ButtonEventHandler(PressEventHandler));         button1.click();         button1.press();     }       public static void Main(String [] args)     {         DelegatesAndEvents d=new DelegatesAndEvents();     }       public void ClickEventHandler1(object sender, ButtonEventArgs e)     {         Console.WriteLine("click event handler1");         Console.WriteLine(e.msg);         Console.WriteLine("after");     }       public void ClickEventHandler2(object sender, ButtonEventArgs e)     {         Console.WriteLine("click event handler2");         Console.WriteLine(e.msg);         Console.WriteLine("after");     }       public void ClickEventHandler3(object sender, ButtonEventArgs e)     {         Console.WriteLine("click event handler3");         Console.WriteLine(e.msg);         Console.WriteLine("after");     }       public void PressEventHandler(object sender, ButtonEventArgs e)     {         Console.WriteLine("press event handler");         Console.WriteLine(e.msg);         Console.WriteLine("after");     } }

Output

Conclusion

What goes on behind the scenes when event handlers are added? How do delegates aid in this? How can the event handling in a class be simulated, how do do multiple methods get called when a particular event has been raised etc. have been the core points of discussion dealt with in this article. I hope that the explanations would have helped in bringing about some amount of clarity. Some aspects are only internally known to the runtime and no effort has been made to dwelve into them. One such example is how does the click event get raised when the button is actually clicked. The article has focused only on what is absolutely necessary for us to understand the way delegates and events interrelate in the context of an event handler.

Delegates and events

February 23, 2008

Delegates and events

People often find it difficult to see the difference between events and delegates. C# doesn’t help matters by allowing you to declare field-like events which are automatically backed by a delegate variable of the same name. This article aims to clarify the matter for you. Another source of confusion is the overloading of the term “delegate”. Sometimes it is used to mean a delegate type, and at other times it can be used to mean an instance of a delegate type. I’ll use “delegate type” and “delegate instance” to distinguish between them, and “delegate” when talking about the whole topic in a general sense.

Delegate types

In some ways, you can think of a delegate type as being a bit like an interface with a single method. It specifies the signature of a method, and when you have a delegate instance, you can make a call to it as if it were a method with the same signature. Delegates provide other features, but the ability to make calls with a particular signature is the reason for the existence of the delegate concept. Delegates hold a reference to a method, and (for instance methods) a reference to the target object the method should be called on.

Delegates types are declared with the delegate keyword. They can appear either on their own or nested within a class, as shown below.

namespace DelegateArticle {     public delegate string FirstDelegate (int x);          public class Sample     {         public delegate void SecondDelegate (char a, char b);     } }

This code declares two delegate types. The first is DelegateArticle.FirstDelegate which has a single parameter of type int and returns a string. The second is DelegateArticle.Sample.SecondDelegate which has two char parameters, and doesn’t return anything (because the return type is specified as void).

Note that the delegate keyword doesn’t always mean that a delegate type is being declared. As we’ll see in a moment, the same keyword is used when creating instances of the delegate type.

The types declared here derive from System.MulticastDelegate, which in turn derives from System.Delegate. In practice, you’ll only see delegate types deriving from MulticastDelegate. The difference between Delegate and MulticastDelegate is largely historical; in betas of .NET 1.0 the difference was significant (and annoying) – Microsoft considered merging the two types together, but decided it was too late in the release cycle to make such a major change. You can pretty much pretend that they’re only one type.

Any delegate type you create has the members inherited from its parent types, one constructor with parameters of object and IntPtr and three extra methods: Invoke, BeginInvoke and EndInvoke. We’ll come back to the constructor in a minute. The methods can’t be inherited from anything, because the signatures vary according to the signature the delegate is declared with. Using the sample code above, the first delegate has the following methods:

     public string Invoke (int x); public System.IAsyncResult BeginInvoke(int x, System.AsyncCallback callback, object state); public string Endinvoke(IAsyncResult result);

As you can see, the return type of Invoke and EndInvoke matches that of the declaration signature, as are the parameters of Invoke and the first parameters of BeginInvoke. We’ll see the purpose of Invoke in the next section, and cover BeginInvoke and EndInvoke in the section on advanced usage. It’s a bit premature to talk about calling methods when we don’t know how to create an instance, however. We’ll cover that (and more) in the next section.

Delegate instances: the basics

Now we know how a delegate type is declared and what it contains, let’s look at how to create an instance of such a type, and what we can do with it.

Creating delegate instances

Note: this article doesn’t cover the features of C# 2.0 and 3.0 for creating delegate instances. I cover the C# 2.0 features in my article about C# 2.0. When I eventually get round to writing about C# 3.0, I’m sure I’ll cover the new features for lambda functions etc at that point. By concentrating on the explicit manner of creating instances in C# 1.0/1.1, I believe it will be easier to understand what’s going on under the hood. When you understand the basics, it’s clearly worth knowing the features these later versions provide – but if you try to use them without having a firm grasp on the basics, you may well get confused.

As mentioned earlier, the key points of data in any particular delegate instance are the method the delegate refers to, and a reference to call the method on (the target). For static methods, no target is required. The CLR itself supports other slightly different forms of delegate, where either the first argument passed to a static method is held within the delegate, or the target of an instance method is provided as an argument when the method is called. See the documentation for System.Delegate for more information on this if you’re interested, but don’t worry too much about it – it’s largely irrelevant from a C# point of view. C# only supports creating what MSDN calls a closed instance delegate type.

So, now that we know the two pieces of data required to create an instance (along with the type itself, of course), how do we tell the compiler what they are? We use what the C# specification calls a delegate-creation-expression which is of the form new delegate-type (expression). The expression must either be another delegate of the same type (or a compatible delegate type in C# 2.0) or a method group – the name of a method and optionally a target, specified as if you were calling the method, but without the arguments or brackets. Creating copies of a delegate is fairly rare, so we will concentrate on the more common form. A few examples are listed below:

// The following two creation expressions are equivalent, // where InstanceMethod is an instance method in the class // containing the creation expression (or a base class).  // The target is "this". FirstDelegate d1 = new FirstDelegate(InstanceMethod); FirstDelegate d2 = new FirstDelegate(this.InstanceMethod);  // Here we create a delegate instance referring to the same method // as the first two examples, but with a different target. FirstDelegate d3 = new FirstDelegate(anotherInstance.InstanceMethod);  // This delegate instance uses an instance method in a different class, // specifying the target to call the method on FirstDelegate d4 = new FirstDelegate(instanceOfOtherClass.OtherInstanceMethod);  // This delegate instance uses a static method in ths class containing // the creation expression (or a base class). FirstDelegate d5 = new FirstDelegate(StaticMethod);  // This delegate instance uses a static method in a different class FirstDelegate d6 = new FirstDelegate(OtherClass.OtherStaticMethod);

The constructor we mentioned earlier has two parameters – an object and an IntPtr. The object is a reference to the target (or null for static methods) and the IntPtr is a pointer to the method itself.

One point to note is that delegate instances can refer to methods and targets which wouldn’t normally be visible at the point the call is actually made. For instance, a private method can be used to create a delegate instance, and then the delegate instance can be returned from a public member. Alternatively, the target of an instance may be an object which the eventual caller knows nothing about. However, both the target and the method must be accessible to the creating code. In other words, if (and only if) you can call a particular method on a particular object, you can use that method and target for delegate creation. Access rights are effectively ignored at call time. Speaking of which…

Calling delegate instances

Delegate instances are called just as if they were the methods themselves. For instance, to call the delegate referred to by variable d1 above, we could write:

string result = d1(10);

The method referred to by the delegate instance is called on the target object (if there is one), and the result is returned. Producing a complete program to demonstrate this without including a lot of seemingly irrelevant code is tricky. However, here’s a program which gives one example of a static method and one of an instance method. DelegateTest.StaticMethod could be written as just StaticMethod in the same way that (within an instance method) you could write InstanceMethod instead of this.InstanceMethod – I’ve included the class name just to make it clear how you would reference methods from other classes.

using System;  public delegate string FirstDelegate (int x);      class DelegateTest {         string name;          static void Main()     {         FirstDelegate d1 = new FirstDelegate(DelegateTest.StaticMethod);                  DelegateTest instance = new DelegateTest();         instance.name = "My instance";         FirstDelegate d2 = new FirstDelegate(instance.InstanceMethod);                  Console.WriteLine (d1(10)); // Writes out "Static method: 10"         Console.WriteLine (d2(5));  // Writes out "My instance: 5"     }          static string StaticMethod (int i)     {         return string.Format ("Static method: {0}", i);     }      string InstanceMethod (int i)     {         return string.Format ("{0}: {1}", name, i);     } }

The C# syntax is just a short-hand for calling the Invoke method provided by each delegate type. Delegates can also be run asynchronously if they provide BeginInvoke/EndInvoke methods. These are explained later.

Combining delegates

Delegates can be combined such that when you call the delegate, a whole list of methods are called – potentially with different targets. When I said before that a delegate contained a target and a method, that was a slight simplification. That’s what a delegate instance representing one method contains. For the sake of clarity, I’ll refer to such delegate instances as simple delegates. The alternative is a delegate instance which is effectively a list of simple delegates, all of the same type (i.e. having the same signature). I’ll call these combined delegates. Combined delegates can themselves be combined together, effectively creating one big list of simple delegates in the obvious fashion.

It’s important to understand that delegate instances are always immutable. Anything which combines them together (or takes one away from the other) creates a new delegate instance to represent the new list of targets/methods to call. This is just like strings: if you call String.PadLeft for instance, it doesn’t actually change the string you call it on – it just returns a new string with the appropriate padding.

Combining two delegate instances is usually done using the addition operator, as if the delegate instances were strings or numbers. Subtracting one from another is usually done with the subtraction operator. Note that when you subtract one combined delegate from another, the subtraction works in terms of lists. If the list to subtract is not found in the original list, the result is just the original list. Otherwise, the last occurrence of the list is removed. This is best shown with some examples. Instead of actual code, the following uses lists of simple delegates d1, d2 etc. For instance, [d1, d2, d3] is a combined delegate which, when executed, would call d1 then d2 then d3. An empty list is represented by null rather than an actual delegate instance.

Expression Result
null + d1 d1
d1 + null d1
d1 + d2 [d1, d2]
d1 + [d2, d3] [d1, d2, d3]
[d1, d2] + [d2, d3] [d1, d2, d2, d3]
[d1, d2] – d1 d2
[d1, d2] – d2 d1
[d1, d2, d1] – d1 [d1, d2]
[d1, d2, d3] – [d1, d2] d3
[d1, d2, d3] – [d2, d1] [d1, d2, d3]
[d1, d2, d3, d1, d2] – [d1, d2] [d1, d2, d3]
[d1, d2] – [d1, d2] null

Delegate instances can also be combined with the static Delegate.Combine method, and one can be subtracted from another with the static Delegate.Remove method. The C# compiler converts the addition and subtraction operators into calls to these methods. Because they are static methods, they work easily with null references.

The addition and subtraction operators always work as part of assignment: d1 += d2; is exactly equivalent to d1 = d1+d2;, and likewise for subtraction. Again, the original delegate instance remains unchanged; the value of d1 just changes to be a reference to the appropriate new combined delegate.

Note that because extra delegates are both added to and removed from the end of the list, x += y; x -= y; is always a no-op.

If a delegate type is declared to return a value (i.e. it’s not declared with a void return type) and a combined delegate instance is called, the value returned from that call is the one returned by the last simple delegate in the list.

Events

First things first: events aren’t delegate instances. Let’s try that again.

Events aren’t delegate instances.

It’s unfortunate in some ways that C# lets you use them in the same way in certain situations, but it’s very important that you understand the difference.

I find the easiest way to understand events is to think of them a bit like properties. While properties look like they’re fields, they’re definitely not – and you can write properties which don’t use fields at all. Similarly, while events look like delegate instances in terms of the way you express the add and remove operations, they’re not.

Events are pairs of methods, appropriately decorated in IL to tie them together and let languages know that the methods represent events. The methods correspond to add and remove operations, each of which take a delegate instance parameter of the same type (the type of the event). What you do with those operations is pretty much up to you, but the typical use is to add or remove the delegate from a list of handlers for the event. When the event is triggered (whatever that trigger might be – a button click, a timeout, an unhandled exception) the handlers are called in turn. Note that in C#, the calling of the event handlers is not part of the event itself. (CIL defines an association with a raise_eventName method, and indeed “other” methods, but these are not used in C#.)

The add and remove methods are called in C# using eventName += delegateInstance; and eventName -= delegateInstance; respectively, where eventName may be qualified with a reference (e.g. myForm.Click) or a type name (e.g. MyClass.SomeEvent). Static events are relatively rare.

Events themselves can be declared in two ways. The first is with explicit add and remove methods, declared in a very similar way to properties, but with the event keyword. Here’s an example of an event for the System.EventHandler delegate type. Note how it doesn’t actually do anything with the delegate instances which are passed to the add and remove methods – it just prints out which operation has been called. Note that the remove operation is called even though we’ve told it to remove null.

using System;  class Test {     public event EventHandler MyEvent     {         add         {             Console.WriteLine ("add operation");         }                  remove         {             Console.WriteLine ("remove operation");         }     }                 static void Main()     {         Test t = new Test();                  t.MyEvent += new EventHandler (t.DoNothing);         t.MyEvent -= null;     }          void DoNothing (object sender, EventArgs e)     {     } }

Although it would be very rare to ignore the value in this way, there are times when you don’t want to back an event with a simple delegate variable. For instance, in situations where there are lots of events but only a few are likely to be subscribed to, you could have a map from some key describing the event to the delegate currently handling it. This is what Windows Forms does – it means that you can have a huge number of events without wasting a lot of memory with variables which will usually just have null values.

A shortcut: field-like events

C# provides a simple way of declaring both a delegate variable and an event at the same time. This is called a field-like event, and is declared very simply – it’s the same as the “longhand” event declaration, but without the “body” part:

public event EventHandler MyEvent

This creates a delegate variable and an event, both with the same type. The access to the event is determined by the event declaration (so the example above creates a public event, for instance) but the delegate variable is always private. The implicit body of the event is the obvious one to add/remove delegate instances to the delegate variable, but the changes are made within a lock. For C# 1.1, the event is equivalent to:

private EventHandler _myEvent;      public event EventHandler MyEvent {     add     {         lock (this)         {             _myEvent += value;         }     }     remove     {         lock (this)         {             _myEvent -= value;         }     }         }

That’s for an instance member. For an event declared as static, the variable is also static and a lock is taken out on typeof(XXX) where XXX is the name of the class declaring the event. In C# 2.0 there is little guarantee about what is used for locking – only that a single object associated with the instance is used for locking with instance events, and a single object associated with the class is used for locking static events. (Note that this only holds for class events, not struct events – there are issues in terms of locking with struct events; in practice I don’t remember ever seeing a struct with any events.) None of this is actually as useful as you might think – see the threading section for more details.

So, what happens when you refer to MyEvent in code? Well, within the text of type itself (including nested types) the compiler generates code which refers to the delegate variable (_myEvent in my sample above). In all other contexts, the compiler generates code which refers to the event.

What’s the Point?

Now we know what they are, what’s the point of having both delegates and events? The answer is encapsulation. Suppose events didn’t exist as a concept in C#/.NET. How would another class subscribe to an event. Three options:

  1. A public delegate variable
  2. A delegate variable backed by a property
  3. A delegate variable with AddXXXHandler and RemoveXXXHandler methods

Option 1 is clearly horrible, for all the normal reasons we abhor public variables. Option 2 is slightly better, but allows subscribers to effectively override each other – it would be all too easy to write someInstance.MyEvent = eventHandler; which would replace any existing event handlers rather than adding a new one. In addition, you still need to write the properties.

Option 3 is basically what events give you, but with a guaranteed convention (generated by the compiler and backed by extra flags in the IL) and a “free” implementation if you’re happy with the semantics that field-like events give you. Subscribing to and unsubscribing from events is encapsulated without allowing arbitrary access to the list of event handlers, and languages can make things simpler by providing syntax for both declaration and subscription.

Thread-safe events

Earlier we touched on field-like events locking during the add/remove operations. This is to provide a certain amount of thread safety. Unfortunately, it’s not terribly useful. Firstly, even with 2.0, the spec allows for the lock to be the reference to this object, or the type itself for static events. That goes against the principle of locking on privately held references to avoid accidental deadlocks.

Ironically, the second problem is the exact reverse of the first – because in C# 2.0 you can’t guarantee which lock is going to be used, you can’t use it yourself when raising an event to ensure that you see the most recent value in the thread doing the raising. You can lock on something else or call one of the memory barrier methods, but it leaves something of a nasty taste in the mouth.

If you want to be truly thread-safe, such that when you raise an event you always use the most recent value of the delegate variable, along with making sure that the add/remove operations don’t interfere with each other, you need to write the body of the add/remove operations yourself. Here’s an example:

/// <summary> /// Delegate variable backing the SomeEvent event. /// </summary> SomeEventHandler someEvent;  /// <summary> /// Lock for SomeEvent delegate access. /// </summary> readonly object someEventLock = new object();  /// <summary> /// Description for the event /// </summary> public event SomeEventHandler SomeEvent {     add     {         lock (someEventLock)         {             someEvent += value;         }     }     remove     {         lock (someEventLock)         {             someEvent -= value;         }     } }  /// <summary> /// Raises the SomeEvent event /// </summary> protected virtual OnSomeEvent(EventArgs e) {     SomeEventHandler handler;     lock (someEventLock)     {         handler = someEvent;     }     if (handler != null)     {         handler (this, e);     } }

You could use a single lock for all your events, or even for other things as well – it depends on your situation. Note that you need to assign the current value to a local variable inside the lock (to get the most recent value) and then test it for nullity and execute it outside the lock: holding the lock whilst raising the event is a very bad idea, as you could easily deadlock. (Event handlers may well need to wait for another thread to do something, and if that other thread were to call the add or remove operation on your event, you’d get deadlock.)

This all works because once handler has been assigned the value of someEvent, the value of handler won’t change even if someEvent does. So if all the handlers are unsubscribed from the event, someEvent will become null but handler will still have whatever value it had when it was assigned. In fact, as delegate instances are immutable, whatever handlers were subscribed when the handler = someEvent; line was executed will be called, even if others have subscribed between then and the handler (this, e); line.

Now, it’s important to consider whether or not you even need thread safety. Are event handlers going to be added or removed from other threads? Do you need to raise the event from another thread? If you’re in complete control of your application, the answer may very well be “no”. (If you’re writing a class library, it’s more likely that being thread-safe is important.) If you don’t need thread safety, you may want to implement the add/remove operations to get round the problem of the externally visible lock that C# uses (or may use in the case of 2.0). At that point, the operations become pretty trivial. Here’s the equivalent of the earlier code, but without thread safety.

/// <summary> /// Delegate variable backing the SomeEvent event. /// </summary> SomeEventHandler someEvent;  /// <summary> /// Description for the event /// </summary> public event SomeEventHandler SomeEvent {     add     {         someEvent += value;     }     remove     {         someEvent -= value;     } }  /// <summary> /// Raises the SomeEvent event /// </summary> protected virtual OnSomeEvent(EventArgs e) {     if (someEvent != null)     {         someEvent (this, e);     } }

The check for nullity is due to delegate variables being null when there aren’t any delegate instances to call. One way to make things simpler is to use a no-op delegate instance as the “default” one, which is never removed. At that point, you can just obtain the value of the delegate variable (inside a lock if you’re being thread-safe) and then execute the delegate instance. If there are no “real” delegate targets to call, the no-op target will execute and that’s all that will happen.

Delegate instances: other methods

Earlier we saw how a call to someDelegate(10) is actually a short-hand for someDelegate.Invoke(10). Delegates types may also allow asynchronous behaviour using the BeginInvoke/EndInvoke pair. These are optional as far as the CLI specification is concerned, but C# delegate types always provide them. They follow the same model for asynchronous execution as the rest of .NET, allowing a callback handler to be provided, along with an object to store state information. The delegates are executed on threads created by the system thread-pool.

The first example below operates without a callback, simply using BeginInvoke and EndInvoke from the same thread. This is occasionally useful when a single thread is used for an operation which is synchronous in general, but which contains elements which may be performed in parallel. The methods involved are all static for the sake of simplicity, but delegate instances with specific target objects can also be used, and often are. EndInvoke returns whatever value was returned by the delegate call. If the call threw an exception, the same exception is thrown by EndInvoke.

using System; using System.Threading;  delegate int SampleDelegate(string data);      class AsyncDelegateExample1 {     static void Main()     {         SampleDelegate counter = new SampleDelegate(CountCharacters);         SampleDelegate parser = new SampleDelegate(Parse);                  IAsyncResult counterResult = counter.BeginInvoke ("hello", null, null);         IAsyncResult parserResult = parser.BeginInvoke ("10", null, null);         Console.WriteLine ("Main thread continuing");                  Console.WriteLine ("Counter returned {0}", counter.EndInvoke(counterResult));         Console.WriteLine ("Parser returned {0}", parser.EndInvoke(parserResult));                  Console.WriteLine ("Done");     }          static int CountCharacters (string text)     {         Thread.Sleep (2000);         Console.WriteLine ("Counting characters in {0}", text);         return text.Length;     }          static int Parse (string text)     {         Thread.Sleep (100);         Console.WriteLine ("Parsing text {0}", text);         return int.Parse(text);     } }

The calls to Thread.Sleep are just to demonstrate that the execution really does occur in parallel. The sleep in CountCharacters is as large as it is to force the system thread-pool to run the tasks on two different threads – the thread-pool serializes requests which don’t take long in order to avoid creating more threads than it needs to. By sleeping for a long time, we’re simulating a long-running request. Here’s the output from a sample run:

Main thread continuing Parsing text 10 Counting characters in hello Counter returned 5 Parser returned 10 Done

The calls to EndInvoke block until the delegate has completed in much the same way as calls to Thread.Join block until the threads involved have terminated. The IAsyncResult values returned by the calls to BeginInvoke allows access to the state passed as the last parameter to BeginInvoke, but this isn’t typically used in the style of asynchronous invocation shown above.

The code above is fairly simple, but often not as powerful as a model which uses callbacks after the delegate has completed. Typically, the callback will call EndInvoke to obtain the result of the delegate. Although it is still a theoretically blocking call, it will never actually block because the callback only executes when the delegate has completed anyway. The callback may well use the state provided to BeginInvoke as extra context information. The sample code below uses the same counting and parsing delegates as the previous example, but with a callback displaying the results. The state is used to determine how to format each result, so a single callback can be used for both asynchronous calls. Note the cast from IAsyncResult to AsyncResult: the value provided to the callback is always an instance of AsyncResult, and this can be used to obtain the original delegate instance, so that the callback can call EndInvoke. It is somewhat anomalous that AsyncResult lives in the System.Runtime.Remoting.Messaging namespace when all the other classes involved are in either System or System.Threading, but such is life.

using System; using System.Threading; using System.Runtime.Remoting.Messaging;  delegate int SampleDelegate(string data);      class AsyncDelegateExample2 {     static void Main()     {         SampleDelegate counter = new SampleDelegate(CountCharacters);         SampleDelegate parser = new SampleDelegate(Parse);                  AsyncCallback callback = new AsyncCallback (DisplayResult);                  counter.BeginInvoke ("hello", callback, "Counter returned {0}");         parser.BeginInvoke ("10", callback, "Parser returned {0}");          Console.WriteLine ("Main thread continuing");          Thread.Sleep (3000);         Console.WriteLine ("Done");     }          static void DisplayResult(IAsyncResult result)     {         string format = (string) result.AsyncState;         AsyncResult delegateResult = (AsyncResult) result;         SampleDelegate delegateInstance = (SampleDelegate)delegateResult.AsyncDelegate;                  Console.WriteLine (format, delegateInstance.EndInvoke(result));     }          static int CountCharacters (string text)     {         Thread.Sleep (2000);         Console.WriteLine ("Counting characters in {0}", text);         return text.Length;     }          static int Parse (string text)     {         Thread.Sleep (100);         Console.WriteLine ("Parsing text {0}", text);         return int.Parse(text);     } }

This time almost all the work is done on thread-pool threads. The main thread just kicks off the asynchronous tasks and then sleeps for long enough to let all the work finish. (Thread-pool threads are background threads – without the extra Sleep call, the application would terminate before the delegate calls finished executing.) Some sample output is below – notice how this time, because there is no guaranteed ordering to the calls to EndInvoke, the parser result is displayed before the counter result. In the previous example, the parser almost certainly completed before the counter did, but the main thread waited to obtain the result of the counter first.

Main thread continuing Parsing text 10 Parser returned 10 Counting characters in hello Counter returned 5 Done

Note that you must call EndInvoke when you use asynchronous execution in order to guarantee not to leak memory or handles. Some implementations may not leak, but you shouldn’t rely on this. See my thread-pool article for some sample code to allow “fire and forget” style asynchronous behaviour if this is inconvenient.

Conclusion

Delegates provide a simple way of representing a method call, potentially with a target object, as a piece of data which can be passed around. They are the basis for events, which are effectively conventions for adding and removing handler code to be invoked at appropriate times.

Web Parts in ASP.NET 2.0

February 23, 2008

Web Parts in ASP.NET 2.0

by Jesse Libertyhttp://www.ondotnet.com/pub/a/dotnet/2005/01/10/liberty.html
01/10/2005 In a previous article, I discussed how personalization works. This article will pick up from where that one left off and show you how to use Web Parts to allow your users to further personalize their interactions with your web site.

Getting Started

There have been some small changes since the previous articles were published, and so I suggest you download the updated starter code. Unzip the starter project to any directory you like. It will create a subdirectory called Web Parts. Right click on the subdirectory and choose Sharing and Security. Click on the Web Sharing tab and choose Share this folder. Accept the defaults as offered, as shown in Figure 1.

Figure 1
Figure 1. Sharing the Web Parts directory

Start Visual Studio 2005 Beta 1 and choose File -> Open -> Open Web site. Navigate to the Web Parts directory and click Open. Click Debug (and save the .sln file) and you should be brought to the default page. Log in with the username Jesse (the starter kit includes this user) with the password Jesse. You’re ready to begin to add Web Parts to what had been the Personalization project.

Begin by adding a new page, WebParts.aspx, to your project, and add a link to that page on your default.aspx page.

Creating Zones

A page that uses Web Parts is divided into zones: areas of the page that can contain content. It is typical (though certainly not required) to organize these zones using tables. To see a simple example of this at work, follow these steps:

1. Open the WebParts section of your Toolbox, and drag a WebPartManager onto your page, as shown in Figure 2.

Figure 2
Figure 2. Web Parts toolbox

The job of the WebPartManager is to track and coordinate all the Web Part controls on the page. It will not be visible when the page is running.

2. Add a new table, with two rows and three columns. Rearrange the columns so that they are not of even size.

3. Drag a WebPartZone into each of the six table cells. Each WebPartZone will have a default name (e.g., WebPartZone6) and a default heading. You can easily modify either or both of these properties in the properties window. Resize the WebPartZone controls as appropriate to the cell. Notice that within the zone is a shaded area with the text “Click here to add WebParts to the WebPartZone,” as shown in Figure 3.

Figure 3
Figure 3. Creating zones

Adding Controls To Zones

4. Set the heading on the first Web Part control to News and drag a Label into the zone. The Label is wrapped in a Web Part control, and its title is set to Untitled, as shown in Figure 4.

Figure 4
Figure 4. Adding Controls

5. Switch to source view and change the title of the label to Today’s News and the text to “<br/>Thousands die. Thousands more die at eleven.”. Switch back to design view and drag a list box into WebPartZone3. Set the header text for the WebPartZone to “Sponsors.” Click on the list box, and then on its smart tag to open the ListItemCollection Editor. Add a few items to the list box. Back in source view, set the Title property to “Our Sponsors” and run the application. You’ll need to log in using one of the accounts you set up previously. Click on the link to the Web Parts page. You should see two Web Parts, complete with Minimize and Close commands, as shown in Figure 5.

Figure 5
Figure 5. The Web Parts live

Minimizing and Restoring

Click on the Minimize tag and the contents of the Web Part (e.g., the list box) collapses, and the link changes from “Minimize” to “Restore” as shown in Figure 6.

Figure 6
Figure 6. Closing and restoring

Exit the application. Start it again and sign back in, and navigate back to these pages. Aha! The minimized zone remains minimized. You’ll find that the Web Parts are closely tied with personalization, and each individual’s personalized Web Parts are persisted through the personalization database.

Allow Your Users to Move the Web Parts

Web Parts make it easy for you to allow the user to rearrange the page, placing, for example, News on the right and Sponsors on the left. To do so, drag a WebPartPageMenu control onto your page, as shown in Figure 7.

Figure 7
Figure 7. Adding a menu

Once this is in place, run the application. Log in and navigate to the Web Parts page. Click the drop-down list in the Web Parts Page Manager to set it to Design Page Layout and click the Change button. All of the WebPartZones become visible, and you can drag and drop WebParts from one zone to another by clicking on their titles and dragging them to different zones, as shown in Figure 8, in which you see the Today’s News Web Part being dragged from Zone 1 (upper left) to Zone 4 (lower left).

Figure 8
Figure 8. Movable Web Parts

When you are done, return to the Web Parts Page Manager, set it to Browse This Page and click Change. The changes (moving from one zone to another) are reflected in the page. You may find it interesting to log into this page as another user (no changes reflected) and then again as the first user, to see that the changes are preserved from session to session. In a subsequent article, I’ll look at how you can use Web Parts to create a portal application and how you can modify the Web Parts to create a customized look and feel.

Identifying Object-Oriented Classes By RoyClem(Article is from CodeProject)

February 21, 2008

Introduction

In object-oriented software design (OOD), classes are templates for defining the characteristics and operations of an object. Often, classes and objects are used interchangeably, one synonymous with the other. In actuality, a class is a specification that an object implements.

Identifying classes can be challenging. Poorly chosen classes can complicate the application’s logical structure, reduce reusability, and hinder maintenance. This article provides a brief overview of object-oriented classes and offers tips and suggestions to identify cohesive classes.

Note: The following class diagrams were modeled using Enterprise Architect. Many other modeling tools exist. Use the one that is best suited for your purpose and project.

Classes

Object-oriented classes support the object-oriented principles of abstraction, encapsulation, polymorphism and reusability. They do so by providing a template, or blueprint, that defines the variables and the methods common to all objects that are based on it. Classes specify knowledge (attributes) – they know things – and behavior (methods) – they do things.

Classes are specifications for objects.

Derived from the Use Cases, classes provide an abstraction of the requirements and provide the internal view of the application.

Attributes

Attributes define the characteristics of the class that, collectively, capture all the information about the class. Attributes should be protected by their enclosing class. Unless changed by the class’ behavior, attributes maintain their values.

The type of data that an attribute can contain is determined by its data type. There are two basic data types: Primitive and Derived.

  1. Primitive data types are fundamental types. Examples are integer, string, float.
  2. Derived data types are defined in terms of the Primitive data types, that is, they form new data types by extending the primitive data types. A Student class, for example, is a derived data type formed by a collection of primitive data types.

When defined in the context of a problem domain, derived data types are called Domain Specific Data types. These are the types that define and constrain attributes to be consistent with the semantics of the data. For example, Address studentAddress versus string studentAddress.

Where practical, design models should use domain specific data types in lieu of primitive data types.

When looking for attributes in the design model, look for these types:

  1. Descriptive attributes provide intrinsic information about the class. For example, information about enrollment status, test scores, and education goals would be intrinsic to a Student class but not an Automobile class. Ask, “What characteristics distinguish this class from others?”
  2. Naming attributes are used to uniquely identify an object and typically don’t change during the lifetime of the object. Consider two Student objects that contain the naming attribute, studentName. The values of “Jack” and “Jill” would identify two different Student objects. Ask, “What uniquely identifies this object from another object of the same class?”
  3. Referential attributes contain links to objects. A student’s test scores might be stored in an Assessment class, for example. The value for the Assessment attribute (in the Student class) would link the Student class to the Assessment class. Ask, “How is this object associated with other objects?”

Responsibilities

A class has behaviors and responsibilities. A responsibility is something that a class knows or does…it’s an obligation a class has to know certain information and/or to perform a task. For example, a student knows about her address and SSN. A student does enroll in a class.

Technically, responsibilities are not the same as the class’ operations (behavior), but, operations fulfill the responsibilities. It may take more than one operation (sometimes, more than one object) to fulfill the responsibility.

Responsibility is the obligation of a class or object to perform a task or know information.

Identifying classes

Identifying object-oriented classes is both a skill and an art. It’s a process that one gets better at over time. For example, it’s not unusual for inexperienced designers to identify too many classes. Modeling too many classes results in poor performance, unnecessary complexity and increased maintenance. On the other hand, too few classes tend to increase couplings, and make classes larger and unwieldy. In general, strive for class cohesiveness where behavior is shared between multiple, related classes rather than one very large class.

Cohesive classes reduce coupling, enable extensibility and increase maintainability.

Moreover, classes that seem obvious wind up being poor choices and classes that are initially hidden or that rely on problem domain knowledge wind up as the best choices.

Therefore, begin class modeling by identifying candidate classes – an initial list of classes from which the actual design classes will emerge. Design classes are the classes that are modeled. Candidate classes exist for the sole purpose of deriving the design classes. Initially, there will be a lot of candidate classes – that’s good. However, through analysis, their number will be reduced as they are dropped, combined and merged.

Candidate classes provide the initial impetus to produce cohesive classes.

Candidate classes can be discovered in a variety of ways. Here are three:

  1. Noun and noun phrases: Identify the noun and noun phrases, verbs (actions) and adjectives (attributes) from the Use Cases, Actor-Goal List, Application Narrative and Problem Description.
  2. CRC cards: an informal, group approach to object modeling.
  3. GRASP: A formal set of principles that assign responsibilities.

Each of these methods will yield a list candidate classes. The list won’t be complete nor will every class be appropriate and there will likely be a mix of business and system oriented classes; i.e.; Student and StudentRecord, for example. That’s fine. The goal is to identify the major classes – the obvious ones. Other classes will become apparent as the design process continues.

Once the list has been created, analyze the candidate classes for associations with other classes. Look for collaborating classes. How does each relate to each other and to the business process? Sometimes, it’s helpful to ask, “Why keep this class?” In other words, assume the class is redundant or unnecessary. Keep it only if it plays a collaborating role. Often you’ll find the class’ functionality is accomplished by another class or within the context of another class.

When a class is kept, move it to the list of design classes. Eventually, a list of design classes will result that provides the foundational structure for the application.

Candidate Classes Design Classes
Student Student
Teacher Professor
Class Course
Subject Assessment
Grades
Tests

Design classes will emerge from the analysis of the candidate classes.

Associations are the key to identifying cohesive classes. The following subsections identify the various associations that can exist between classes and suggestions to identify them.

Associations

The classes in an application system don’t exist in a vacuum. Classes are associated with, or related to, other classes. These relationships occur when a class has, uses, knows about, or is acquainted with, one or more classes.

A relationship is an association between classes.

When identifying relationships, start with the class that interacts with as many other classes as possible; perhaps, the core classes of the application. It’s helpful to ask, “Who cares about this class?”, “Who is interested in this class?”, “Why is this class necessary?” Starting with the core classes will quickly identify the other relationships.

Start with core associations.

An association is usually modeled using a solid line that connects two classes.

Most times, a single line doesn’t provide enough information. Form a practice of giving each association a name to clarify the relationship. Use verbs or simple verb phrases as association names.

Association roles

Associations also have roles. Each class in an association has a role that describes its meaning in the relationship. Roles are optional and if, used, should describe the role as a noun. For example, a Professor is an instructor to a Student who is a learner or pupil.

Multiplicity Indicators

A role can have multiplicity – an indication of how many objects participate in the relationship. Multiplicity indicators can be conditional or unconditional.

Examples of multiplicity indicators are:

In Figure 4, the first two indicators (that start with “0…”) are conditional meaning no objects need be present in the relationship. The last two indicators (that start with “1..”) are unconditional meaning at least one object must be present in the relationship. For example:

In Figure 5, a Professor can exist without the existence of a Student. Therefore, the multiplicity for the Student is 0…*. However, the same is not true for the Student. A Student must have at least one Professor. Hence, the 1…* indicator for the Professor.

Multiplicity indicators are also referred to as cardinalities.

Unconditional indicators may impose a referential integrity constraint. Consider the following example:

Class A and class B depend on the existence of the other. Since the multiplicity is unconditional the following is implied:

  1. When class A (or class B) is removed, the corresponding class B (or class A) must also be removed.
  2. When class A (or class B) is added, the corresponding class B (or class A) must also be added.

Unconditional indicators must be checked for referential integrity constraints..

Association class

An association can also possess its own attributes and behavior – just like a class. Sometimes, data exist that does not strictly belong to any of the participating classes. In these cases, an Association class is created to map the data to the participating classes. The class, then, becomes the association. The association class will contain attributes that include pointers, or references, to instances of the two classes.

For example, a Student class has an association to a Course class. A student can take many courses, and a course can be taken by many students. However, who is responsible for the grade? Placing the grade in the Student class gives a student the same grade for all courses. Placing the grade in the Course class gives all students taking the same course the same grade.

The Association class resolves this issue by linking (or mapping) the grade (and other attributes) to the Student and the Course classes. Now, a Student can have many grades for many courses, but each grade in the StudentClassAssociation is associated to a single student and course.

Association classes often occur in many-to-many associations.

Composition

Sometimes a class is composed of other classes. Composition associations form a whole-part relationship. In this relationship, the life of the part depends on the whole. In other words, when the whole is destroyed or removed, the part is also. Moreover, the part cannot belong to more than one whole. This implies that the cardinality of the whole to the part is always “1”.

In a composition association, the whole manages the lifecycle of the part.

To identify composition associations, look for classes that can not exist without other classes. Look for “wholes” and “parts”. Ask, “Is this class part of another class?” For example, a Sentence class is part of a Paragraph class that is part of a Chapter class that is part of a Book class. “Does this class depend on another class?”

The key question to ask, “Is this class destroyed when another class is destroyed?”

Aggregation

Aggregation is a weaker form of a composition. The key difference between an aggregation and a composition is, in an aggregation, the part is not destroyed when the whole is destroyed. In an aggregation relationship, the part may be independent of the whole but the whole requires the part. An automobile, for example, is composed of an engine, chassis, wheels, etc.. The wheels are required for the definition for an automobile, but, they are independent and not necessarily destroyed when the automobile is destroyed. Aggregation is often referred to as a “Has-a” relationship, as in, an Automobile Has-a(n) engine.

To identify aggregation associations, ask, “Is this class part of another class and is it independent of the other class?”

To avoid confusion, when the decision to use the composition/aggregation association is unclear, it’s best to model the relationship as a simple association.

Generalization/Specialization

The generalization/specialization association exists when one class is a specialized version of another class. In this relationship, a common, or base, class forms the foundation for more specialized, or derived, classes. This association is commonly referred to as inheritance because the derived classes inherit the functionality of their base classes to provide specialized behavior.

Inheritance provides the mechanism for new classes to be formed from the attributes and behavior of existing classes.

As base classes are specialized into derived classes, hierarchies are formed that represent is-a or kind-of relationships. For example, an Algebra course is-a specialization of a Math course; a student is a kind-of Person.

To identify inheritance relationships, ask, “Is this class a specialization of a more general class?”

Beware of the tendency to see all associations in terms of inheritance. This leads to complex and deep class hierarchies that are difficult to develop. As a rule of thumb, limit hierarchies to six or fewer levels.

Inheritance is best suited for relatively shallow class hierarchies.

Use Inheritance when:

  • The inheritance hierarchy represents an is-a relationship and not a has-a (composition/aggregate) relationship.
  • The same behavior is applied to different data types.
  • The class hierarchy is reasonably shallow, and unlikely to become much deeper over time.

Interface inheritance

Closely related to inheritance is the concept of interface inheritance. Like an inherited class, an interface provides a common specification for behavior, but, unlike an inherited class, an interface cannot be created. An interface simply specifies common behavior that other classes inherit but implement differently. This implies that unrelated classes can provide independent implementations for the same behavior specification (polymorphism).

For example, the .NET framework provides the IComparable interface that defines a generalized comparison method. This interface is typically used for sorting purposes. Classes that inherit the IComparable interface implement behavior specific to their needs. So, using the same IComparable interface, an Integer class can sort integers, a Byte class can sort bytes, a Student class can sort students, and so on.

The behavior has been abstracted out from any particular class and specifically implemented by all classes that need it.

Use interface inheritance when:

  • Unrelated object types need to provide the same behavior.
  • Multiple inheritance is needed (very difficult to implement using the inheritance association).
  • Inheritance is prohibited. For example, C# structures cannot inherit from classes, but they can implement interfaces.

The Strategy Design Pattern is an excellent candidate for an interface inheritance.

Conclusion

Sometimes, developers don’t know where or how to begin identifying classes. Often classes are simply chosen based on what seems to make sense to the developer without regarding class associations or cohesiveness. As a result, the logical structure for an application can contain classes that are unnecessary and complex making the application hard to extend and maintain. This article provided tips and guidance to identify object-oriented, cohesive classes that work together to accomplish the application’s business function.

Additional links

License

template column find control

February 19, 2008

Label lbl = ((Label)((Infragistics.WebUI.UltraWebGrid.CellItem)((Infragistics.WebUI.UltraWebGrid.TemplatedColumn)row.Cells[5].Column).CellItems[row.Index]).FindControl(“lblAntibioticString”));

forcefully do server postback

February 9, 2008

oEvent.needPostBack = false;

Best site for recursion problems

February 8, 2008

http://erwnerve.tripod.com/prog/recursion/index.htm


Follow

Get every new post delivered to your Inbox.