<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Dotnet786's Weblog</title>
	<atom:link href="http://dotnet786.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://dotnet786.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Thu, 10 Apr 2008 07:01:58 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='dotnet786.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/3328266624ec01edff2a30ae6b324312?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Dotnet786's Weblog</title>
		<link>http://dotnet786.wordpress.com</link>
	</image>
			<item>
		<title>javascript+how to create properties and get whether element is check or not</title>
		<link>http://dotnet786.wordpress.com/2008/04/10/javascripthow-to-create-properties-and-get-whether-element-is-check-or-not/</link>
		<comments>http://dotnet786.wordpress.com/2008/04/10/javascripthow-to-create-properties-and-get-whether-element-is-check-or-not/#comments</comments>
		<pubDate>Thu, 10 Apr 2008 06:56:40 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/?p=15</guid>
		<description><![CDATA[ document.onkeydown = myKeyDownHandler;
 function
myKeyDownHandler(e){
if(event.keyCode==13 ){alert(document.getElementById(&#8216;&#60;%=btnInsertRow.ClientID %&#62;&#8217;).hasFocus);document.getElementById( &#8216;&#60;%=btnInsertRow.ClientID %&#62;&#8217;).focus();


window.onload = function() {
for (i=0; i&#60;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;
   };
}
}

&#60;style type=&#8221;text/css&#8221;&#62;
input, select, textarea, label, button {
   background-color: #FFF;
}
input:focus, select:focus, textarea:focus, label:focus, button:focus {
   background-color: #FEFEFE;
}
&#60;/style&#62;

 

    [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=15&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p> <span style="font-size:x-small;">document.onkeydown = myKeyDownHandler;</span></p>
<p><span style="font-size:x-small;"><span style="font-size:x-small;"> </span></span><span style="font-size:x-small;color:#0000ff;">function<br />
</span><span style="font-size:x-small;">myKeyDownHandler(e){<br />
</span><span style="font-size:x-small;color:#0000ff;">if</span><span style="font-size:x-small;">(</span><span style="font-size:x-small;color:#0000ff;">event</span><span style="font-size:x-small;">.keyCode==13 ){</span><span style="font-size:x-small;"><span style="font-size:x-small;">alert(document.getElementById(</span></span><span style="font-size:x-small;color:#a31515;">&#8216;&lt;%=btnInsertRow.ClientID %&gt;&#8217;</span><span style="font-size:x-small;">).hasFocus);<span style="font-size:x-small;">document.getElementById(</span></span> <span style="font-size:x-small;color:#a31515;">&#8216;&lt;%=btnInsertRow.ClientID %&gt;&#8217;</span><span style="font-size:x-small;">).focus();</span></p>
<div></div>
<p><span style="font-size:x-small;"></p>
<div class="quoteCode">window.onload = function() {<br />
for (i=0; i&lt;form.elements.length-1; i++) {<br />
   elem = document.forms['quick_reply'].elements[i];<br />
   elem.focused = false;<br />
   elem.hasFocus = function() {<br />
      return this.focused;<br />
   };<br />
   elem.onfocus=function() {<br />
      this.focused=true;<br />
   };<br />
   elem.onblur=function() {<br />
      this.focused=false;<br />
   };<br />
}<br />
}</div>
<div class="quoteCode">
<div class="quoteCode">&lt;style type=&#8221;text/css&#8221;&gt;<br />
input, select, textarea, label, button {<br />
   background-color: #FFF;<br />
}<br />
input:<span class="posthilit"><span style="color:#989e00;">focus</span></span>, select:<span class="posthilit"><span style="color:#989e00;">focus</span></span>, textarea:<span class="posthilit"><span style="color:#989e00;">focus</span></span>, label:<span class="posthilit"><span style="color:#989e00;">focus</span></span>, button:<span class="posthilit"><span style="color:#989e00;">focus</span></span> {<br />
   background-color: #FEFEFE;<br />
}<br />
&lt;/style&gt;</div>
</div>
<p> </p>
<p></span></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/15/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/15/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/15/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=15&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/04/10/javascripthow-to-create-properties-and-get-whether-element-is-check-or-not/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>
	</item>
		<item>
		<title>string.format from(http://blog.stevex.net/index.php/string-formatting-in-csharp/)</title>
		<link>http://dotnet786.wordpress.com/2008/04/02/stringformat-fromhttpblogstevexnetindexphpstring-formatting-in-csharp/</link>
		<comments>http://dotnet786.wordpress.com/2008/04/02/stringformat-fromhttpblogstevexnetindexphpstring-formatting-in-csharp/#comments</comments>
		<pubDate>Wed, 02 Apr 2008 13:08:43 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/04/02/stringformat-fromhttpblogstevexnetindexphpstring-formatting-in-csharp/</guid>
		<description><![CDATA[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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=14&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>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 &lt;&lt; “Error ” &lt;&lt; nError &lt;&lt; ” occurred.” &lt;&lt; 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 &#8211; 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 &#8211; 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 &#8211; 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(”-&gt;{1,10}&lt;-”, “Hello”); -&gt; Hello&lt;- String.Format(”-&gt;{1,-10}&lt;-”, “Hello”); -&gt;Hello &lt;- 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 &amp; time December 10, 2002 10:11 PM F Full date &amp; time (long) December 10, 2002 10:11:29 PM g Default date &amp; time 10/12/2002 10:11 PM G Default date &amp; 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 ″.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/14/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/14/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=14&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/04/02/stringformat-fromhttpblogstevexnetindexphpstring-formatting-in-csharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>
	</item>
		<item>
		<title>manually save image file</title>
		<link>http://dotnet786.wordpress.com/2008/02/24/manually-save-image-file/</link>
		<comments>http://dotnet786.wordpress.com/2008/02/24/manually-save-image-file/#comments</comments>
		<pubDate>Sun, 24 Feb 2008 12:59:56 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/02/24/manually-save-image-file/</guid>
		<description><![CDATA[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(&#8220;.gif&#8221;))

// {
// bmp.Save(fs, ImageFormat.Gif);
// }
// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(&#8220;.jpg&#8221;))
// {
// bmp.Save(fs, ImageFormat.Jpeg);
// }
// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(&#8220;.jpeg&#8221;))
// {
// bmp.Save(fs, ImageFormat.Jpeg);
// }
// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(&#8220;.bmp&#8221;))
// {
// bmp.Save(s, ImageFormat.Bmp);
// }
//else [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=13&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font size="2"></font><font size="2" color="#2b91af">Stream</font><font size="2"> s = </font><font size="2" color="#2b91af">File</font><font size="2">.OpenRead(HFilePath.Value);</font><font size="2"><font size="2" color="#0000ff">byte</font><font size="2">[] buffer = </font><font size="2" color="#0000ff">new</font><font size="2"> </font><font size="2" color="#0000ff">byte</font><font size="2">[s.Length];s.Read(buffer, 0, (</font></p>
<p></font><font size="2" color="#0000ff">int</font><font size="2">)s.Length);</font><font size="2"></font><font size="2" color="#2b91af">FileStream</font><font size="2"> fs = </font><font size="2" color="#0000ff">new</font><font size="2"> </font><font size="2" color="#2b91af">FileStream</font><font size="2">(filePath + fileName + fileExtension,</font><font size="2" color="#2b91af">FileMode</font><font size="2">.Create);</font><font size="2">fs.Write(buffer,0,(<font size="2" color="#2b91af">Int32</font><font size="2">)s.Length);<font size="2" color="#008000">// Code to save a File</font></p>
<p></font></p>
<p></font><font size="2"></font><font size="2" color="#2b91af">Bitmap</font><font size="2"> bmp = </font><font size="2" color="#0000ff">new</font><font size="2"> </font><font size="2" color="#2b91af">Bitmap</font><font size="2">(fs);</font><font size="2">bmp.Save(fs, <font size="2" color="#2b91af">ImageFormat</font><font size="2">.Gif);<font size="2" color="#008000">// if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(&#8220;.gif&#8221;))</font></p>
<p></font></p>
<p></font><font size="2"><font size="2" color="#008000">// {</font></p>
<p></font><font size="2"><font size="2" color="#008000">// bmp.Save(fs, ImageFormat.Gif);</font></p>
<p></font><font size="2"><font size="2" color="#008000">// }</font></p>
<p></font><font size="2"><font size="2" color="#008000">// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(&#8220;.jpg&#8221;))</font></p>
<p></font><font size="2"><font size="2" color="#008000">// {</font></p>
<p></font><font size="2"><font size="2" color="#008000">// bmp.Save(fs, ImageFormat.Jpeg);</font></p>
<p></font><font size="2"><font size="2" color="#008000">// }</font></p>
<p></font><font size="2"><font size="2" color="#008000">// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(&#8220;.jpeg&#8221;))</font></p>
<p></font><font size="2"><font size="2" color="#008000">// {</font></p>
<p></font><font size="2"><font size="2" color="#008000">// bmp.Save(fs, ImageFormat.Jpeg);</font></p>
<p></font><font size="2"><font size="2" color="#008000">// }</font></p>
<p></font><font size="2"><font size="2" color="#008000">// else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(&#8220;.bmp&#8221;))</font></p>
<p></font><font size="2"><font size="2" color="#008000">// {</font></p>
<p></font><font size="2"><font size="2" color="#008000">// bmp.Save(s, ImageFormat.Bmp);</font></p>
<p></font><font size="2"><font size="2" color="#008000">// }</font></p>
<p></font><font size="2"><font size="2" color="#008000">//else if (System.IO.Path.GetExtension(HFilePath.Value).ToLower().Equals(&#8220;.png&#8221;))</font></p>
<p></font><font size="2"><font size="2" color="#008000">// {</font></p>
<p></font><font size="2"><font size="2" color="#008000">// bmp.Save(s, ImageFormat.Bmp);</font></p>
<p></font><font size="2"><font size="2" color="#008000">// }</font></p>
<p></font></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=13&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/02/24/manually-save-image-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>
	</item>
		<item>
		<title>Delegates and Events</title>
		<link>http://dotnet786.wordpress.com/2008/02/23/delegates-and-events-2/</link>
		<comments>http://dotnet786.wordpress.com/2008/02/23/delegates-and-events-2/#comments</comments>
		<pubDate>Sat, 23 Feb 2008 16:40:05 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[CSharp 2.0]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/02/23/delegates-and-events-2/</guid>
		<description><![CDATA[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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=12&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2><a href="http://www.codeproject.com/KB/cs/delegates-part1.aspx">http://www.codeproject.com/KB/cs/delegates-part1.aspx</a></h2>
<h2>Introduction</h2>
<p>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#.</p>
<h2>Events</h2>
<p>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.</p>
<h2>Delegates</h2>
<p>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.</p>
<p>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.</p>
<h2>Types of Delegates</h2>
<p>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.</p>
<p>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.</p>
<h3>Single Cast delegate</h3>
<p>The signature of a single cast delegate is shown below. The letters in italics can be replaced with your own names and parameters.</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">delegate</span> <span class="code-SDKkeyword">Boolean</span> <i> DelegateName (parm1, parm2)</i></pre>
</div>
<p>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.</p>
<p>As an example let us create a single cast delegate named MyDelegate which would point to a function MyFunction. The code appears as below,</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">delegate</span> <span class="code-SDKkeyword">Boolean</span> MyDelegate(<span class="code-SDKkeyword">Object</span> sendingobj, <span class="code-SDKkeyword">Int32</span> x);  <span class="code-keyword">public</span> <span class="code-keyword">class</span> TestDelegateClass {      	<span class="code-SDKkeyword">Boolean</span> MyFunction(<span class="code-SDKkeyword">Object</span> sendingobj, <span class="code-SDKkeyword">Int32</span> x)  	{            		<span class="code-comment">//</span><span class="code-comment">Perform some processing            </span>		<span class="code-keyword">return</span> (<span class="code-keyword">true</span>);   	} 	        	<span class="code-keyword">public</span> <span class="code-keyword">static</span> <span class="code-keyword">void</span> main(<span class="code-SDKkeyword">String</span> [] args) 	{ 		<span class="code-comment">//</span><span class="code-comment">Instantiate the delegate passing the method to invoke in its constructor </span>		MyDelegate mdg = <span class="code-keyword">new</span> MyDelegate(MyFunction);              		<span class="code-comment">//</span><span class="code-comment"> Construct an instance of this class </span>		TestDelegateClass tdc = <span class="code-keyword">new</span> TestDelegateClass();                 		<span class="code-comment">//</span><span class="code-comment"> The following line will call MyFunction </span>		<span class="code-SDKkeyword">Boolean</span> f = mdg(<span class="code-keyword">this</span>, <span class="code-digit">1</span>);         	} }</pre>
</div>
<p>How does the above code work?</p>
<p>The System.Delegate contains a few fields. The most important of them are Target and Method.</p>
<p>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.</p>
<p>The Method field identifies the method to be called. This field always has some value. It is never null.</p>
<p>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.</p>
<p>In the code sample above we saw,</p>
<div class="no-vmads">
<pre><span class="code-SDKkeyword">Boolean</span> f = mdg(<span class="code-keyword">this</span>, <span class="code-digit">1</span>);</pre>
</div>
<p>When the compiler comes across this line, this is what happens,</p>
<ol>
<li>The compiler identifies that mdg is a delegate object.</li>
<li>The delegate object has the target and method fields as described above.</li>
<li>The compiler generates code that calls the Invoke method of the <strong>System.Delegate</strong> derived class i.e <strong>MyDelegate</strong>.</li>
<li>The Invoke method internally uses the <strong>MethodInfo</strong> type identified by the delegate&#8217;s <strong>Method</strong> field and calls the <strong>MethoidInfo</strong>&#8217;s invoke method.</li>
<li>The <strong>MethodInfo</strong>&#8217;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 <strong>Int32</strong> value.</li>
</ol>
<p>The above discussion would have made you clear about what happens internally when a method gets called through a Single Cast delegate.</p>
<h2>Multi Cast delegate</h2>
<p>The signature of a mutli cast delegate is shown below. The letters in italics can be replaced with your own names and parameters.</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">delegate</span> <span class="code-keyword">void</span> <i>DelegateName (parm1, parm2)</i></pre>
</div>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">static</span> Delegate Combine(Delegate a, Delegate b);</pre>
</div>
<p>What the above method does is that it combines the two delegates a and b and makes b&#8217;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.</p>
<p>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,</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">static</span> Delegate Remove(Delegate source, Delegate <span class="code-keyword">value</span>);</pre>
</div>
<p>Here&#8217;s a small sample that illustrates the use of a multi cast delegate,</p>
<div style="width:100%;" class="precollapse"><img width="9" src="http://www.codeproject.com/images/minus.gif" height="9" style="cursor:pointer;" /><span style="margin-bottom:0;cursor:pointer;"> Collapse</span></div>
<div style="margin-top:0;" class="no-vmads">
<pre><span class="code-keyword">using</span> System;  <span class="code-keyword">class</span> MCD1 {     <span class="code-keyword">public</span> <span class="code-keyword">void</span> dispMCD1(<span class="code-SDKkeyword">string</span> s)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">MCD1"</span>);     } }  <span class="code-keyword">class</span> MCD2 {      <span class="code-keyword">public</span> <span class="code-keyword">void</span> dispMCD2(<span class="code-SDKkeyword">string</span> s)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">MCD2"</span>);     } }     <span class="code-keyword">public</span> <span class="code-keyword">delegate</span> <span class="code-keyword">void</span> OnMsgArrived(<span class="code-SDKkeyword">string</span> s);  <span class="code-keyword">class</span> TestMultiCastUsingDelegates {     <span class="code-keyword">public</span> <span class="code-keyword">static</span> <span class="code-keyword">void</span> Main(<span class="code-SDKkeyword">string</span> [] args)     {         MCD1 mcd1=new MCD1();         MCD2 mcd2=new MCD2();         <span class="code-comment">//</span><span class="code-comment"> Create a delegate to point to dispMCD1 of mcd1 object </span>        OnMsgArrived oma=new OnMsgArrived(mcd1.dispMCD1);          <span class="code-comment">//</span><span class="code-comment"> Create a delegate to point to dispMCD2 of mcd2 object </span>        OnMsgArrived omb=new OnMsgArrived(mcd2.dispMCD2);           OnMsgArrived omc;         <span class="code-comment">//</span><span class="code-comment"> Combine the two created delegates. Now omc would point to the head of a linked list </span>        <span class="code-comment">//</span><span class="code-comment"> of delegates </span>        omc=(OnMsgArrived)Delegate.Combine(oma,omb);           Delegate [] omd;          <span class="code-comment">//</span><span class="code-comment"> Obtain the array of delegate references by invoking GetInvocationList() </span>        omd=omc.GetInvocationList();            OnMsgArrived ome;         <span class="code-comment">//</span><span class="code-comment"> Now navigate through the array and call each delegate which in turn would call each of the </span>        <span class="code-comment">//</span><span class="code-comment"> methods </span>        <span class="code-keyword">for</span>(<span class="code-keyword">int</span> i=0;i<span class="code-keyword">&lt;</span>omd.Length;i++)         {             <span class="code-comment">//</span><span class="code-comment"> Now call each of the delegates </span>            ome=(OnMsgArrived)omd[i];             ome(<span class="code-string">"</span><span class="code-string">string"</span>);         }     } }</pre>
</div>
<p>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.</p>
<h2>Problem Scenario</h2>
<p>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 &#8220;Button Clicked&#8221; will appear.</p>
<p>Compilation directions: Compile using</p>
<div class="no-vmads">
<pre>csc /r:System.DLL;System.WinForms.DLL;Microsoft.Win32.Interop.DLL FormTest.cs</pre>
</div>
<div style="width:100%;" class="precollapse"><img width="9" src="http://www.codeproject.com/images/minus.gif" height="9" style="cursor:pointer;" /><span style="margin-bottom:0;cursor:pointer;"> Collapse</span></div>
<div style="margin-top:0;" class="no-vmads">
<pre><span class="code-comment">/*</span><span class="code-comment"> Creating a form and adding a button to it and associating the button with an event handler */</span> <span class="code-keyword">using</span> System; <span class="code-keyword">using</span> System.WinForms; <span class="code-keyword">public</span> <span class="code-keyword">class</span> FormTest : Form {     <span class="code-comment">//</span><span class="code-comment">Create a button </span>    <span class="code-keyword">private</span> Button button1 = <span class="code-keyword">new</span> Button();     <span class="code-keyword">public</span> <span class="code-keyword">static</span> <span class="code-keyword">void</span> Main (<span class="code-SDKkeyword">string</span> [] args)     {         <span class="code-comment">//</span><span class="code-comment">Run the application </span>        Application.Run(<span class="code-keyword">new</span> FormTest());     }          <span class="code-keyword">public</span> FormTest()     {         <span class="code-comment">//</span><span class="code-comment">Set up the Form </span>        <span class="code-keyword">this</span>.Text = <span class="code-string">"</span><span class="code-string">Hello WinForms World"</span>;         <span class="code-comment">//</span><span class="code-comment">Set up the button </span>        button1.Text = <span class="code-string">"</span><span class="code-string">Click Me!"</span>;         <span class="code-comment">//</span><span class="code-comment">Register the event handler </span>        button1.AddOnClick(<span class="code-keyword">new</span> System.EventHandler(buttonClicked));         <span class="code-comment">//</span><span class="code-comment">Add the controls to the form </span>        <span class="code-keyword">this</span>.Controls.Add(button1);     }       <span class="code-comment">//</span><span class="code-comment">The event handling method </span>    <span class="code-keyword">private</span> <span class="code-keyword">void</span> buttonClicked(<span class="code-SDKkeyword">object</span> sender, EventArgs evArgs)     {         MessageBox.Show(<span class="code-string">"</span><span class="code-string">Button clicked"</span>);     } }</pre>
</div>
<p>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 &#8220;Button clicked&#8221; is displayed.</p>
<h2>Components of the Exercise</h2>
<p>This section will talk about the components that would complete the architecture,</p>
<h3>1. Delegate Event Handler</h3>
<p>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.</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">delegate</span> <span class="code-keyword">void</span> ButtonEventHandler(<span class="code-SDKkeyword">object</span> sender, ButtonEventArgs e);</pre>
</div>
<p>Parameters</p>
<p>sender &#8211; Identifies the origin of the event</p>
<p>ButtonEventArgs &#8211; 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.</p>
<h3>2. EventArgs derived class</h3>
<p>The reason for using a derived class for EventArgs has been mentioned in the previous point. The class looks like this:</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">class</span> ButtonEventArgs : EventArgs {       	<span class="code-keyword">public</span> <span class="code-SDKkeyword">string</span> msg; <span class="code-comment">//</span><span class="code-comment">identifies the action </span>	<span class="code-keyword">public</span> ButtonEventArgs(<span class="code-SDKkeyword">string</span> message) 	{ 		msg=message;   	} }</pre>
</div>
<h3>3. A button class</h3>
<p>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&lt;Event Name&gt; and RemoveOn&lt;Event Name&gt; 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,</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">void</span> AddOnClick(ButtonEventHandler handler); <span class="code-keyword">public</span> <span class="code-keyword">void</span> RemoveOnClick(ButtonEventHandler handler); <span class="code-keyword">public</span> <span class="code-keyword">void</span> AddOnPress(ButtonEventHandler handler); <span class="code-keyword">public</span> <span class="code-keyword">void</span> RemoveOnPress(ButtonEventHandler handler);</pre>
</div>
<p>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.</p>
<p>Now what is required? The most important part, methods that raises the events. The naming conventions followed for such methods are On&lt;Event Name&gt;. 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.</p>
<p>The signature of the mehods will be as follows,</p>
<div class="no-vmads">
<pre><span class="code-keyword">protected</span> <span class="code-keyword">virtual</span> <span class="code-keyword">void</span> OnPress(ButtonEventArgs e); <span class="code-keyword">protected</span> <span class="code-keyword">virtual</span> <span class="code-keyword">void</span> OnClick(ButtonEventArgs e);</pre>
</div>
<p>Why are the above two methods declared as protected? To help the subclasses override this event without attaching a delegate to it.</p>
<p>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,</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">void</span> click(); <span class="code-keyword">public</span> <span class="code-keyword">void</span> press();</pre>
</div>
<p>Now let us take a look at the whole button class,</p>
<div style="width:100%;" class="precollapse"><img width="9" src="http://www.codeproject.com/images/minus.gif" height="9" style="cursor:pointer;" /><span style="margin-bottom:0;cursor:pointer;"> Collapse</span></div>
<div style="margin-top:0;" class="no-vmads">
<pre><span class="code-keyword">class</span> button {     <span class="code-keyword">private</span> ButtonEventHandler beh=null; <span class="code-comment">//</span><span class="code-comment"> For click </span>    <span class="code-keyword">private</span> ButtonEventHandler bep=null; <span class="code-comment">//</span><span class="code-comment"> For press </span>      <span class="code-keyword">public</span> <span class="code-keyword">void</span> AddOnClick(ButtonEventHandler handler)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">Adding click event handler"</span>);         beh=(ButtonEventHandler)Delegate.Combine(beh, handler);     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> RemoveOnClick(ButtonEventHandler handler)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">Removing click event handler"</span>);         beh=(ButtonEventHandler)Delegate.Remove(beh, handler);     }       <span class="code-keyword">protected</span> <span class="code-keyword">virtual</span> <span class="code-keyword">void</span> OnClick(ButtonEventArgs e)     {         <span class="code-keyword">if</span> (beh!=null)         {         beh(<span class="code-keyword">this</span>, e);         }     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> AddOnPress(ButtonEventHandler handler)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">Adding Press Event handler"</span>);         bep=(ButtonEventHandler)Delegate.Combine(bep, handler);     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> RemoveOnPress(ButtonEventHandler handler)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">Removing Press Event handler"</span>);         bep=(ButtonEventHandler)Delegate.Remove(bep, handler);     }       <span class="code-keyword">protected</span> <span class="code-keyword">virtual</span> <span class="code-keyword">void</span> OnPress(ButtonEventArgs e)     {         <span class="code-keyword">if</span> (bep!=null)         {         bep(<span class="code-keyword">this</span>, e);         }     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> click()     {         ButtonEventArgs bea=new ButtonEventArgs(<span class="code-string">"</span><span class="code-string">clicked"</span>);         OnClick(bea);     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> press()     {         ButtonEventArgs bea=new ButtonEventArgs(<span class="code-string">"</span><span class="code-string">pressed"</span>);         OnPress(bea);     } }</pre>
</div>
<p>Now let us begin a line by line walkthrough of the above code,</p>
<div class="no-vmads">
<pre><span class="code-keyword">private</span> ButtonEventHandler beh=null; <span class="code-comment">//</span><span class="code-comment"> For click </span><span class="code-keyword">private</span> ButtonEventHandler bep=null; <span class="code-comment">//</span><span class="code-comment"> For press</span></pre>
</div>
<p>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.</p>
<div class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">void</span> AddOnClick(ButtonEventHandler handler) {    Console.WriteLine(<span class="code-string">"</span><span class="code-string">Adding click event handler"</span>);        beh=(ButtonEventHandler)Delegate.Combine(beh, handler); }</pre>
</div>
<p>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,</p>
<div class="no-vmads">
<pre>beh ------<span class="code-keyword">&gt;</span> ButtonEventHandler1 -----<span class="code-keyword">&gt;</span> &amp;Fn1()                               ButtonEventHandler2 -----<span class="code-keyword">&gt;</span> &amp;Fn2()             ButtonEventHandler3 -----<span class="code-keyword">&gt;</span> &amp;Fn3()             ButtonEventHandler4 -----<span class="code-keyword">&gt;</span> &amp;Fn4()</pre>
</div>
<p>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.</p>
<p>The same explanation applies to RemoveOn methods.</p>
<h4><font color="#ff9900">4. The Form Simulation</font></h4>
<p>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.</p>
<p>The code for the client class is as follows,</p>
<div style="width:100%;" class="precollapse"><img width="9" src="http://www.codeproject.com/images/minus.gif" height="9" style="cursor:pointer;" /><span style="margin-bottom:0;cursor:pointer;"> Collapse</span></div>
<div style="margin-top:0;" class="no-vmads">
<pre><span class="code-keyword">public</span> <span class="code-keyword">class</span> DelegatesAndEvents {     <span class="code-comment">//</span><span class="code-comment">Declare the simulated button class </span>    <span class="code-keyword">private</span> button button1=new button();       <span class="code-comment">//</span><span class="code-comment">Have a private constrcutor </span>    <span class="code-keyword">private</span> DelegatesAndEvents()     {         <span class="code-comment">/*</span><span class="code-comment">         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         */</span>         button1.AddOnClick(<span class="code-keyword">new</span> ButtonEventHandler(ClickEventHandler1));         button1.AddOnClick(<span class="code-keyword">new</span> ButtonEventHandler(ClickEventHandler2));         button1.AddOnClick(<span class="code-keyword">new</span> ButtonEventHandler(ClickEventHandler3));         button1.AddOnPress(<span class="code-keyword">new</span> ButtonEventHandler(PressEventHandler));         button1.click();         button1.press();     }       <span class="code-keyword">public</span> <span class="code-keyword">static</span> <span class="code-keyword">void</span> Main(<span class="code-SDKkeyword">String</span> [] args)     {         DelegatesAndEvents d=new DelegatesAndEvents();     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> ClickEventHandler1(<span class="code-SDKkeyword">object</span> sender, ButtonEventArgs e)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">click event handler1"</span>);         Console.WriteLine(e.msg);         Console.WriteLine(<span class="code-string">"</span><span class="code-string">after"</span>);     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> ClickEventHandler2(<span class="code-SDKkeyword">object</span> sender, ButtonEventArgs e)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">click event handler2"</span>);         Console.WriteLine(e.msg);         Console.WriteLine(<span class="code-string">"</span><span class="code-string">after"</span>);     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> ClickEventHandler3(<span class="code-SDKkeyword">object</span> sender, ButtonEventArgs e)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">click event handler3"</span>);         Console.WriteLine(e.msg);         Console.WriteLine(<span class="code-string">"</span><span class="code-string">after"</span>);     }       <span class="code-keyword">public</span> <span class="code-keyword">void</span> PressEventHandler(<span class="code-SDKkeyword">object</span> sender, ButtonEventArgs e)     {         Console.WriteLine(<span class="code-string">"</span><span class="code-string">press event handler"</span>);         Console.WriteLine(e.msg);         Console.WriteLine(<span class="code-string">"</span><span class="code-string">after"</span>);     } }</pre>
</div>
<h3>Output</h3>
<p><img border="0" width="657" src="http://dotnet786.wordpress.com/wp-admin/Delegates-Part1/delega1.gif" height="439" /></p>
<h2>Conclusion</h2>
<p>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.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/12/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/12/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=12&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/02/23/delegates-and-events-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>

		<media:content url="http://www.codeproject.com/images/minus.gif" medium="image" />

		<media:content url="http://www.codeproject.com/images/minus.gif" medium="image" />

		<media:content url="http://www.codeproject.com/images/minus.gif" medium="image" />

		<media:content url="http://www.codeproject.com/images/minus.gif" medium="image" />

		<media:content url="http://dotnet786.wordpress.com/wp-admin/Delegates-Part1/delega1.gif" medium="image" />
	</item>
		<item>
		<title>Delegates and events</title>
		<link>http://dotnet786.wordpress.com/2008/02/23/delegates-and-events/</link>
		<comments>http://dotnet786.wordpress.com/2008/02/23/delegates-and-events/#comments</comments>
		<pubDate>Sat, 23 Feb 2008 16:29:11 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/02/23/delegates-and-events/</guid>
		<description><![CDATA[Delegates and events
People often find it difficult to see the difference between events and delegates. C# doesn&#8217;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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=11&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h1>Delegates and events</h1>
<p>People often find it difficult to see the difference between events and delegates. C# doesn&#8217;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 &#8220;delegate&#8221;. Sometimes it is used to mean a delegate <i>type</i>, and at other times it can be used to mean an <i>instance</i> of a delegate type. I&#8217;ll use &#8220;delegate type&#8221; and &#8220;delegate instance&#8221; to distinguish between them, and &#8220;delegate&#8221; when talking about the whole topic in a general sense.</p>
<h2>Delegate types</h2>
<p>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.</p>
<p>Delegates types are declared with the <code>delegate</code> keyword. They can appear either on their own or nested within a class, as shown below.</p>
<table class="code">
<tr>
<td>
<pre><span class="Namespace">namespace</span> DelegateArticle {     <span class="Modifier">public</span> <span class="ReferenceType">delegate</span> <span class="ReferenceType">string</span> FirstDelegate (<span class="ValueType">int</span> x);          <span class="Modifier">public</span> <span class="ReferenceType">class</span> Sample     {         <span class="Modifier">public</span> <span class="ReferenceType">delegate</span> <span class="ValueType">void</span> SecondDelegate (<span class="ValueType">char</span> a, <span class="ValueType">char</span> b);     } }</pre>
</td>
</tr>
</table>
<p>This code declares two delegate types. The first is <code>DelegateArticle.FirstDelegate</code> which has a single parameter of type <code>int</code> and returns a <code>string</code>. The second is <code>DelegateArticle.Sample.SecondDelegate</code> which has two <code>char</code> parameters, and doesn&#8217;t return anything (because the return type is specified as <code>void</code>).</p>
<p>Note that the <code>delegate</code> keyword doesn&#8217;t always mean that a delegate type is being declared. As we&#8217;ll see in a moment, the same keyword is used when creating instances of the delegate type.</p>
<p>The types declared here derive from <code>System.MulticastDelegate</code>, which in turn derives from <code>System.Delegate</code>. In practice, you&#8217;ll only see delegate types deriving from <code>MulticastDelegate</code>. The difference between <code>Delegate</code> and <code>MulticastDelegate</code> is largely historical; in betas of .NET 1.0 the difference was significant (and annoying) &#8211; 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&#8217;re only one type.</p>
<p>Any delegate type you create has the members inherited from its parent types, one constructor with parameters of <code>object</code> and <code>IntPtr</code> and three extra methods: <code>Invoke</code>, <code>BeginInvoke</code> and <code>EndInvoke</code>. We&#8217;ll come back to the constructor in a minute. The methods can&#8217;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:</p>
<table class="code">
<tr>
<td>
<pre>     <span class="Modifier">public</span> <span class="ReferenceType">string</span> Invoke (<span class="ValueType">int</span> x); <span class="Modifier">public</span> System.IAsyncResult BeginInvoke(<span class="ValueType">int</span> x, System.AsyncCallback callback, <span class="ReferenceType">object</span> state); <span class="Modifier">public</span> <span class="ReferenceType">string</span> Endinvoke(IAsyncResult result);</pre>
</td>
</tr>
</table>
<p>As you can see, the return type of <code>Invoke</code> and <code>EndInvoke</code> matches that of the declaration signature, as are the parameters of <code>Invoke</code> and the first parameters of <code>BeginInvoke</code>. We&#8217;ll see the purpose of <code>Invoke</code> in the next section, and cover <code>BeginInvoke</code> and <code>EndInvoke</code> in the <a href="http://dotnet786.wordpress.com/wp-admin/#advanced">section on advanced usage</a>. It&#8217;s a bit premature to talk about calling methods when we don&#8217;t know how to create an instance, however. We&#8217;ll cover that (and more) in the next section.</p>
<h2>Delegate instances: the basics</h2>
<p>Now we know how a delegate type is declared and what it contains, let&#8217;s look at how to create an instance of such a type, and what we can do with it.</p>
<h3>Creating delegate instances</h3>
<p>Note: this article doesn&#8217;t cover the features of C# 2.0 and 3.0 for creating delegate instances. I cover the C# 2.0 features in my <a href="http://dotnet786.wordpress.com/wp-admin/csharp2/delegates.html">article about C# 2.0</a>. When I eventually get round to writing about C# 3.0, I&#8217;m sure I&#8217;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&#8217;s going on under the hood. When you understand the basics, it&#8217;s clearly worth knowing the features these later versions provide &#8211; but if you try to use them without having a firm grasp on the basics, you may well get confused.</p>
<p>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 <i>target</i>). 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 <code>System.Delegate</code> for more information on this if you&#8217;re interested, but don&#8217;t worry too much about it &#8211; it&#8217;s largely irrelevant from a C# point of view. C# only supports creating what MSDN calls a <i>closed instance delegate</i> type.</p>
<p>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 <i>delegate-creation-expression</i> which is of the form <code>new delegate-type (expression)</code>. The expression must either be another delegate of the same type (or a compatible delegate type in C# 2.0) or a <i>method group</i> &#8211; 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:</p>
<table class="code">
<tr>
<td>
<pre><span class="InlineComment">// The following two creation expressions are equivalent,</span> <span class="InlineComment">// where InstanceMethod is an instance method in the class</span> <span class="InlineComment">// containing the creation expression (or a base class). </span> <span class="InlineComment">// The target is "this".</span> FirstDelegate d1 = <span class="Keyword">new</span> FirstDelegate(InstanceMethod); FirstDelegate d2 = <span class="Keyword">new</span> FirstDelegate(<span class="Keyword">this</span>.InstanceMethod);  <span class="InlineComment">// Here we create a delegate instance referring to the same method</span> <span class="InlineComment">// as the first two examples, but with a different target.</span> FirstDelegate d3 = <span class="Keyword">new</span> FirstDelegate(anotherInstance.InstanceMethod);  <span class="InlineComment">// This delegate instance uses an instance method in a different class,</span> <span class="InlineComment">// specifying the target to call the method on</span> FirstDelegate d4 = <span class="Keyword">new</span> FirstDelegate(instanceOfOtherClass.OtherInstanceMethod);  <span class="InlineComment">// This delegate instance uses a static method in ths class containing</span> <span class="InlineComment">// the creation expression (or a base class).</span> FirstDelegate d5 = <span class="Keyword">new</span> FirstDelegate(StaticMethod);  <span class="InlineComment">// This delegate instance uses a static method in a different class</span> FirstDelegate d6 = <span class="Keyword">new</span> FirstDelegate(OtherClass.OtherStaticMethod);</pre>
</td>
</tr>
</table>
<p>The constructor we mentioned earlier has two parameters &#8211; an <code>object</code> and an <code>IntPtr</code>. The <code>object</code> is a reference to the target (or <code>null</code> for static methods) and the <code>IntPtr</code> is a pointer to the method itself.</p>
<p>One point to note is that delegate instances can refer to methods and targets which wouldn&#8217;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 <i>creating</i> 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&#8230;</p>
<h3>Calling delegate instances</h3>
<p>Delegate instances are called just as if they were the methods themselves. For instance, to call the delegate referred to by variable <code>d1</code> above, we could write:</p>
<table class="code">
<tr>
<td>
<pre><span class="ReferenceType">string</span> result = d1(10);</pre>
</td>
</tr>
</table>
<p>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&#8217;s a program which gives one example of a static method and one of an instance method. <code>DelegateTest.StaticMethod</code> could be written as just <code>StaticMethod</code> in the same way that (within an instance method) you could write <code>InstanceMethod</code> instead of <code>this.InstanceMethod</code> &#8211; I&#8217;ve included the class name just to make it clear how you would reference methods from other classes.</p>
<table class="code">
<tr>
<td>
<pre><span class="Namespace">using</span> System;  <span class="Modifier">public</span> <span class="ReferenceType">delegate</span> <span class="ReferenceType">string</span> FirstDelegate (<span class="ValueType">int</span> x);      <span class="ReferenceType">class</span> DelegateTest {         <span class="ReferenceType">string</span> name;          <span class="Modifier">static</span> <span class="ValueType">void</span> Main()     {         FirstDelegate d1 = <span class="Keyword">new</span> FirstDelegate(DelegateTest.StaticMethod);                  DelegateTest instance = <span class="Keyword">new</span> DelegateTest();         instance.name = <span class="String">"My instance"</span>;         FirstDelegate d2 = <span class="Keyword">new</span> FirstDelegate(instance.InstanceMethod);                  Console.WriteLine (d1(10)); <span class="InlineComment">// Writes out "Static method: 10"</span>         Console.WriteLine (d2(5));  <span class="InlineComment">// Writes out "My instance: 5"</span>     }          <span class="Modifier">static</span> <span class="ReferenceType">string</span> StaticMethod (<span class="ValueType">int</span> i)     {         <span class="Statement">return</span> <span class="ReferenceType">string</span>.Format (<span class="String">"Static method: {0}"</span>, i);     }      <span class="ReferenceType">string</span> InstanceMethod (<span class="ValueType">int</span> i)     {         <span class="Statement">return</span> <span class="ReferenceType">string</span>.Format (<span class="String">"{0}: {1}"</span>, name, i);     } }</pre>
</td>
</tr>
</table>
<p>The C# syntax is just a short-hand for calling the <code>Invoke</code> method provided by each delegate type. Delegates can also be run asynchronously if they provide <code>BeginInvoke</code>/<code>EndInvoke</code> methods. These are explained <a href="http://dotnet786.wordpress.com/wp-admin/#advanced">later</a>.</p>
<h3>Combining delegates</h3>
<p>Delegates can be combined such that when you call the delegate, a whole list of methods are called &#8211; potentially with different targets. When I said before that a delegate contained a target and a method, that was a slight simplification. That&#8217;s what a delegate instance representing one method contains. For the sake of clarity, I&#8217;ll refer to such delegate instances as <i>simple delegates</i>. 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&#8217;ll call these <i>combined delegates</i>. Combined delegates can themselves be combined together, effectively creating one big list of simple delegates in the obvious fashion.</p>
<p>It&#8217;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 <code>String.PadLeft</code> for instance, it doesn&#8217;t actually change the string you call it on &#8211; it just returns a new string with the appropriate padding.</p>
<p>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 <i>lists</i>. If the list to subtract is not found in the original list, the result is just the original list. Otherwise, the <i>last</i> occurrence of the list is removed. This is best shown with some examples. Instead of actual code, the following uses lists of simple delegates <code>d1</code>, <code>d2</code> etc. For instance, <code>[d1, d2, d3]</code> is a combined delegate which, when executed, would call <code>d1</code> then <code>d2</code> then <code>d3</code>. An empty list is represented by <code>null</code> rather than an actual delegate instance.</p>
<table border="1">
<tr>
<th>Expression</th>
<th>Result</th>
</tr>
<tr>
<td>null + d1</td>
<td>d1</td>
</tr>
<tr>
<td>d1 + null</td>
<td>d1</td>
</tr>
<tr>
<td>d1 + d2</td>
<td>[d1, d2]</td>
</tr>
<tr>
<td>d1 + [d2, d3]</td>
<td>[d1, d2, d3]</td>
</tr>
<tr>
<td>[d1, d2] + [d2, d3]</td>
<td>[d1, d2, d2, d3]</td>
</tr>
<tr>
<td>[d1, d2] &#8211; d1</td>
<td>d2</td>
</tr>
<tr>
<td>[d1, d2] &#8211; d2</td>
<td>d1</td>
</tr>
<tr>
<td>[d1, d2, d1] &#8211; d1</td>
<td>[d1, d2]</td>
</tr>
<tr>
<td>[d1, d2, d3] &#8211; [d1, d2]</td>
<td>d3</td>
</tr>
<tr>
<td>[d1, d2, d3] &#8211; [d2, d1]</td>
<td>[d1, d2, d3]</td>
</tr>
<tr>
<td>[d1, d2, d3, d1, d2] &#8211; [d1, d2]</td>
<td>[d1, d2, d3]</td>
</tr>
<tr>
<td>[d1, d2] &#8211; [d1, d2]</td>
<td>null</td>
</tr>
</table>
<p>Delegate instances can also be combined with the static <code>Delegate.Combine</code> method, and one can be subtracted from another with the static <code>Delegate.Remove</code> method. The C# compiler converts the addition and subtraction operators into calls to these methods. Because they are static methods, they work easily with <code>null</code> references.</p>
<p>The addition and subtraction operators always work as part of assignment: <code>d1 += d2;</code> is exactly equivalent to <code>d1 = d1+d2;</code>, and likewise for subtraction. Again, the original delegate instance remains unchanged; the value of <code>d1</code> just changes to be a reference to the appropriate new combined delegate.</p>
<p>Note that because extra delegates are both added to and removed from the end of the list, <code>x += y; x -= y;</code> is always a no-op.</p>
<p>If a delegate type is declared to return a value (i.e. it&#8217;s not declared with a <code>void</code> 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.</p>
<h2>Events</h2>
<p>First things first: events aren&#8217;t delegate instances. Let&#8217;s try that again.</p>
<p><b>Events aren&#8217;t delegate instances.</b></p>
<p>It&#8217;s unfortunate in some ways that C# lets you use them in the same way in certain situations, but it&#8217;s very important that you understand the difference.</p>
<p>I find the easiest way to understand events is to think of them a bit like properties. While properties <i>look</i> like they&#8217;re fields, they&#8217;re definitely not &#8211; and you can write properties which don&#8217;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&#8217;re not.</p>
<p>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 <i>add</i> and <i>remove</i> 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 <i>typical</i> 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 &#8211; 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 <i>not</i> part of the event itself. (CIL defines an association with a <code>raise_<i>eventName</i></code> method, and indeed &#8220;other&#8221; methods, but these are not used in C#.)</p>
<p>The add and remove methods are called in C# using <code>eventName += delegateInstance;</code> and <code>eventName -= delegateInstance;</code> respectively, where <code>eventName</code> may be qualified with a reference (e.g. <code>myForm.Click</code>) or a type name (e.g. <code>MyClass.SomeEvent</code>). Static events are relatively rare.</p>
<p>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 <code>event</code> keyword. Here&#8217;s an example of an event for the <code>System.EventHandler</code> delegate type. Note how it doesn&#8217;t actually do anything with the delegate instances which are passed to the add and remove methods &#8211; it just prints out which operation has been called. Note that the remove operation is called even though we&#8217;ve told it to remove <code>null</code>.</p>
<table class="code">
<tr>
<td>
<pre><span class="Namespace">using</span> System;  <span class="ReferenceType">class</span> Test {     <span class="Modifier">public</span> <span class="Modifier">event</span> EventHandler MyEvent     {         add         {             Console.WriteLine (<span class="String">"add operation"</span>);         }                  remove         {             Console.WriteLine (<span class="String">"remove operation"</span>);         }     }                 <span class="Modifier">static</span> <span class="ValueType">void</span> Main()     {         Test t = <span class="Keyword">new</span> Test();                  t.MyEvent += <span class="Keyword">new</span> EventHandler (t.DoNothing);         t.MyEvent -= <span class="Keyword">null</span>;     }          <span class="ValueType">void</span> DoNothing (<span class="ReferenceType">object</span> sender, EventArgs e)     {     } }</pre>
</td>
</tr>
</table>
<p>Although it would be very rare to ignore the value in this way, there are times when you don&#8217;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 &#8211; it means that you can have a huge number of events without wasting a lot of memory with variables which will usually just have <code>null</code> values.</p>
<h2>A shortcut: field-like events</h2>
<p>C# provides a simple way of declaring both a delegate variable and an event at the same time. This is called a <i>field-like event</i>, and is declared very simply &#8211; it&#8217;s the same as the &#8220;longhand&#8221; event declaration, but without the &#8220;body&#8221; part:</p>
<table class="code">
<tr>
<td>
<pre><span class="Modifier">public</span> <span class="Modifier">event</span> EventHandler MyEvent</pre>
</td>
</tr>
</table>
<p>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:</p>
<table class="code">
<tr>
<td>
<pre><span class="Modifier">private</span> EventHandler _myEvent;      <span class="Modifier">public</span> <span class="Modifier">event</span> EventHandler MyEvent {     add     {         <span class="Statement">lock</span> (<span class="Keyword">this</span>)         {             _myEvent += value;         }     }     remove     {         <span class="Statement">lock</span> (<span class="Keyword">this</span>)         {             _myEvent -= value;         }     }         }</pre>
</td>
</tr>
</table>
<p>That&#8217;s for an instance member. For an event declared as static, the variable is also static and a lock is taken out on <code>typeof(XXX)</code> where <code>XXX</code> is the name of the class declaring the event. In C# 2.0 there is little guarantee about what is used for locking &#8211; 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 <i>class</i> events, not <i>struct</i> events &#8211; there are issues in terms of locking with struct events; in practice I don&#8217;t remember ever seeing a struct with any events.) None of this is actually as useful as you might think &#8211; see the <a href="http://dotnet786.wordpress.com/wp-admin/#threading">threading section</a> for more details.</p>
<p>So, what happens when you refer to <code>MyEvent</code> in code? Well, within the text of type itself (including nested types) the compiler generates code which refers to the delegate variable (<code>_myEvent</code> in my sample above). In all other contexts, the compiler generates code which refers to the event.</p>
<h2>What&#8217;s the Point?</h2>
<p>Now we know what they are, what&#8217;s the point of having both delegates and events? The answer is encapsulation. Suppose events didn&#8217;t exist as a concept in C#/.NET. How would another class subscribe to an event. Three options:</p>
<ol>
<li>A public delegate variable</li>
<li>A delegate variable backed by a property</li>
<li>A delegate variable with <code>AddXXXHandler</code> and <code>RemoveXXXHandler</code> methods</li>
</ol>
<p>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 &#8211; it would be all too easy to write <code>someInstance.MyEvent = eventHandler;</code> which would <i>replace</i> any existing event handlers rather than adding a new one. In addition, you still need to write the properties.</p>
<p>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 &#8220;free&#8221; implementation if you&#8217;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.</p>
<h2><a name="threading"></a>Thread-safe events</h2>
<p>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&#8217;s not terribly useful. Firstly, even with 2.0, the spec allows for the lock to be the reference to <code>this</code> object, or the type itself for static events. That goes against the principle of locking on privately held references to avoid accidental deadlocks.</p>
<p>Ironically, the second problem is the exact reverse of the first &#8211; because in C# 2.0 you can&#8217;t guarantee which lock is going to be used, you can&#8217;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.</p>
<p>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&#8217;t interfere with each other, you need to write the body of the add/remove operations yourself. Here&#8217;s an example:</p>
<table class="code">
<tr>
<td>
<pre><span class="XmlComment">/// &lt;summary&gt;</span> <span class="XmlComment">/// Delegate variable backing the SomeEvent event.</span> <span class="XmlComment">/// &lt;/summary&gt;</span> SomeEventHandler someEvent;  <span class="XmlComment">/// &lt;summary&gt;</span> <span class="XmlComment">/// Lock for SomeEvent delegate access.</span> <span class="XmlComment">/// &lt;/summary&gt;</span> <span class="Modifier">readonly</span> <span class="ReferenceType">object</span> someEventLock = <span class="Keyword">new</span> <span class="ReferenceType">object</span>();  <span class="XmlComment">/// &lt;summary&gt;</span> <span class="XmlComment">/// Description for the event</span> <span class="XmlComment">/// &lt;/summary&gt;</span> <span class="Modifier">public</span> <span class="Modifier">event</span> SomeEventHandler SomeEvent {     add     {         <span class="Statement">lock</span> (someEventLock)         {             someEvent += value;         }     }     remove     {         <span class="Statement">lock</span> (someEventLock)         {             someEvent -= value;         }     } }  <span class="XmlComment">/// &lt;summary&gt;</span> <span class="XmlComment">/// Raises the SomeEvent event</span> <span class="XmlComment">/// &lt;/summary&gt;</span> <span class="Modifier">protected</span> <span class="Modifier">virtual</span> OnSomeEvent(EventArgs e) {     SomeEventHandler handler;     <span class="Statement">lock</span> (someEventLock)     {         handler = someEvent;     }     <span class="Statement">if</span> (handler != <span class="Keyword">null</span>)     {         handler (<span class="Keyword">this</span>, e);     } }</pre>
</td>
</tr>
</table>
<p>You could use a single lock for all your events, or even for other things as well &#8211; 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 <i>outside</i> 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&#8217;d get deadlock.)</p>
<p>This all works because once <code>handler</code> has been assigned the value of <code>someEvent</code>, the value of <code>handler</code> won&#8217;t change even if <code>someEvent</code> does. So if all the handlers are unsubscribed from the event, <code>someEvent</code> will become <code>null</code> but <code>handler</code> will still have whatever value it had when it was assigned. In fact, as delegate instances are immutable, whatever handlers were subscribed when the <code>handler = someEvent;</code> line was executed will be called, even if others have subscribed between then and the <code>handler (this, e);</code> line.</p>
<p>Now, it&#8217;s important to consider whether or not you even <i>need</i> 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&#8217;re in complete control of your application, the answer may very well be &#8220;no&#8221;. (If you&#8217;re writing a class library, it&#8217;s more likely that being thread-safe is important.) If you don&#8217;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&#8217;s the equivalent of the earlier code, but without thread safety.</p>
<table class="code">
<tr>
<td>
<pre><span class="XmlComment">/// &lt;summary&gt;</span> <span class="XmlComment">/// Delegate variable backing the SomeEvent event.</span> <span class="XmlComment">/// &lt;/summary&gt;</span> SomeEventHandler someEvent;  <span class="XmlComment">/// &lt;summary&gt;</span> <span class="XmlComment">/// Description for the event</span> <span class="XmlComment">/// &lt;/summary&gt;</span> <span class="Modifier">public</span> <span class="Modifier">event</span> SomeEventHandler SomeEvent {     add     {         someEvent += value;     }     remove     {         someEvent -= value;     } }  <span class="XmlComment">/// &lt;summary&gt;</span> <span class="XmlComment">/// Raises the SomeEvent event</span> <span class="XmlComment">/// &lt;/summary&gt;</span> <span class="Modifier">protected</span> <span class="Modifier">virtual</span> OnSomeEvent(EventArgs e) {     <span class="Statement">if</span> (someEvent != <span class="Keyword">null</span>)     {         someEvent (<span class="Keyword">this</span>, e);     } }</pre>
</td>
</tr>
</table>
<p>The check for nullity is due to delegate variables being <code>null</code> when there aren&#8217;t any delegate instances to call. One way to make things simpler is to use a no-op delegate instance as the &#8220;default&#8221; one, which is never removed. At that point, you can just obtain the value of the delegate variable (inside a lock if you&#8217;re being thread-safe) and then execute the delegate instance. If there are no &#8220;real&#8221; delegate targets to call, the no-op target will execute and that&#8217;s all that will happen.</p>
<h2><a name="advanced"></a>Delegate instances: other methods</h2>
<p>Earlier we saw how a call to <code>someDelegate(10)</code> is actually a short-hand for <code>someDelegate.Invoke(10)</code>. Delegates types may also allow asynchronous behaviour using the <code>BeginInvoke</code>/<code>EndInvoke</code> 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.</p>
<p>The first example below operates without a callback, simply using <code>BeginInvoke</code> and <code>EndInvoke</code> 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. <code>EndInvoke</code> returns whatever value was returned by the delegate call. If the call threw an exception, the same exception is thrown by <code>EndInvoke</code>.</p>
<table class="code">
<tr>
<td>
<pre><span class="Namespace">using</span> System; <span class="Namespace">using</span> System.Threading;  <span class="ReferenceType">delegate</span> <span class="ValueType">int</span> SampleDelegate(<span class="ReferenceType">string</span> data);      <span class="ReferenceType">class</span> AsyncDelegateExample1 {     <span class="Modifier">static</span> <span class="ValueType">void</span> Main()     {         SampleDelegate counter = <span class="Keyword">new</span> SampleDelegate(CountCharacters);         SampleDelegate parser = <span class="Keyword">new</span> SampleDelegate(Parse);                  IAsyncResult counterResult = counter.BeginInvoke (<span class="String">"hello"</span>, <span class="Keyword">null</span>, <span class="Keyword">null</span>);         IAsyncResult parserResult = parser.BeginInvoke (<span class="String">"10"</span>, <span class="Keyword">null</span>, <span class="Keyword">null</span>);         Console.WriteLine (<span class="String">"Main thread continuing"</span>);                  Console.WriteLine (<span class="String">"Counter returned {0}"</span>, counter.EndInvoke(counterResult));         Console.WriteLine (<span class="String">"Parser returned {0}"</span>, parser.EndInvoke(parserResult));                  Console.WriteLine (<span class="String">"Done"</span>);     }          <span class="Modifier">static</span> <span class="ValueType">int</span> CountCharacters (<span class="ReferenceType">string</span> text)     {         Thread.Sleep (2000);         Console.WriteLine (<span class="String">"Counting characters in {0}"</span>, text);         <span class="Statement">return</span> text.Length;     }          <span class="Modifier">static</span> <span class="ValueType">int</span> Parse (<span class="ReferenceType">string</span> text)     {         Thread.Sleep (100);         Console.WriteLine (<span class="String">"Parsing text {0}"</span>, text);         <span class="Statement">return</span> <span class="ValueType">int</span>.Parse(text);     } }</pre>
</td>
</tr>
</table>
<p>The calls to <code>Thread.Sleep</code> are just to demonstrate that the execution really does occur in parallel. The sleep in <code>CountCharacters</code> is as large as it is to force the system thread-pool to run the tasks on two different threads &#8211; the thread-pool serializes requests which don&#8217;t take long in order to avoid creating more threads than it needs to. By sleeping for a long time, we&#8217;re simulating a long-running request. Here&#8217;s the output from a sample run:</p>
<table class="results">
<tr>
<td>
<pre>Main thread continuing Parsing text 10 Counting characters in hello Counter returned 5 Parser returned 10 Done</pre>
</td>
</tr>
</table>
<p>The calls to <code>EndInvoke</code> block until the delegate has completed in much the same way as calls to <code>Thread.Join</code> block until the threads involved have terminated. The <code>IAsyncResult</code> values returned by the calls to <code>BeginInvoke</code> allows access to the state passed as the last parameter to <code>BeginInvoke</code>, but this isn&#8217;t typically used in the style of asynchronous invocation shown above.</p>
<p>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 <code>EndInvoke</code> 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 <code>BeginInvoke</code> 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 <code>IAsyncResult</code> to <code>AsyncResult</code>: the value provided to the callback is always an instance of <code>AsyncResult</code>, and this can be used to obtain the original delegate instance, so that the callback can call <code>EndInvoke</code>. It is somewhat anomalous that <code>AsyncResult</code> lives in the <code>System.Runtime.Remoting.Messaging</code> namespace when all the other classes involved are in either <code>System</code> or <code>System.Threading</code>, but such is life.</p>
<table class="code">
<tr>
<td>
<pre><span class="Namespace">using</span> System; <span class="Namespace">using</span> System.Threading; <span class="Namespace">using</span> System.Runtime.Remoting.Messaging;  <span class="ReferenceType">delegate</span> <span class="ValueType">int</span> SampleDelegate(<span class="ReferenceType">string</span> data);      <span class="ReferenceType">class</span> AsyncDelegateExample2 {     <span class="Modifier">static</span> <span class="ValueType">void</span> Main()     {         SampleDelegate counter = <span class="Keyword">new</span> SampleDelegate(CountCharacters);         SampleDelegate parser = <span class="Keyword">new</span> SampleDelegate(Parse);                  AsyncCallback callback = <span class="Keyword">new</span> AsyncCallback (DisplayResult);                  counter.BeginInvoke (<span class="String">"hello"</span>, callback, <span class="String">"Counter returned {0}"</span>);         parser.BeginInvoke (<span class="String">"10"</span>, callback, <span class="String">"Parser returned {0}"</span>);          Console.WriteLine (<span class="String">"Main thread continuing"</span>);          Thread.Sleep (3000);         Console.WriteLine (<span class="String">"Done"</span>);     }          <span class="Modifier">static</span> <span class="ValueType">void</span> DisplayResult(IAsyncResult result)     {         <span class="ReferenceType">string</span> format = (<span class="ReferenceType">string</span>) result.AsyncState;         AsyncResult delegateResult = (AsyncResult) result;         SampleDelegate delegateInstance = (SampleDelegate)delegateResult.AsyncDelegate;                  Console.WriteLine (format, delegateInstance.EndInvoke(result));     }          <span class="Modifier">static</span> <span class="ValueType">int</span> CountCharacters (<span class="ReferenceType">string</span> text)     {         Thread.Sleep (2000);         Console.WriteLine (<span class="String">"Counting characters in {0}"</span>, text);         <span class="Statement">return</span> text.Length;     }          <span class="Modifier">static</span> <span class="ValueType">int</span> Parse (<span class="ReferenceType">string</span> text)     {         Thread.Sleep (100);         Console.WriteLine (<span class="String">"Parsing text {0}"</span>, text);         <span class="Statement">return</span> <span class="ValueType">int</span>.Parse(text);     } }</pre>
</td>
</tr>
</table>
<p>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 &#8211; without the extra <code>Sleep</code> call, the application would terminate before the delegate calls finished executing.) Some sample output is below &#8211; notice how this time, because there is no guaranteed ordering to the calls to <code>EndInvoke</code>, 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.</p>
<table class="results">
<tr>
<td>
<pre>Main thread continuing Parsing text 10 Parser returned 10 Counting characters in hello Counter returned 5 Done</pre>
</td>
</tr>
</table>
<p>Note that you <i>must</i> call <code>EndInvoke</code> when you use asynchronous execution in order to guarantee not to leak memory or handles. Some implementations may not leak, but you shouldn&#8217;t rely on this. See my <a href="http://www.pobox.com/~skeet/csharp/threads/threadpool.shtml">thread-pool article</a> for some sample code to allow &#8220;fire and forget&#8221; style asynchronous behaviour if this is inconvenient.</p>
<h2>Conclusion</h2>
<p>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.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=11&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/02/23/delegates-and-events/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>
	</item>
		<item>
		<title>Web Parts in ASP.NET 2.0</title>
		<link>http://dotnet786.wordpress.com/2008/02/23/web-parts-in-aspnet-20/</link>
		<comments>http://dotnet786.wordpress.com/2008/02/23/web-parts-in-aspnet-20/#comments</comments>
		<pubDate>Sat, 23 Feb 2008 13:42:20 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/02/23/web-parts-in-aspnet-20/</guid>
		<description><![CDATA[Web Parts in ASP.NET 2.0
by Jesse Libertyhttp://www.ondotnet.com/pub/a/dotnet/2005/01/10/liberty.html
01/10/2005 <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=10&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Web Parts in ASP.NET 2.0</h2>
<p>by <a href="http://www.ondotnet.com/pub/au/239">Jesse Liberty</a>http://www.ondotnet.com/pub/a/dotnet/2005/01/10/liberty.html<br />
01/10/2005 <!-- sidebar begins --><!-- don't move sidebars --><!-- sidebar ends -->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.</p>
<h3>Getting Started</h3>
<p>There have been some small changes since the previous articles were published, and so I suggest you <a href="http://www.ondotnet.com/dotnet/2005/01/10/examples/web_parts_starter_kit.zip">download the updated starter code</a>. Unzip the starter project to any directory you like. It will create a subdirectory called <em>Web Parts</em>. 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.</p>
<p><img border="0" width="500" src="http://www.ondotnet.com/dotnet/2005/01/10/graphics/sharing_web_parts_directory.gif" alt="Figure 1" height="391" /><br />
<em><strong>Figure 1.</strong> Sharing the <i>Web Parts</i> directory</em></p>
<p>Start Visual Studio 2005 Beta 1 and choose File -&gt; Open -&gt; Open Web site. Navigate to the <i>Web Parts</i> 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&#8217;re ready to begin to add Web Parts to what had been the Personalization project.</p>
<p>Begin by adding a new page, <i>WebParts.aspx</i>, to your project, and add a link to that page on your <i>default.aspx</i> page.</p>
<h3>Creating Zones</h3>
<p>A page that uses Web Parts is divided into <i>zones</i>: 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:</p>
<p>1. Open the WebParts section of your Toolbox, and drag a WebPartManager onto your page, as shown in Figure 2.</p>
<p><img border="0" width="170" src="http://www.ondotnet.com/dotnet/2005/01/10/graphics/web_parts_manager.gif" alt="Figure 2" height="451" /><br />
<em><strong>Figure 2.</strong> Web Parts toolbox</em></p>
<p>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.</p>
<p>2. Add a new table, with two rows and three columns. Rearrange the columns so that they are not of even size.</p>
<p>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 &#8220;Click here to add WebParts to the WebPartZone,&#8221; as shown in Figure 3.</p>
<p><img border="0" width="500" src="http://www.ondotnet.com/dotnet/2005/01/10/graphics/dragging_web_part_zones.gif" alt="Figure 3" height="311" /><br />
<em><strong>Figure 3.</strong> Creating zones</em></p>
<h3>Adding Controls To Zones</h3>
<p>4. Set the heading on the first Web Part control to <code>News</code> and drag a Label into the zone. The Label is wrapped in a Web Part control, and its title is set to <em>Untitled</em>, as shown in Figure 4.</p>
<p><img border="0" width="277" src="http://www.ondotnet.com/dotnet/2005/01/10/graphics/label_web_part_raw.gif" alt="Figure 4" height="215" /><br />
<em><strong>Figure 4.</strong> Adding Controls</em></p>
<p>5. Switch to source view and change the title of the label to <em>Today&#8217;s News</em> and the text to &#8220;&lt;br/&gt;Thousands die. Thousands more die at eleven.&#8221;. Switch back to design view and drag a list box into WebPartZone3. Set the header text for the WebPartZone to &#8220;Sponsors.&#8221; 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 &#8220;Our Sponsors&#8221; and run the application. You&#8217;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.</p>
<p><img border="0" width="500" src="http://www.ondotnet.com/dotnet/2005/01/10/graphics/web_parts_running_simple.gif" alt="Figure 5" height="272" /><br />
<em><strong>Figure 5. </strong>The Web Parts live</em></p>
<h3>Minimizing and Restoring</h3>
<p>Click on the Minimize tag and the contents of the Web Part (e.g., the list box) collapses, and the link changes from &#8220;Minimize&#8221; to &#8220;Restore&#8221; as shown in Figure 6.</p>
<p><img border="0" width="500" src="http://www.ondotnet.com/dotnet/2005/01/10/graphics/web_parts_running_simple_minimized.gif" alt="Figure 6" height="272" /><br />
<em><strong>Figure 6. </strong>Closing and restoring</em></p>
<p>Exit the application. Start it again and sign back in, and navigate back to these pages. Aha! The minimized zone remains minimized. You&#8217;ll find that the Web Parts are closely tied with personalization, and each individual&#8217;s personalized Web Parts are persisted through the personalization database.</p>
<h3>Allow Your Users to Move the Web Parts</h3>
<p>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.</p>
<p><img border="0" width="500" src="http://www.ondotnet.com/dotnet/2005/01/10/graphics/web_parts_page_menu.gif" alt="Figure 7" height="329" /><br />
<em><strong>Figure 7.</strong> Adding a menu</em></p>
<p>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 <em>Design Page Layout</em> 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 <em>Today&#8217;s News</em> Web Part being dragged from Zone 1 (upper left) to Zone 4 (lower left).</p>
<p><img border="0" width="444" src="http://www.ondotnet.com/dotnet/2005/01/10/graphics/relocating_web_parts.gif" alt="Figure 8" height="500" /><br />
<em><strong>Figure 8. </strong>Movable Web Parts</em></p>
<p>When you are done, return to the Web Parts Page Manager, set it to <em>Browse This Page </em>and click <em>Change</em>. 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&#8217;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.</p>
<p><!-- article_sidebar2.view begins --></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=10&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/02/23/web-parts-in-aspnet-20/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>

		<media:content url="http://www.ondotnet.com/dotnet/2005/01/10/graphics/sharing_web_parts_directory.gif" medium="image">
			<media:title type="html">Figure 1</media:title>
		</media:content>

		<media:content url="http://www.ondotnet.com/dotnet/2005/01/10/graphics/web_parts_manager.gif" medium="image">
			<media:title type="html">Figure 2</media:title>
		</media:content>

		<media:content url="http://www.ondotnet.com/dotnet/2005/01/10/graphics/dragging_web_part_zones.gif" medium="image">
			<media:title type="html">Figure 3</media:title>
		</media:content>

		<media:content url="http://www.ondotnet.com/dotnet/2005/01/10/graphics/label_web_part_raw.gif" medium="image">
			<media:title type="html">Figure 4</media:title>
		</media:content>

		<media:content url="http://www.ondotnet.com/dotnet/2005/01/10/graphics/web_parts_running_simple.gif" medium="image">
			<media:title type="html">Figure 5</media:title>
		</media:content>

		<media:content url="http://www.ondotnet.com/dotnet/2005/01/10/graphics/web_parts_running_simple_minimized.gif" medium="image">
			<media:title type="html">Figure 6</media:title>
		</media:content>

		<media:content url="http://www.ondotnet.com/dotnet/2005/01/10/graphics/web_parts_page_menu.gif" medium="image">
			<media:title type="html">Figure 7</media:title>
		</media:content>

		<media:content url="http://www.ondotnet.com/dotnet/2005/01/10/graphics/relocating_web_parts.gif" medium="image">
			<media:title type="html">Figure 8</media:title>
		</media:content>
	</item>
		<item>
		<title>Identifying Object-Oriented Classes By RoyClem(Article is from CodeProject)</title>
		<link>http://dotnet786.wordpress.com/2008/02/21/identifying-object-oriented-classes-by-royclemarticle-is-from-codeproject/</link>
		<comments>http://dotnet786.wordpress.com/2008/02/21/identifying-object-oriented-classes-by-royclemarticle-is-from-codeproject/#comments</comments>
		<pubDate>Thu, 21 Feb 2008 03:31:48 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/02/21/identifying-object-oriented-classes-by-royclemarticle-is-from-codeproject/</guid>
		<description><![CDATA[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, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=9&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Introduction</h2>
<p>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.</p>
<p>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.</p>
<p><b>Note</b>: The following class diagrams were modeled using <a target="_blank" href="http://www.sparxsystems.com.au/ea.htm">Enterprise Architect</a>. Many other modeling tools exist. Use the one that is best suited for your purpose and project.</p>
<h2>Classes</h2>
<p>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) &#8211; <i>they know things</i> &#8211; and behavior (methods) &#8211; <i>they do things</i>.</p>
<p><b>Classes are specifications for objects.</b></p>
<p>Derived from the <a href="http://www.codeproject.com/gen/design/pusecase.asp">Use Cases</a>, classes provide an abstraction of the requirements and provide the internal view of the application.</p>
<h3>Attributes</h3>
<p>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.</p>
<p>The type of data that an attribute can contain is determined by its data type. There are two basic data types: Primitive and Derived.</p>
<ol>
<li>Primitive data types are fundamental types. Examples are integer, string, float.</li>
<li>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 <code>Student</code> class, for example, is a derived data type formed by a collection of primitive data types.</li>
</ol>
<p>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, <code>Address studentAddress</code> versus<code> <span class="code-SDKkeyword">string</span> studentAddress</code>.</p>
<p><b>Where practical, design models should use domain specific data types in lieu of primitive data types.</b></p>
<p>When looking for attributes in the design model, look for these types:</p>
<ol>
<li>Descriptive attributes provide intrinsic information about the class. For example, information about enrollment status, test scores, and education goals would be intrinsic to a <code>Student</code> class but not an <code>Automobile</code> class. Ask, “What characteristics distinguish this class from others?”</li>
<li>Naming attributes are used to uniquely identify an object and typically don’t change during the lifetime of the object. Consider two <code>Student</code> objects that contain the naming attribute, <code>studentName</code>. The values of “Jack” and “Jill” would identify two different <code>Student</code> objects. Ask, “What uniquely identifies this object from another object of the same class?”</li>
<li>Referential attributes contain links to objects. A student’s test scores might be stored in an <code>Assessment</code> class, for example. The value for the <code>Assessment</code> attribute (in the <code>Student</code> class) would link the <code>Student</code> class to the <code>Assessment</code> class. Ask, “How is this object associated with other objects?”</li>
</ol>
<h3>Responsibilities</h3>
<p>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.</p>
<p>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.</p>
<p><b>Responsibility is the obligation of a class or object to perform a task or know information.</b></p>
<h2>Identifying classes</h2>
<p>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.</p>
<p><b>Cohesive classes reduce coupling, enable extensibility and increase maintainability.</b></p>
<p>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.</p>
<p>Therefore, begin class modeling by identifying candidate classes &#8211; 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.</p>
<p><b>Candidate classes provide the initial impetus to produce cohesive classes.</b></p>
<p>Candidate classes can be discovered in a variety of ways. Here are three:</p>
<ol>
<li><a target="_blank" href="http://en.wikipedia.org/wiki/Noun">Noun and noun phrases</a>: Identify the noun and noun phrases, verbs (actions) and adjectives (attributes) from the Use Cases, Actor-Goal List, Application Narrative and Problem Description.</li>
<li><a target="_blank" href="http://alistair.cockburn.us/crystal/articles/ucrcc/usingcrccards.html">CRC cards</a>: an informal, group approach to object modeling.</li>
<li><a target="_blank" href="http://cis.gsu.edu/~cstucke/cis3310/3310.3.a.pdf">GRASP</a>: A formal set of principles that assign responsibilities.</li>
</ol>
<p>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.; <code>Student</code> and <code>StudentRecord</code>, for example. That’s fine. The goal is to identify the major classes &#8211; the obvious ones. Other classes will become apparent as the design process continues.</p>
<p>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.</p>
<p>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.</p>
<table border="1" cellPadding="0" cellSpacing="0" style="border-collapse:collapse;border:medium none;" class="MsoTableGrid">
<tr>
<td width="140" vAlign="top" style="width:105.3pt;background-color:transparent;border:windowtext 1pt solid;padding:0 5.4pt;"><b>Candidate Classes</b></td>
<td width="124" vAlign="top" style="border-right:windowtext 1pt solid;border-top:windowtext 1pt solid;border-left:#ece9d8;width:93.1pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><b>Design Classes </b></td>
</tr>
<tr>
<td width="140" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:windowtext 1pt solid;width:105.3pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Student</code></td>
<td width="124" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:#ece9d8;width:93.1pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Student</code></td>
</tr>
<tr>
<td width="140" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:windowtext 1pt solid;width:105.3pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Teacher</code></td>
<td width="124" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:#ece9d8;width:93.1pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Professor</code></td>
</tr>
<tr>
<td width="140" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:windowtext 1pt solid;width:105.3pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Class</code></td>
<td width="124" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:#ece9d8;width:93.1pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Course</code></td>
</tr>
<tr>
<td width="140" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:windowtext 1pt solid;width:105.3pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Subject</code></td>
<td width="124" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:#ece9d8;width:93.1pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Assessment</code></td>
</tr>
<tr>
<td width="140" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:windowtext 1pt solid;width:105.3pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Grades</code></td>
<td width="124" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:#ece9d8;width:93.1pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"></td>
</tr>
<tr>
<td width="140" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:windowtext 1pt solid;width:105.3pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"><code>Tests</code></td>
<td width="124" vAlign="top" style="border-right:windowtext 1pt solid;border-top:#ece9d8;border-left:#ece9d8;width:93.1pt;border-bottom:windowtext 1pt solid;background-color:transparent;padding:0 5.4pt;"></td>
</tr>
</table>
<p><b>Design classes will emerge from the analysis of the candidate classes.</b></p>
<p>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.</p>
<h3>Associations</h3>
<p>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.</p>
<p><b>A relationship is an association between classes.</b></p>
<p>When identifying relationships, start with the class that interacts with as many other classes as possible; perhaps, the core classes of the application. It&#8217;s helpful to ask, &#8220;Who cares about this class?&#8221;, &#8220;Who is interested in this class?&#8221;, &#8220;Why is this class necessary?&#8221; Starting with the core classes will quickly identify the other relationships.</p>
<p><b>Start with core associations.</b></p>
<p>An association is usually modeled using a solid line that connects two classes.</p>
<p><img width="345" src="http://www.codeproject.com/KB/architecture/idclass/figure1.png" height="97" /></p>
<p>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.</p>
<p><img width="341" src="http://www.codeproject.com/KB/architecture/idclass/figure2.png" height="94" /></p>
<h3>Association roles</h3>
<p>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 <code>Professor</code> is an instructor to a <code>Student</code> who is a learner or pupil.</p>
<p><img width="338" src="http://www.codeproject.com/KB/architecture/idclass/figure3.png" height="93" /></p>
<h3>Multiplicity Indicators</h3>
<p>A role can have multiplicity &#8211; an indication of how many objects participate in the relationship. Multiplicity indicators can be conditional or unconditional.</p>
<p>Examples of multiplicity indicators are:</p>
<p><img width="491" src="http://www.codeproject.com/KB/architecture/idclass/figure4.png" height="328" /></p>
<p>In Figure 4, the first two indicators (that start with &#8220;0&#8230;&#8221;) are conditional meaning no objects need be present in the relationship. The last two indicators (that start with &#8220;1..&#8221;) are unconditional meaning at least one object must be present in the relationship. For example:</p>
<p><img width="338" src="http://www.codeproject.com/KB/architecture/idclass/figure5.png" height="92" /></p>
<p>In Figure 5, a <code>Professor</code> can exist without the existence of a <code>Student</code>. Therefore, the multiplicity for the <code>Student</code> is 0…*. However, the same is not true for the <code>Student</code>. A <code>Student</code> must have at least one <code>Professor</code>. Hence, the 1…* indicator for the <code>Professor</code>.</p>
<p><b>Multiplicity indicators are also referred to as cardinalities.</b></p>
<p>Unconditional indicators may impose a referential integrity constraint. Consider the following example:</p>
<p><img width="337" src="http://www.codeproject.com/KB/architecture/idclass/figure6.png" height="95" /></p>
<p>Class <code>A</code> and class <code>B</code> depend on the existence of the other. Since the multiplicity is unconditional the following is implied:</p>
<ol>
<li>When class <code>A</code> (or class <code>B</code>) is removed, the corresponding class <code>B</code> (or class <code>A</code>) must also be removed.</li>
<li>When class <code>A</code> (or class <code>B</code>) is added, the corresponding class <code>B</code> (or class A) must also be added.</li>
</ol>
<p><b>Unconditional indicators must be checked for referential integrity constraints..</b></p>
<h3>Association class</h3>
<p>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.</p>
<p>For example, a <code>Student</code> class has an association to a <code>Course</code> 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 <code>Student</code> class gives a student the same grade for all courses. Placing the grade in the <code>Course</code> class gives all students taking the same course the same grade.</p>
<p><img width="333" src="http://www.codeproject.com/KB/architecture/idclass/figure7.png" height="98" /></p>
<p>The Association class resolves this issue by linking (or mapping) the grade (and other attributes) to the <code>Student</code> and the <code>Course</code> classes. Now, a <code>Student</code> can have many grades for many courses, but each grade in the <code>StudentClassAssociation</code> is associated to a single student and course.</p>
<p><img width="373" src="http://www.codeproject.com/KB/architecture/idclass/figure8.png" height="263" /></p>
<p><b>Association classes often occur in many-to-many associations.</b></p>
<h3>Composition</h3>
<p>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”.</p>
<p><b>In a composition association, the whole manages the lifecycle of the part.</b></p>
<p>To identify composition associations, look for classes that can not exist without other classes. Look for &#8220;wholes&#8221; and &#8220;parts&#8221;. Ask, &#8220;Is this class part of another class?&#8221; For example, a <code>Sentence</code> class is part of a <code>Paragraph</code> class that is part of a <code>Chapter</code> class that is part of a <code>Book</code> class. &#8220;Does this class depend on another class?&#8221;</p>
<p><b>The key question to ask, &#8220;Is this class destroyed when another class is destroyed?&#8221;</b></p>
<h3>Aggregation</h3>
<p>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 &#8220;Has-a&#8221; relationship, as in, an Automobile Has-a(n) engine.</p>
<p>To identify aggregation associations, ask, &#8220;Is this class part of another class <b>and</b> is it independent of the other class?&#8221;</p>
<p><b>To avoid confusion, when the decision to use the composition/aggregation association is unclear, it&#8217;s best to model the relationship as a simple association.</b></p>
<h3>Generalization/Specialization</h3>
<p>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.</p>
<p><b>Inheritance provides the mechanism for new classes to be formed from the attributes and behavior of existing classes.</b></p>
<p>As base classes are specialized into derived classes, hierarchies are formed that represent <i>is-a</i> or <i>kind-of</i> relationships. For example, an Algebra course <i>is-a</i> specialization of a Math course; a student is a <i>kind-of</i> Person.</p>
<p>To identify inheritance relationships, ask, &#8220;Is this class a specialization of a more general class?&#8221;</p>
<p>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.</p>
<p><b>Inheritance is best suited for relatively shallow class hierarchies.</b></p>
<p>Use Inheritance when:</p>
<ul>
<li>The inheritance hierarchy represents an <i>is-a</i> relationship and not a <i>has-a</i> (composition/aggregate) relationship.</li>
<li>The same behavior is applied to different data types.</li>
<li>The class hierarchy is reasonably shallow, and unlikely to become much deeper over time.</li>
</ul>
<h3>Interface inheritance</h3>
<p>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).</p>
<p>For example, the .NET framework provides the <code>IComparable</code> interface that defines a generalized comparison method. This interface is typically used for sorting purposes. Classes that inherit the <code>IComparable</code> interface implement behavior specific to their needs. So, using the same <code>IComparable</code> interface, an <code>Integer</code> class can sort integers, a <code><span class="code-SDKkeyword">Byte</span></code> class can sort bytes, a <code>Student</code> class can sort students, and so on.</p>
<p><b>The behavior has been abstracted out from any particular class and specifically implemented by all classes that need it.</b></p>
<p>Use interface inheritance when:</p>
<ul>
<li>Unrelated object types need to provide the same behavior.</li>
<li>Multiple inheritance is needed (very difficult to implement using the inheritance association).</li>
<li>Inheritance is prohibited. For example, C# structures cannot inherit from classes, but they can implement interfaces.</li>
</ul>
<p><b>The Strategy Design Pattern is an excellent candidate for an interface inheritance.</b></p>
<h2>Conclusion</h2>
<p>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.</p>
<h2>Additional links</h2>
<ul>
<li><a target="_blank" href="http://www.holub.com/goodies/uml/">Allen Holub&#8217;s UML Quick Reference</a></li>
<li>Scott Ambler’s <a target="_blank" href="http://www.agilemodeling.com/artifacts/classDiagram.htm#DesignClassDiagrams">How to Create Class Diagrams</a>.</li>
<li>Scott Ambler’s <a target="_blank" href="http://www.agilemodeling.com/style/classDiagram.htm">UML Class Diagram Guidelines</a>.</li>
<li><a target="_blank" href="http://www.uml.org/">OMG’s UML Resource Page</a>.</li>
<li>Craig Larman’s, <a target="_blank" href="http://www.amazon.com/exec/obidos/tg/detail/-/0131489062/qid=1101839515/sr=1-1/ref=sr_1_1/002-7792023-3440049?v=glance&amp;s=books">Applying UML and Patterns</a> is a must read.</li>
</ul>
<p><!-- Article Ends --><!-- Main Page Contents End --></p>
<h2>License</h2>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=9&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/02/21/identifying-object-oriented-classes-by-royclemarticle-is-from-codeproject/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>

		<media:content url="http://www.codeproject.com/KB/architecture/idclass/figure1.png" medium="image" />

		<media:content url="http://www.codeproject.com/KB/architecture/idclass/figure2.png" medium="image" />

		<media:content url="http://www.codeproject.com/KB/architecture/idclass/figure3.png" medium="image" />

		<media:content url="http://www.codeproject.com/KB/architecture/idclass/figure4.png" medium="image" />

		<media:content url="http://www.codeproject.com/KB/architecture/idclass/figure5.png" medium="image" />

		<media:content url="http://www.codeproject.com/KB/architecture/idclass/figure6.png" medium="image" />

		<media:content url="http://www.codeproject.com/KB/architecture/idclass/figure7.png" medium="image" />

		<media:content url="http://www.codeproject.com/KB/architecture/idclass/figure8.png" medium="image" />
	</item>
		<item>
		<title>template column find control</title>
		<link>http://dotnet786.wordpress.com/2008/02/19/template-column-find-control/</link>
		<comments>http://dotnet786.wordpress.com/2008/02/19/template-column-find-control/#comments</comments>
		<pubDate>Tue, 19 Feb 2008 14:50:09 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/02/19/template-column-find-control/</guid>
		<description><![CDATA[Label lbl = ((Label)((Infragistics.WebUI.UltraWebGrid.CellItem)((Infragistics.WebUI.UltraWebGrid.TemplatedColumn)row.Cells[5].Column).CellItems[row.Index]).FindControl(&#8220;lblAntibioticString&#8221;));

       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=8&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font size="2"><font size="2" color="#2b91af">Label</font><font size="2"> lbl = ((</font><font size="2" color="#2b91af">Label</font><font size="2">)((Infragistics.WebUI.UltraWebGrid.</font><font size="2" color="#2b91af">CellItem</font><font size="2">)((Infragistics.WebUI.UltraWebGrid.</font><font size="2" color="#2b91af">TemplatedColumn</font><font size="2">)row.Cells[5].Column).CellItems[row.Index]).FindControl(</font><font size="2" color="#a31515">&#8220;lblAntibioticString&#8221;</font><font size="2">));</font></p>
<p></font></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/8/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/8/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=8&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/02/19/template-column-find-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>
	</item>
		<item>
		<title>forcefully do server postback</title>
		<link>http://dotnet786.wordpress.com/2008/02/09/forcefully-do-server-postback/</link>
		<comments>http://dotnet786.wordpress.com/2008/02/09/forcefully-do-server-postback/#comments</comments>
		<pubDate>Sat, 09 Feb 2008 06:50:13 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/02/09/forcefully-do-server-postback/</guid>
		<description><![CDATA[oEvent.needPostBack = false;
       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=7&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>oEvent.needPostBack = false;</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/7/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/7/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=7&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/02/09/forcefully-do-server-postback/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>
	</item>
		<item>
		<title>Best site for recursion problems</title>
		<link>http://dotnet786.wordpress.com/2008/02/08/best-site-for-recursion-problems/</link>
		<comments>http://dotnet786.wordpress.com/2008/02/08/best-site-for-recursion-problems/#comments</comments>
		<pubDate>Fri, 08 Feb 2008 06:48:36 +0000</pubDate>
		<dc:creator>dotnet786</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnet786.wordpress.com/2008/02/08/best-site-for-recursion-problems/</guid>
		<description><![CDATA[http://erwnerve.tripod.com/prog/recursion/index.htm
       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=6&subd=dotnet786&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://erwnerve.tripod.com/prog/recursion/index.htm">http://erwnerve.tripod.com/prog/recursion/index.htm</a></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnet786.wordpress.com/6/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnet786.wordpress.com/6/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnet786.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnet786.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnet786.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnet786.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnet786.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnet786.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnet786.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnet786.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnet786.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnet786.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnet786.wordpress.com&blog=1866952&post=6&subd=dotnet786&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnet786.wordpress.com/2008/02/08/best-site-for-recursion-problems/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/ba32f35659941d00db353b2d0e6e3ac6?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnet786</media:title>
		</media:content>
	</item>
	</channel>
</rss>