<?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"
	>

<channel>
	<title>Blog For .NET</title>
	<atom:link href="http://www.blogfor.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.blogfor.net</link>
	<description>welcome to the blogosphere</description>
	<pubDate>Tue, 04 Nov 2008 04:08:59 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>Creating Class Libraries of Asp.Net Web Components</title>
		<link>http://www.blogfor.net/2008/11/03/creating-class-libraries-of-aspnet-web-components/</link>
		<comments>http://www.blogfor.net/2008/11/03/creating-class-libraries-of-aspnet-web-components/#comments</comments>
		<pubDate>Tue, 04 Nov 2008 04:08:59 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=48</guid>
		<description><![CDATA[Investigation into creating a class libraries to hold Asp.net pages, user controls, server control, and web services.]]></description>
			<content:encoded><![CDATA[<p>Suppose you have multiple client projects and want to build a reusable framework for them. This framework could include components to build sites (server controls, data control fields, custom datagrid, custom pager etc.). It could also include components such as pages, user controls, and web services.</p>
<p>Scott Gu espouses a strategy for creating user control libraries <a href="http://webproject.scottgu.com/CSharp/UserControls/UserControls.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/webproject.scottgu.com');">here</a>, <a href="http://weblogs.asp.net/scottgu/archive/2006/08/16/Tip_2F00_Trick_3A00_-Creating-Sub_2D00_Web-Projects-using-the-VS-2005-Web-Application-Project-Option.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/weblogs.asp.net');">here</a>, and <a href="http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/weblogs.asp.net');">here</a>. The technique involves copying the makrup files from the library &#8220;project&#8221; to the client &#8220;project&#8221; using xcopy (robocopy on vista). There are additional articles like this <a href="http://www.codeproject.com/KB/aspnet/ConvertUserToCustom.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');">one</a> describing even more ways to achieve partial solutions to this problem.</p>
<p>Depending on your development and deployment needs the solution to this problem will vary. In this article I&#8217;ll go through some of the choices available their related trade-offs, give sample applications demonstrating various approaches, and show another method to do this without copying markup files by referencing only the fully compiled library site.</p>
<p>If your library is developed as a <a href="http://msdn.microsoft.com/en-us/library/ms178463(VS.80).aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">web site</a> you can leverage the edit-and-continue feature to create and debug components more quickly. Conversely, since there is no assembly associated with a web site, a <a href="http://blogs.msdn.com/webdevtools/archive/2008/01/25/announcing-rtw-of-visual-studio-2008-web-deployment-projects-wdp.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">web deployment project</a> is needed before components can be referenced in a client application.</p>
<p><em>Note: In order for components in the app_code directory of the library assembly to be accessible to the client application, library assembly must be referenced by the client application</em> and <em>the setting &#8220;Treat As Library Component (remove the App_Code.compiled file)&#8221; must be selected in the web deployment project.</em></p>
<p>By copying the component files to the client application, the library components containing markup are in effect being compiled as part of the client application. This can, however, lead to some issues.</p>
<p>If the web deployment project has &#8220;Allow this precompiled site to be updateable&#8221; checked, the build will remove the markup from aspx and ascx files and replace them with the text &#8220;This is a marker file generated by the precompilation tool, and should not be deleted!&#8221;. When the client application builds, Visual Studio tries to build these marker files and  fails on build with an error similar to &#8220;The page must have a &lt;%@ webservice class=&#8221;MyNamespace.MyClass&#8221; &#8230; %&gt; directive.&#8221;</p>
<p>When copying the markup files directly from the library &#8220;project&#8221; the files may contain a &#8220;codeFile&#8221; attribute which will not exist in the client application, causing a compiler warning. Alternatively, when the markup files are copied from the web deployment project&#8217;s output, the codeFile attribute has been removed but the compiler will now warn &#8220;c:\&#8230;\v2.0.50727\Temporary ASP.NET Files\&#8230;\App_Web_x4mc84hf.0.cs(134,53): warning CS0108: &#8216;ASP.library_usercontrols_libraryusercontrol_ascx.Profile&#8217; hides inherited member &#8216;LibrarySite.Library.UserControls.LibraryUserControl.Profile&#8217;. Use the new keyword if hiding was intended.&#8221; This is because the web application project already compiled part of the markup into the library assembly, namely the &#8220;Profile&#8221; and &#8220;ApplicationInstance&#8221; properties.</p>
<p>To enable web deployment compilation of the client application, the markup files must be copied from the library project (with the codeFile attribute) and not from the web deployment project output, otherwise Aspnet_compile will error.</p>
<p>Another common error is &#8220;Compiler Error Message: CS0433: The type &#8216;ASP.library_usercontrols_libraryusercontrol_ascx&#8217; exists in both &#8216;c:\&#8230;\v2.0.50727\Temporary ASP.NET Files\&#8230;\App_Web_empkj51o.dll&#8217; and &#8216;c:\&#8230;\v2.0.50727\Temporary ASP.NET Files\&#8230;\assembly\&#8230;\LibrarySite.DLL&#8217;&#8221; This again stems from the re-compilation of library controls in the client application when the client application already references the library assembly. It stems from a situation where the user control/page/webservice has been compiled in the library assembly and is compiled into the client application with the same type name.</p>
<p>A sample of this setup where the library is a web site can be found <a href="http://www.blogfor.net/wp-content/uploads/2008/11/websitelibrarywebsiteclient.zip" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/2008/11/websitelibrarywebsiteclient.zip');">here</a> (Client application is a vs2k8 web site) and <a href="http://www.blogfor.net/wp-content/uploads/2008/11/websitelibrarywebapplicationprojectclient.zip" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/2008/11/websitelibrarywebapplicationprojectclient.zip');">here</a> (Client application is a vs2k8 <a href="http://msdn.microsoft.com/en-us/library/aa983474.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">web application project</a>).</p>
<p>A sample of this setup where the library is a web application project can be found <a href="http://www.blogfor.net/wp-content/uploads/2008/11/webapplicationprojectlibrarywebsiteclient.zip" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/2008/11/webapplicationprojectlibrarywebsiteclient.zip');">here</a> (Client application is vs2k8 web site) and <a href="http://www.blogfor.net/wp-content/uploads/2008/11/webapplicationprojectlibrarywebapplicationprojectclient.zip" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/2008/11/webapplicationprojectlibrarywebapplicationprojectclient.zip');">here</a> (Client application is a vs2k8 web application project).</p>
<p>If you&#8217;re using subversion, one final approach to this method involves using svn <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/svnbook.red-bean.com');">externs</a>.  An extern link to a child directory of the library is created from a child directory of the client application. When the Client application was compiled, it would also compile these files. Since the client application does not reference the library assembly, there is no type conflict and the controls are only compiled once.</p>
<p>This solution does not work for web services and is quite inflexible.</p>
<p>The basic problem with these approaches is the recompilation of the library controls and the tedious copying of the markup files.</p>
<p>A more flexible approach is to fully compile the library into a single assembly and reference it from the client application as a standard assembly. The problem now is to make the pages, user controls, and web services available to the client application.</p>
<p>In .net 2.0, user controls can be referenced by assembly and namespace in addition to url via the <a href="http://msdn.microsoft.com/en-us/library/ewtd66a0.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">LoadControl</a> method. When referencing precompiled user controls, the key is to reference the compiled markup class, not the codebehind (ASP.library_usercontrols_libraryusercontrol_ascx instead of LibrarySite.Library.UserControls.LibraryUserControl).</p>
<p>To reference pages and web services in the library assembly we need to update our configuration to map requests to these resources to the correct handlers.</p>
<p>In HttpHandlers section of the client application web.config we replace the existing handlers for aspx and asmx as follows:</p>
<blockquote><p><span style="font-size: x-small;"><span style="font-size: x-small; color: #000000;">&lt;remove verb=&#8221;*&#8221; path=&#8221;*.asmx&#8221;/&gt;<br />
&lt;remove verb=&#8221;*&#8221; path=&#8221;*.aspx&#8221;/&gt;</span></span></p>
<p><span style="font-size: x-small;"><span style="font-size: x-small; color: #000000;">&lt;add verb=&#8221;*&#8221; path=&#8221;*.aspx&#8221; type=&#8221;LibrarySite.PageHandlerFactory, LibrarySite&#8221; validate=&#8221;true&#8221; /&gt;<br />
&lt;add verb=&#8221;*&#8221; path=&#8221;*.asmx&#8221; validate=&#8221;false&#8221; type=&#8221;LibrarySite.AutoDiscoveryWebServiceHandlerFactory, LibrarySite&#8221;/&gt;</span></span></p></blockquote>
<p>Now all http requests for .aspx and .asmx files will go through custom <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttphandlerfactory.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">IHTTPHandlerFactories</a> to dynamically load pages and web services from the library assembly as necessary. The IHTTPHandlerFactories receives requests and tries to match them to the resource against the full type names in loaded assemblies (e.g. <a href="http://localhost/ClientSite/LibrarySite.Library.Pages.LibraryPage.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/localhost');">http://localhost/ClientSite/LibrarySite.Library.Pages.LibraryPage.aspx</a> will cause the IHTTPHandlerFactory to load and execute the page LibrarySite.Library.Pages.LibraryPage). If it is unable to find a match, the IHTTPHandlerFactory returns the result of the base (standard) IHTTPHandlerFactory.</p>
<p>The web service implementation for this came from this fantastic posting on codeproject: <span style="font-size: x-small; color: #008000;"><span style="font-size: x-small; color: #008000;"><a href="http://secure.codeproject.com/KB/cpp/WebserviceAndJavaProxy.aspx?display=Print" onclick="javascript:pageTracker._trackPageview('/outbound/article/secure.codeproject.com');">http://secure.codeproject.com/KB/cpp/WebserviceAndJavaProxy.aspx?display=Print</a>. <span style="color: #000000;">The author took great care to ensure his solution worked with JSON enabled web services which is very helpful.</span></span></span></p>
<p>In contrast to the web services code, the IHTTPHandlerFactory is much simpler:<br />
Note: the framework caches the mappings between virtualPath and the IHTTPHandler returned so the probe for matching page handlers is only done once per virtualPath.</p>
<blockquote><p>public override IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path)<br />
{<br />
 // Try to get the type associated with the request (On a name to type basis)<br />
 Type pageType = this.GetPageServiceType(Path.GetFileNameWithoutExtension(path));<br />
 // if we did not find any send it on to the original ajax script service handler.<br />
 if (pageType == null)<br />
 {<br />
  return base.GetHandler(context, requestType, virtualPath, path);<br />
 }<br />
 else<br />
 {</p>
<p>  return (Page)Activator.CreateInstance(pageType);<br />
 }<br />
}</p>
<p>  /// &lt;summary&gt;<br />
  /// Searches all Services and tries to find a class with the specified name<br />
  /// &lt;/summary&gt;<br />
  private Type GetPageServiceType(string pageTypeName)<br />
  {<br />
   // Todo: Caching mechanism for assembly checks<br />
   foreach (Assembly loadedAssembly in AppDomain.CurrentDomain.GetAssemblies())<br />
   {<br />
    Type basePageType = loadedAssembly.GetType(pageTypeName);<br />
    if (basePageType != null)<br />
    {<br />
     var services = from t in loadedAssembly.GetTypes()<br />
           where t.IsSubclassOf(basePageType)<br />
            select t;<br />
     var pageType = services.FirstOrDefault();<br />
     if (pageType != null)<br />
     {<br />
      return pageType;<br />
     }<br />
    }<br />
   }<br />
   return null;<br />
  }</p></blockquote>
<p>A working sample of all of this is <a href="http://www.blogfor.net/wp-content/uploads/2008/11/websitelibrarywebsiteclientnomarkupfiles.zip" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/2008/11/websitelibrarywebsiteclientnomarkupfiles.zip');">here.</a></p>
<p><span style="font-size: x-small; color: #008000;"><span style="font-size: x-small; color: #008000;"><span style="font-size: x-small; color: #008000;"></span></span></span></p>
<p> </p>
<p> </p>
<p><span style="font-size: x-small; color: #008000;"></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/11/03/creating-class-libraries-of-aspnet-web-components/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Migrating Asp.Net SiteMaps to MS SQL (or fun with MS SQL XML functions)</title>
		<link>http://www.blogfor.net/2008/10/20/migrating-aspnet-sitemaps-to-ms-sql-or-fun-with-ms-sql-xml-functions/</link>
		<comments>http://www.blogfor.net/2008/10/20/migrating-aspnet-sitemaps-to-ms-sql-or-fun-with-ms-sql-xml-functions/#comments</comments>
		<pubDate>Tue, 21 Oct 2008 02:06:46 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[t-sql]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=45</guid>
		<description><![CDATA[As part of a larger project, my recent work has involved migrating Asp.Net sitemaps from Xml to MS SQL in order to use a modified version of the SqlSiteMapProvider. 
Using the xml processing functions new in MS SQL 2005, sitemap files can be imported ease.
A &#8220;regular&#8221; sitemap file is going to look like this:

&#60;siteMap&#62;
  &#60;siteMapNode [...]]]></description>
			<content:encoded><![CDATA[<p>As part of a larger project, my recent work has involved migrating Asp.Net <a href="http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">sitemaps</a> from Xml to MS SQL in order to use a modified version of the <a href="http://msdn.microsoft.com/en-us/magazine/cc163657.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">SqlSiteMapProvider</a>. <br />
Using the <a href="http://msdn.microsoft.com/en-us/library/ms345115.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">xml processing functions</a> new in MS SQL 2005, sitemap files can be imported ease.</p>
<p>A &#8220;regular&#8221; sitemap file is going to look like this:</p>
<pre name="code" class="xml">
&lt;siteMap&gt;
  &lt;siteMapNode title="Home" description="Home" url="~/default.aspx" SomeProperty="someValue"&gt;
    &lt;siteMapNode title="Products" description="Our products"
      url="~/Products.aspx"  SomeProperty="someValue"  SomeOtherProperty="someOtherValue"&gt;
      &lt;siteMapNode title="Hardware" description="Hardware choices"
        url="~/Hardware.aspx" SomeThirdProperty="someThirdValue"/&gt;
      &lt;siteMapNode title="Software" description="Software choices"
        url="~/Software.aspx" /&gt;
    &lt;/siteMapNode&gt;
    &lt;siteMapNode title="Services" description="Services we offer"
        url="~/Services.aspx"&gt;
        &lt;siteMapNode title="Training" description="Training classes"
          url="~/Training.aspx" /&gt;
        &lt;siteMapNode title="Consulting" description="Consulting services"
          url="~/Consulting.aspx" /&gt;
        &lt;siteMapNode title="Support" description="Supports plans"
          url="~/Support.aspx" /&gt;
    &lt;/siteMapNode&gt;
  &lt;/siteMapNode&gt;
&lt;/siteMap&gt;
</pre>
<p>using the script <a href='http://www.blogfor.net/wp-content/uploads/2008/10/populate-sitemap-table-from-xml.sql'>here</a> we can populate a table (created with this <a href="http://www.blogfor.net/wp-content/uploads/2008/10/create-sitemap-table.sql" >script</a>). </p>
<p><em>Note: siteMap nodes can contain custom <a href="http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.attributes.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">additional attributes</a>. This script inserts these attributes into the AdditionalProperties column as xml elements:<br />
</em></p>
<pre name="code" class="xml">
    &lt;siteMapNode title="Products" description="Our products"
      url="~/Products.aspx"  SomeProperty="someValue"  SomeOtherProperty="someOtherValue"&gt;
</pre>
<p>becomes</p>
<pre name="code" class="xml">
&lt;row name="SomeProperty" value="someValue"/&gt;
&lt;row name="SomeOtherProperty" value="someOtherValue"/&gt;
</pre>
<p>The bulk of the work is down in this query:</p>
<pre name="code" class="sql">
select T.c.value('@url', 'nvarchar(255)') as url
, T.c.value('@title', 'nvarchar(255)') as title
, isnull(T.c.value('@description', 'nvarchar(255)'), '') as description
,
	(select U.c.value('local-name(.)', 'varchar(255)') as name , U.c.value('.', 'varchar(255)') as value
	from T.c.nodes('@*[local-name(.) != "url" and local-name(.) != "title" and local-name(.) != "description"]&#8216;) U(c)
	FOR XML RAW
)
as AdditionalProperties
,T.c.value(&#8217;../@url&#8217;, &#8216;nvarchar(255)&#8217;) as parentUrl
from @xml.nodes(&#8217;/siteMap//siteMapNode&#8217;) T(c);
</pre>
<p>First we parse the xml variable into &#8220;rows&#8221; using the nodes() function to query to for all the &#8220;siteMapNode&#8221; elements.<br />
To build the &#8220;AdditionalProperties&#8221; value for an element node, we do the following:<br />
Parse the element attributes into rows using the XPath query &#8220;@*&#8221;.<br />
Filter out attribute rows with already defined names (url, title, etc.)<br />
Combine the result set of attributes again into a single entry using the &#8220;FOR XML RAW&#8221; statement. </p>
<p><em>Note: this uses the MS SQL functions for untyped XML. If the config has an xmlns attribute, it must be removed before running the script.</em><br />
To verify the results, run the following query and compare the results to the source config file:</p>
<pre name="code" class="sql">with TMP ([id]
      ,[Title]
      ,[Description]
      ,[Url]
      ,[Roles]
      ,[Parent]
      ,[Sequence]
      ,[AdditionalProperties]
	  ,level)
as (
	SELECT [id]
      ,[Title]
      ,[Description]
      ,[Url]
      ,[Roles]
      ,[Parent]
      ,[Sequence]
      ,[AdditionalProperties]
	  ,0 as level
  FROM [SiteMap] as a
  where parent is null
  union all
	SELECT a.[id]
      ,a.[Title]
      ,a.[Description]
      ,a.[Url]
      ,a.[Roles]
      ,a.[Parent]
      ,a.[Sequence]
      ,a.[AdditionalProperties]
	  ,TMP.level + 1 as level
  FROM [SiteMap] as a
  inner join TMP on a.parent = TMP.id
)
select * from Tmp
order by level, sequence
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/10/20/migrating-aspnet-sitemaps-to-ms-sql-or-fun-with-ms-sql-xml-functions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Understanding the Javascript language from a .Net based background</title>
		<link>http://www.blogfor.net/2008/09/22/understanding-the-javascript-language-from-a-net-based-background/</link>
		<comments>http://www.blogfor.net/2008/09/22/understanding-the-javascript-language-from-a-net-based-background/#comments</comments>
		<pubDate>Tue, 23 Sep 2008 02:43:02 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[javascript]]></category>

		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=43</guid>
		<description><![CDATA[Ever wonder why the Microsoft samples for Ajax always call Function.createDelegate? Why IE6 has such bad memory leak problems? Ever wonder what &#8220;this&#8221; in javascript refers to?
Javacript is dynamic and interpreted.  Superficially this means that:

all objects have a dictionary of properties. One can then modify this dictionary in a very tangible if not intuitive sense by [...]]]></description>
			<content:encoded><![CDATA[<p>Ever wonder why the Microsoft samples for Ajax always call Function.createDelegate? Why IE6 has such bad memory leak problems? Ever wonder what &#8220;this&#8221; in javascript refers to?</p>
<p>Javacript is <a href="http://en.wikipedia.org/wiki/Dynamic_programming_language" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">dynamic</a> and <a href="http://en.wikipedia.org/wiki/Interpreted_language" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">interpreted</a>.  Superficially this means that:</p>
<ul>
<li>all objects have a dictionary of properties. One can then modify this dictionary in a very tangible if not intuitive sense by simply setting properties on the object.<br />
var x = [];<br />
x.someProperty = 1;</li>
<li>the dictionary of properties can be enumerated like a collection<br />
for (var property in object) {..}</li>
<li>arrays are really just objects with properties, the &#8220;key&#8221; in the dictionary is the array index<br />
var x = <span class="objectBox objectBox-text">{0:&#8221;test&#8221;}</span> ;<br />
is the same as<br />
x = ["test"];</li>
<li>one can use the &#8220;eval&#8221; statement to translate and execute any string of code<br />
var p;<br />
eval(&#8221;p=1&#8243;);<br />
will set p equal to one.</li>
</ul>
<p>There are, however, some more basic questions whose answer is not quite obvious such as:</p>
<ul>
<li>how does one implement inheritance?</li>
<li>what does &#8220;this&#8221; refer to?</li>
<li>what is the difference between calling a shared method and an instance method? How does one denote one versus the other?</li>
<li>how do I bind an html element&#8217;s event to an event handler method on my object?</li>
<li>how do I bind an object event to an event handler method on another object?</li>
</ul>
<p>Most developers assume that Javascript is merely the scripting equivalent of java, but that is not so. To quote Douglas Crockford (JavaScript Architect at Yahoo!):</p>
<blockquote><p>JavaScript&#8217;s C-like syntax, including curly braces and the clunky for statement, makes it appear to be an ordinary procedural language. This is misleading because JavaScript has more in common with functional languages like Lisp or Scheme than with C or Java. It has arrays instead of lists and objects instead of property lists. Functions are first class. It has closures. You get lambdas without having to balance all those parens.</p></blockquote>
<p>Coming from a .net background, I really don&#8217;t remember much about Lisp from college - I remember lists, lots of parentheses, and thinking &#8220;It&#8217;s all about recursion&#8221;. One key feature of Javascript is the <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">closure</a>. To quote wikipedia:</p>
<blockquote><p>a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables.</p></blockquote>
<p>A good explanation with examples can be found <a href="http://www.javascriptkit.com/javatutors/closures.shtml" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.javascriptkit.com');">here</a>. In javascript one can still create object oriented code with private and public methods. It is not, however, intuitive to do so. Opposite from .net, standard class methods are public and accessible as static members. Closures are what gives us state in our methods by binding variables to objects when the method is executed, particularly the &#8220;this&#8221; object based on context.</p>
<p>In ASP.Net, one adds an event handler like so:<br />
textBox.TextChanged += new EventHandler(SomeObject.TextChangedHandler);</p>
<p>In order for this to work, &#8220;SomeObject&#8221; must be instantiated and the TextChanged event bound to &#8220;SomeObject&#8221;. </p>
<p>Suppose instead that I could create a new method like so:</p>
<p>textBox.TextChanged += new Function(sender,eventArgs=&gt;some other code)</p>
<p>In this case I don&#8217;t need to initialize an object or create a static method to handle the TextChanged event. Instead I create an anonymous function and databind the sender and eventArgs parameters to the caller and the caller&#8217;s event args.</p>
<p>This is exactly what Javascript has been doing since IE5. The coding emphasis is now on the function to handle the event using databound variables rather than forcing the developer to go through hoops to instantiate objects and wire up methods on those objects. The mechanism that lets you do this is the closure.</p>
<p>Closures lead to certain issues, however, specifically the <a href="http://en.wikipedia.org/wiki/Funarg_problem" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">funarg</a> problem.  Simplify stated a closure may contain a reference to almost any object on the heap. The garbage collector now has to determine if an object is referenced by any closures before destruction. The amount of additional work reqiured for reference counting and object graph traversal is monstrous.</p>
<p>The garbage collection algorithm used by IE6 has been notorious for <a href="http://support.microsoft.com/kb/929874" onclick="javascript:pageTracker._trackPageview('/outbound/article/support.microsoft.com');">leaking memory due to poor garbage collection</a>. In November 2007, Microsoft finally recognized the <a href="http://support.microsoft.com/kb/830555/" onclick="javascript:pageTracker._trackPageview('/outbound/article/support.microsoft.com');">problem</a> and released a partial <a href="http://support.microsoft.com/kb/929874/en-us" onclick="javascript:pageTracker._trackPageview('/outbound/article/support.microsoft.com');">fix</a>. Microsoft notes <a href="http://msdn.microsoft.com/en-us/library/bb250448.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">here</a> that:</p>
<blockquote><p>New Web applications live up to higher standards. A page might run for hours without being navigated and retrieve updated information dynamically through Web services. Language features are pushed to the breaking point by combining complex event schemes, object-oriented JScript, and closures to produce entire applications. With these and other changes, certain memory leak patterns are becoming more prominent, especially those previously hidden by navigation.</p>
<p>The good news is that memory leak patterns can be easily spotted if you know what to look for. Most of the troublesome patterns you might face have known workarounds requiring only a small amount of extra work on your behalf. While some pages might still fall prey to small memory leaks, the most noticeable ones can be easily removed&#8230;.</p>
<p>Closures are a specific form of circular reference that pose the largest pattern to existing Web application architectures. Closures are easy to spot because they rely on a specific language keyword and can be searched for generically</p></blockquote>
<p>If Javascript is more like scheme or Lisp than Java, then perhaps just learning a new syntax isn&#8217;t enough to properly code Javascript. Take a moment and check out Douglas Crockford&#8217;s <a href="http://www.crockford.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.crockford.com');">site</a>, particularly his javascript <a href="http://javascript.crockford.com/survey.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/javascript.crockford.com');">tutorial</a> and javascript <a href="http://javascript.crockford.com/javascript.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/javascript.crockford.com');">history</a>. The more you learn about Javascript, the more you will realize how vastly different it is from any Microsoft technology prior to .net 3.5.  You&#8217;ll also get a much better idea how the language constructs of .net 3.5 (lambda expressions, closures, extensions, etc.) are revolutionary in bringing some of the power and flexibility of dynamic languages into static ones without sacrificing compile time type checking and performance.</p>
<p>What is easy and clean in javascript (using the prototype library):</p>
<blockquote><p>originalList.findAll<span class="brackets">(</span><span class="keywords">function</span><span class="brackets">(p</span><span class="brackets">)</span> {<br />
  <span class="keywords">return</span> p.Age &gt; 50;<br />
}<span class="brackets">)</span></p></blockquote>
<p>Is now just as easy in .net 3.5:</p>
<blockquote><p>results = origionaList.Where(p=&gt;p.Age &gt; 50).ToList();</p></blockquote>
<p>If you&#8217;re working on a javascript heavy application, take the time to learn about the language and to lever its inherent features rather than try and bend it to a static language paradigm.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/09/22/understanding-the-javascript-language-from-a-net-based-background/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Testing HTTP Handlers And Modules Without A Web Server</title>
		<link>http://www.blogfor.net/2008/09/22/testing-http-handlers-and-modules-without-a-web-server/</link>
		<comments>http://www.blogfor.net/2008/09/22/testing-http-handlers-and-modules-without-a-web-server/#comments</comments>
		<pubDate>Tue, 23 Sep 2008 02:05:19 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=44</guid>
		<description><![CDATA[Recently I came across this posting at Cozi Tech Blog:

A Way To Unit Test ASP.NET IHttpHandler Implementations


If you find yourself writing simple HTTP handler code that produces and consumes structured data (for instance, some RESTful application), you may wonder how to test it without fiddling with IIS or configuration files. Here&#8217;s a trick to write pure [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I came across this <a href="http://blogs.cozi.com/tech/2008/05/a-way-to-unit-t.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.cozi.com');">posting</a> at Cozi Tech Blog:</p>
<blockquote>
<h3 class="entry-header">A Way To Unit Test ASP.NET IHttpHandler Implementations</h3>
<div class="entry-content">
<div class="entry-body">
<p>If you find yourself writing simple HTTP handler code that produces and consumes structured data (for instance, some RESTful application), you may wonder how to test it without fiddling with IIS or configuration files. Here&#8217;s a trick to write pure unit tests that verify your <code>IHttpHandler</code> implementation does what you expect. By &#8220;pure unit tests&#8221;, I mean test code that:</p>
<ul>
<li>works without configuration files (like web.config);</li>
<li>needs no servers (like Cassini, IIS, or your own mock HTTP server with full ASP.NET pipeline that you were about to write and debug just before you stumbled upon this article);</li>
<li>doesn&#8217;t access file system (like ashx files);</li>
</ul>
</div>
</div>
<li>avoids globals (like <code>HttpContext.Current</code>).<br />
&#8230;</li>
</blockquote>
<p>At the core of the post is the <a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.simpleworkerrequest.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');"><span style="color: #000000;">System.Web.Hosting.S</span>impleWorkerRequest</a> object in the System.Web.Hosting namespace. It provides an easy way to create http requests and pass them to a handler. The posting gives a nice example and referencing a  <a href="http://code.google.com/p/codebackpack/source/browse/tags/how-to-test-httphandlers/src/TestHttp/WorkerRequestStub.cs" onclick="javascript:pageTracker._trackPageview('/outbound/article/code.google.com');">custom version of SimpleWorkerRequest</a> on google code.</p>
<p>The SimpleWorkerRequest implementation referenced has a small bug with querystring values and is limited in scope. Some additional things I wanted to test were HTTP Headers (expiration, mime type, etc.) and file attachments. To test these things, modify WorkerRequestStub to override <a href="http://msdn.microsoft.com/en-us/library/system.web.httpworkerrequest.sendresponsefromfile.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">SendResponseFile</a>, <a href="http://msdn.microsoft.com/en-us/library/system.web.httpworkerrequest.sendunknownresponseheader.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">SendKnownResponseHeaders</a>, and <a href="http://msdn.microsoft.com/en-us/library/system.web.httpworkerrequest.sendknownresponseheader.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">SendUnknownResponseHeaders</a> to track and expose the headers and file submissions to the testing container.</p>
<p>While testing web based UIs is still a difficult and expensive problem there&#8217;s no reason testing web services should be.</p>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/09/22/testing-http-handlers-and-modules-without-a-web-server/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Properly using the &#8220;references&#8221; parameter to the MS Ajax $create statement</title>
		<link>http://www.blogfor.net/2008/08/10/properly-using-the-references-parameter-to-the-ms-ajax-create-statement/</link>
		<comments>http://www.blogfor.net/2008/08/10/properly-using-the-references-parameter-to-the-ms-ajax-create-statement/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 15:24:29 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=39</guid>
		<description><![CDATA[the MS Ajax framework provides a built in method to initialze extenders and wire up references between them. Unfortunately, there is very little documentation on how to do so. This is my quick example.]]></description>
			<content:encoded><![CDATA[<p>Suppose you want to reference a component from another component. The MS Ajax documentation gives the following explanation of the <a href="http://www.asp.net/AJAX/Documentation/Live/ClientReference/Global/CreateShortcutMethod.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">$create</a> function:</p>
<blockquote>
<h2>Syntax</h2>
<div class="code">
<pre>$create(<span class="parameter">type, properties, events, references, element</span>);</pre>
</div>
<h2 class="subsectionTitle">Arguments</h2>
<table class="authoredTable" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<th>Parameter</th>
<th>Description</th>
</tr>
<tr>
<td><span class="parameter">type</span></td>
<td>The type of the component to create.</td>
</tr>
<tr>
<td><span class="parameter">properties</span></td>
<td>(Optional) A JSON object that describes the properties and their values.</td>
</tr>
<tr>
<td><span class="parameter">events</span></td>
<td>(Optional) A JSON object that describes the events and their handlers.</td>
</tr>
<tr>
<td><span class="parameter"><strong>references</strong></span></td>
<td><strong>(Optional) A JSON object that describes the properties that are references to other components.</strong></td>
</tr>
<tr>
<td><span class="parameter">element</span></td>
<td>(Optional) The DOM element that the component must be attached to.</td>
</tr>
</tbody>
</table>
</blockquote>
<p>The documentation doesn&#8217;t provide much information, however, on why you should use the references parameter instead of just using the <a href="http://www.asp.net/AJAX/documentation/live/ClientReference/Global/FindShortcutMethod.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">$find</a> method in the initialize event of your component.</p>
<p>When the framework renders <a href="http://www.asp.net/AJAX/Documentation/Live/ClientReference/Global/CreateShortcutMethod.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">$create</a> statements through the <a href="http://www.asp.net/AJAX/Documentation/Live/overview/ScriptManagerOverview.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">scriptmanager</a>,  each script descriptor becomes a $create statement in the page source. These statements are executed by the ajax framework when page_load. In order for a component instance to reference another component instance, the object being referenced has to exist already.  If the $create statement for the object being referenced comes after the referencing component&#8217;s $create, an error will occur when the $find method is called.</p>
<p>One way around this is to execute $find every time that the component needs to be referenced. This has performance implications and doesn&#8217;t scale well when dealing with collections of components.</p>
<p>Another way around this is to use the MS Ajax <a href="http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys/ApplicationClass/SysApplicationLoadEvent.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">Application_load event</a> using code similar to the following:</p>
<pre name="code" class="javascript">MyNamespace.MyComponent.prototype = {
 initialize: function() {
  MyNamespace.MyComponent.callBaseMethod(this, 'initialize');

  this._applicationLoadHandler = Function.createDelegate( this, this.applicationLoad );
  Sys.Application.add_load( this._applicationLoadHandler );
  
 },

 applicationLoad: function(sender, e) {
 
  this._componentReference = $find(this._componentReferenceId);
  //Remove the LoadHandler 
  Sys.Application.remove_load( this._applicationLoadHandler );
  this._applicationLoadHandler = null;
 },
 
 set_ComponentReferenceId : function( value ) {
  this._componentReferenceId = value;
 },
  
 get_ComponentReferenceId : function() {
  return this._componentReferenceId;
 }
 // other code
}</pre>
<p>This approach is explicit and therefore more clear to other developers who might inherit your code. Additionally for collections of components, this method is an excellent option.</p>
<p>The framework does, however, does provide a way to ensure that when the initialize method is called, the component references have already been set just like other component properties.</p>
<p>If our custom component inherits from AjaxControlToolkit.ExtenderControlBase, we can add the AjaxControlToolkit.ComponentReference attribute to the property declaration</p>
<pre name="code" class="c#">&lt;AjaxControlToolkit.RequiredProperty()&gt; _
&lt;AjaxControlToolkit.ExtenderControlProperty()&gt; _
&lt;IDReferenceProperty()&gt; _
&lt;AjaxControlToolkit.ComponentReference()&gt; _
&lt;AjaxControlToolkit.ClientPropertyName("ComponentReference")&gt; _
Public Property ComponentReferenceId() As String
 Get
  Return GetPropertyValue(Of String)("ComponentReferenceId", String.Empty)
 End Get
 Set(ByVal value As String)
  SetPropertyValue(Of String)("ComponentReferenceId", value)
 End Set
End Property
</pre>
<p><i>Note: we also need to change the getter/setter methods in the javascript to:</i></p>
<blockquote><p>set_ComponentReference : function( value ) {<br />
  this._componentReference = value;<br />
},<br />
get_ComponentReference : function() {<br />
  return this._componentReference;<br />
}</p></blockquote>
<p>Before the initialize method is called the framework will now call set_ComponentReference and pass $find(value from the server side property) as the sole parameter.</p>
<p>If you&#8217;re not extending from AjaxControlToolkit.ExtenderControlBase, you can perform the same operation by using the SetComponent method in the GetScriptDescriptors method:</p>
<pre name="code" class="c#">Protected Overrides Function GetScriptDescriptors(ByVal targetControl As System.Web.UI.Control) As System.Collections.Generic.IEnumerable(Of System.Web.UI.ScriptDescriptor)
 Dim descriptor As New ScriptBehaviorDescriptor("MyNamespace.MyComponent", targetControl.ClientID)
 descriptor.AddComponentProperty("ComponentReference",Me.ComponentReference)
 ...
 Return New ScriptDescriptor() {descriptor}
End Sub</pre>
<p>In either event, the net result should be a statment similar to the following generated by the framework in the page source:</p>
<blockquote><p>Sys.Application.add_init(function() {<br />
    $create(MyNamespace.MyComponent, {&#8230;,&#8221;id&#8221;:&#8221;CustomComponentId&#8221;}, null, $find(&#8221;RefefencedBehaviorId&#8221;), $get(&#8221;targetControlId)&#8221;));<br />
});</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/08/10/properly-using-the-references-parameter-to-the-ms-ajax-create-statement/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Binding MS Ajax Extenders to nested Controls</title>
		<link>http://www.blogfor.net/2008/08/10/binding-ms-ajax-extenders-to-nested-controls/</link>
		<comments>http://www.blogfor.net/2008/08/10/binding-ms-ajax-extenders-to-nested-controls/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 15:17:58 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=40</guid>
		<description><![CDATA[How to use the AjaxControlToolkit.ExtenderControlBase's method "ResolveControlProperty" to locate controls contained inside other naming containers.]]></description>
			<content:encoded><![CDATA[<p>The MS Ajax Extender model encourages us to bind html elements to extender properties via clientId. To help make this more declarative, the ajax control toolkit provides property attributes to do this <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Walkthrough/ExtenderClasses.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">mapping</a> between server side control property and client side javascript accessor methods:</p>
<blockquote><p><span style="font-size: 10pt; font-family: 'Courier New';">[<span style="color: #008080;">IDReferenceProperty</span>(<span style="color: #0000ff;">typeof</span>(<span style="color: #008080;">WebControl</span>))] </span><br />
<span style="FONT-SIZE: 10pt"><span style="font-family: 'Courier New';">[<span style="color: #008080;">DefaultValue</span>(<span style="color: #0000ff;">""</span>)]<br />
[<span style="color: #008080;">ExtenderControlProperty</span>]<br />
[<span style="color: #008080;">ClientPropertyName("popupElement")</span>]<br />
[<span style="color: #008080;">ElementReference</span>]<br />
[<span style="color: #008080;">ExtenderControlProperty</span>]<br />
</span></span><br />
<span style="font-size: 10pt; color: #0000ff; font-family: 'Courier New';">public</span><span style="font-size: 10pt; font-family: 'Courier New';"> <span style="color: #0000ff;">string</span> PopupControlID { � }</span></p></blockquote>
<p><span style="font-size: x-small; font-family: Courier New;">In this case, the framework will call a method on the javascript extender called &#8220;set_popupElement&#8221; and pass it the result of $get(&#8221;value from PopupControlId on the server side&#8221;).</span></p>
<p><span style="font-size: x-small; font-family: Courier New;">This method works well until you want to bind the extender against elements contained in a different naming container. For example, suppose you create a custom extender to populate a popup panel depending on what link a user clicks upon. </span></p>
<p><span style="font-size: x-small; font-family: Courier New;">Assume the popup panel control is in fact an asp.net panel. Since panel implements <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">INamingContainer</a>, the custom extender will not locate any elements inside it because the extender&#8217;s parent control (the one whose childControls collection it searches) is not the panel itself. Since FindControl() is not recursive, when the extender tries to find the controls inside the panel by Id, it will be unable to locate them. </span></p>
<p><span style="font-size: x-small; font-family: Courier New;">One limited workaround is to move the extender inside the asp.net panel. This will work until the extender has to resolve controls both inside and outside the popup panel.</span></p>
<p><span style="font-size: x-small; font-family: Courier New;">Another workaround is to set the element ids in the code behind. </span></p>
<blockquote><p><span style="font-size: x-small; font-family: Courier New;">MyExtender.PopupControlId = this.PopupPanel.FindControl(&#8221;elementToBindAgainst&#8221;);</span></p></blockquote>
<p> this can be quite tedious depending on the number of controls you want to bind against and is less intuitive than the declarative approach.</p>
<p>Assuming the extender inherits from AjaxControlToolkit.ExtenderControlBase, a more flexible method is to override the ResolveControlProperty method as follows:</p>
<pre name="code" class="c#"> public string SearchContainerPaths { get; set; }

  private bool searchControlsInitialized;
  private System.Collections.Generic.List&lt;Control&gt; searchContainers = new System.Collections.Generic.List&lt;Control&gt;();
  protected void ResolveControlProperty(object sender, ResolveControlEventArgs e)
  {
   if (string.IsNullOrEmpty(e.ControlID))
   {
    return;
   }

   if (!this.searchControlsInitialized) //check tosee if we've built the "probe" collection of containers to search
   {
    char[] splitChar = new char[] {&#8217;.'};
    string[] controlPaths = this.SearchContainerPaths.Split(new char[] {&#8217;,'});
    foreach (string path in controlPaths) {
     string[] subPaths = path.Split(splitChar);
     Control ctl = this.Parent;
     foreach (string controlId in subPaths)
     {
      ctl = ctl.FindControl(controlId);
      if (ctl == null)
      {
       throw new ArgumentException(&#8221;Cannot find path:&#8221; + path);
      }
     }
     this.searchContainers.Add(ctl);
    }
    searchControlsInitialized = true;
   }
   Control tmpCtl = null;
   foreach (Control control in this.searchContainers)
   {
    tmpCtl = control.FindControl(e.ControlID);
    if (tmpCtl != null)
    {
     e.Control = tmpCtl; //the control is found, set it and exit.
     break;
    }
   }
   if (tmpCtl == null) //unable to find control in map paths, throw an exception.
   {
    throw new ArgumentException(&#8221;Cannot find controlId: &#8221; + e.ControlID);
   }
  }</pre>
<p>By setting SearchContainerPaths we can now probe for any controls outside the immediate naming container e.g. SearchContainerPaths=&#8221;panel1.panel2,modalPanel&#8221; will search the controls collection of panel2 (contained in panel1) and the controls collection of modalPanel.</p>
<p>This <a href="http://www.blogfor.net/wp-content/uploads/2008/08/resolvecontrolpropertysample1.zip" onclick="javascript:pageTracker._trackPageview('/downloads/wp-content/uploads/2008/08/resolvecontrolpropertysample1.zip');">sample</a> gives an example of this using the modalPopupBehavior and a customExtender to bind the popup panel.</p>
<p> </p>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/08/10/binding-ms-ajax-extenders-to-nested-controls/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Perils of Sys.UI.Component and Update Panels</title>
		<link>http://www.blogfor.net/2008/08/10/perils-of-sysuicomponent-and-update-panels/</link>
		<comments>http://www.blogfor.net/2008/08/10/perils-of-sysuicomponent-and-update-panels/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 15:06:22 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=38</guid>
		<description><![CDATA[Howto avoid duplicate extender objects when using update panels and custom extenders.]]></description>
			<content:encoded><![CDATA[<p>When writing custom MS Ajax controls, deciding what framework class to inherit from on the client can be tricky. The MS Ajax <a href="http://www.asp.net/AJAX/Documentation/Live/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">documentation</a> gives the following explanation of the <a href="http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys/ComponentClass/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">Sys.UI.Component</a> and it&#8217;s associated child classes <a href="http://www.asp.net/AJAX/Documentation/Live/tutorials/CreatingCustomClientComponentsTutorial.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">here</a>:</p>
<table class="authoredTable" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<th>Client component object types</th>
<th>Summary</th>
</tr>
<tr>
<td>Components</td>
<td>
<ul>
<li>Derive from the Component base class.</li>
<li>Typically have no UI representation, such as a timer component that raises events at intervals but is not visible on the page.</li>
<li>Have no associated DOM elements.</li>
<li>Encapsulate client code that is intended to be reusable across applications.</li>
</ul>
</td>
</tr>
<tr>
<td>Behaviors</td>
<td>
<ul>
<li>Derive from the Behavior base class, which extends the Component base class.</li>
<li>Extend the behavior of DOM elements, such as a watermarking behavior that can be attached to an existing text box.</li>
<li>Can create UI elements, although they do not typically modify the basic behavior of the DOM element that they are associated with.</li>
<li>If assigned an ID, can be accessed directly from the DOM element through a custom attribute (expando).</li>
<li>Do not require an association with another client object, such as a class derived from the Control or Behavior classes.</li>
<li>Can reference either a control or a non-control HTML element in their <a href="http://www.blogfor.net/ClientReference/Sys.UI/BehaviorClass/BehaviorElementProperty.aspx" >element</a> property.</li>
</ul>
</td>
</tr>
<tr>
<td>Controls</td>
<td>
<ul>
<li>Derive from the Control base class, which extends the Component base class.</li>
<li>Represent a DOM element as a client object, typically changing the original DOM element&#8217;s ordinary behavior to provide new functionality. For example, a menu control might read <span class="keyword">&lt;li&gt;</span> items from a <span class="keyword">&lt;ul&gt;</span> element as its source data, but not display a bulleted list.</li>
<li>Are accessed from the DOM element directly through the control expando.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>If the difference between Behaviors and Controls isn&#8217;t clear to you, you&#8217;re not alone. In fact, depending on the version of microsoft documentation, or their horrific <a href="http://go.microsoft.com/fwlink/?LinkId=116063" onclick="javascript:pageTracker._trackPageview('/outbound/article/go.microsoft.com');">msdn documentation</a>, these terms are used almost interchangeably. Generally, behavior, extender, control all refer to the same thing - some custom code written in javascript and instantiated via $create.</p>
<p>Following the documentation then, if an extender does not have a target control it should inherit from Sys.UI.Component.</p>
<p>Suppose we have a page that&#8217;s using update panels and depending on the user action an extender (inheriting from Sys.UI.Component) is written to the page.</p>
<p>When a postback occurs the extender will be rendered to the page again. Now there will be a new extender and an existing extender both with the same id. This will cause a javascript error that&#8217;s hard to track down, something like &#8220;Behavior with Id:? already exists&#8221;.</p>
<p>The original instance of the extender should have been disposed when the update panel framework reloaded the page. Since the extender didn&#8217;t have a target element (the core difference between Sys.UI.Component and Sys.UI.Behavior), the framework didn&#8217;t know to dispose the extender object when the update panel refreshed its content. </p>
<p>To work around this, simply change the extender to inherit from Sys.UI.Behavior and giving it a target element. This will ensure that the object is disposed when the target element is disposed when either the update panel framework destroys the target element or the page is unloaded.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/08/10/perils-of-sysuicomponent-and-update-panels/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Converting VB to C# while preserving project references and existing solutions</title>
		<link>http://www.blogfor.net/2008/08/10/converting-vb-to-c-while-preserving-project-references-and-existing-solutions/</link>
		<comments>http://www.blogfor.net/2008/08/10/converting-vb-to-c-while-preserving-project-references-and-existing-solutions/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 14:59:05 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=37</guid>
		<description><![CDATA[Converting VB to C# on a large scale involves maintaining project and references properly. This post describes an easy way to do this to avoid rebuilding solutions and project references by hand after a conversion.]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve recently begun converting a tremendous amount of code from VB to C#.  Others have much better postings about the <a href="http://www.dnjonline.com/article.aspx?ID=mar05_vbvscsharp" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.dnjonline.com');">pros and cons</a> of chosing VB or C#.  The web is littered with religious rants from haughty C# developers (although they are in the <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.tiobe.com');">minority</a> of .net developers) about which managed language is <a href="http://discuss.joelonsoftware.com/default.asp?dotnet.12.369517.23" onclick="javascript:pageTracker._trackPageview('/outbound/article/discuss.joelonsoftware.com');">better</a>.</p>
<p>We chose VB originally because it was easier to develop against, it was a language the team was familiar with, and we didn&#8217;t have time to ramp both to .net 2.0 and all the quirks of C#. At the time, there were virtually no features of C# that we felt would make our work more efficient.  Over time, however, our team has changed - some of the original developers have moved on and some really smart people with a lot of strong C#/Java experience have joined us. We&#8217;ve also had two years to ramp up on .net 2.0 and are now moving on to 3.5 with enthusiasm.  Part of the point in moving to 3.5 is to leverage language features only available in C#.</p>
<p>The tool we selected for conversion is <a href="http://www.elegancetech.com/CSVB/CSVB.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.elegancetech.com');">C-Sharpener for VB.Net</a> because it converts projects in total and does <a href="http://www.elegancetech.com/CSVB/FAQ.aspx#HowWorks" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.elegancetech.com');">symbol comparison</a> on the output.  Minor quirks of the software include the following:</p>
<ol>
<li>in VB, int(5) means an array with upper-bound 5, but in C# int(5) means an array with 5 elements and upper-bound 4)</li>
<li>a small issue with complex generics- a dictionary whose value was also a generic does not convert properly</li>
<li>embedded resource references in C# require full names including directory path e.g. to access the embedded resource file name &#8220;MyResource.txt&#8221; in C#, we would need to call assembly.GetManifestResourceStream( &#8220;MyResourceFiles.SomeChildDirectory.MyResource.txt&#8221; ) as opposed to the seemingly simpler VB assembly.GetManifestResourceStream( &#8220;MyResource.txt&#8221; ).</li>
<li>namespace statements are parsed by period. &#8220;Namespace A.B.C&#8221; becomes<br />
namespace A<br />
{<br />
    namespace B<br />
    {<br />
        namespace C<br />
        {</li>
</ol>
<p>Once the project is converted, C-Sharpener gives adds the newly created C# project to your solution with the original project name and &#8220;_CS&#8221; appended to it.</p>
<p>In order to finish the conversion, we need make changes to unmodified versions solution (.sln file) via text editor.<br />
<em>note: C-Sharpener will change the solution when it runs to add the new C# project so be sure to revert the solution after the conversion.</em></p>
<p>Rather than go through every project&#8217;s references and update them to the GUID of the new project we&#8217;d like to simply reuse the GUID. This is relatively easy</p>
<ol>
<li>Open the source VB project&#8217;s vbproj file in a text editor and copy the inner text of the ProjectGuid element.</li>
<li>Open the csproj file of the newly created project in a text editor.</li>
<li>update the AssemblyNamespace and RootNamespace elements by removing the extra &#8220;_CS&#8221;</li>
<li>Update the &lt;ProjectGuid&gt; element - set the inner text of the element to the inner text of the ProjectGuid from the original vb project.</li>
<li>open all solutions containing the original vb project in a text editor.<br />
your vb project should be referenced in the file like so:Project(&#8221;{ProjectTypeGUID}&#8221;) = &#8220;MyAssembly&#8221;, &#8220;..\MyAssembly\MyAssembly.vbproj&#8221;, &#8220;{MyProjectGUID}&#8221;<br />
EndProject</li>
<li>update the path to the newly created cs projectProject(&#8221;{ProjectTypeGUID}&#8221;) = &#8220;MyAssembly&#8221;, &#8220;..\MyAssemblyInCSharp\MyAssembly.csproj&#8221;, &#8220;{MyProjectGUID}&#8221;<br />
EndProject</p>
<p><em>note: you&#8217;ll need to update the path to the csproj and make sure the GUID following it (MyProjectGUID) is the same as the one you pasted from the VB project.<br />
</em></li>
<li>The ProjectTypeGUID indicates to Visual Studio when it tries to compile your solution what kind of project it is - C#, VB, Cobol etc. for example, one of our solutions contains C#, VB, and web deployment projects. It looks like this:Project(&#8221;{F184B08F-C81C-45F6-A57F-5ABD9991F28F}&#8221;) = &#8220;VBProject&#8221;, &#8220;..\VBProject\VBProject.vbproj&#8221;, &#8220;{27509F53-2929-459A-8B1E-E03ADA1D8B36}&#8221;<br />
EndProject</p>
<p>Project(&#8221;{2CFEAB61-6A3B-4EB8-B523-560B4BEEF521}&#8221;) = &#8220;WebDeploymentProject&#8221;, &#8220;WebDeploymentProject.wdproj&#8221;, &#8220;{24F3E583-E313-48D6-92ED-A137AC83BBDB}&#8221;<br />
EndProject</p>
<p>Project(&#8221;{F184B08F-C81C-45F6-A57F-5ABD9991F28F}&#8221;) = &#8220;VBProject2&#8243;, &#8220;..\VBProject2\VBProject2.vbproj&#8221;, &#8220;{C73B5D28-96D6-4B29-B90D-E0E3788F0692}&#8221;<br />
EndProject</p>
<p>Project(&#8221;{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}&#8221;) = &#8220;CSharpProject&#8221;, &#8220;..\CSharpProject\CSharpProject.csproj&#8221;, &#8220;{D20CCA67-387E-4B1F-9232-1EEE1359CD9E}&#8221;<br />
EndProject</p>
<p>note how the second GUID in each project is unique. The first GUID is the one you need to change to tell the solution that the project is no longer a VB project but a C# one instead. For your project, update ProjectTypeGUID to the C# guid - FAE04EC0-301F-11D3-BF4B-00C04F79EFBC.</li>
</ol>
<p> </p>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/08/10/converting-vb-to-c-while-preserving-project-references-and-existing-solutions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Interface Segregation Principle, Asp.Net, Generics, Interfaces and Covariance, Oh my!</title>
		<link>http://www.blogfor.net/2008/08/10/interface-segregation-principle-aspnet-generics-interfaces-and-covariance-oh-my/</link>
		<comments>http://www.blogfor.net/2008/08/10/interface-segregation-principle-aspnet-generics-interfaces-and-covariance-oh-my/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 14:52:23 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=36</guid>
		<description><![CDATA[The interface segregation principle is something most asp.net developers tend to ignore. If I only have one consumer of my business layer (the web/UI layer) why bind against an interface instead of the actual business objects?
Recently at my job we found ourselves answering that question. We have a single code base and strong continuous integration. [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://c2.com/cgi/wiki?InterfaceSegregationPrinciple" onclick="javascript:pageTracker._trackPageview('/outbound/article/c2.com');">interface segregation principle</a> is something most asp.net developers tend to ignore. If I only have one consumer of my business layer (the web/UI layer) why bind against an interface instead of the actual business objects?</p>
<p>Recently at my job we found ourselves answering that question. We have a single code base and strong continuous integration. Binding to UI interfaces seemed to make things &#8220;less agile&#8221; :). Now that we&#8217;re live, however, things have changed. We&#8217;re willing to sacrifice the beautiful patterns we&#8217;ve held so dear for the pragmatic concerns of performance and scalability.</p>
<p>We analyzed our application for problems and began to work around some of our thornier speed issues by writing custom sql that could leverage vendor specific database features and using the caching features of the asp.net framework.</p>
<p>The problem is that our business entities are too heavy - these custom queries were faster in part because we didn&#8217;t need to retrieve all the data necessary to initialize an entity. Additionally, to avoid <a href="http://blogs.msdn.com/tess/archive/2008/05/28/asp-net-memory-thou-shalt-not-store-ui-objects-in-cache-or-session-scope.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">GC problems</a>, the data we wanted to cache needed to be much &#8220;lighter&#8221; without references to other objects or data context.</p>
<p>Our web code was now too rigid. It was binding against strongly typed business objects and needed to bind against interfaces to give us the flexibility and control re-use we needed. We therefore adjusted the necessary Asp.net controls that bound to entities to bind to interfaces instead.</p>
<p>A problem arose, however, when we went to bind lists. The problem is called <a href="http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">covariance</a> and discussed very well <a href="http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">here</a> and compared with JAVA <a href="http://www.jprl.com/Blog/archive/development/2007/Aug-31.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.jprl.com');">here</a>. Basically, to optimize performance, the .net runtime emits code to strongly type collections. This new type has no ties to the interfaces or inheritance hierarchy of the type that it is templating e.g. If A is the base class of B and C, one cannot pass a List&lt;B&gt; to a method expecting a paramter of type List&lt;A&gt;.</p>
<p>The way around this is actually pretty simple. It&#8217;s how most asp.net controls work out of the box. A control&#8217;s <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.datasource.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">datasource</a> is simply an object. Only when <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.databind.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">DataBind()</a> is called is the datasource consumed, and then it&#8217;s consumed item by item in the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.onitemdatabound.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">ItemDataBound</a> event where there is no problem casting individual items of a datasource to an interface.</p>
<p>This paradigm works well. Though we can&#8217;t cast strongly typed generic lists based we can cast Foo to IFoo as we consume each item for databinding. The result is a more flexible UI with more code re-use and improved performance.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/08/10/interface-segregation-principle-aspnet-generics-interfaces-and-covariance-oh-my/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Hallmarks of great developers</title>
		<link>http://www.blogfor.net/2008/08/10/hallmarks-of-great-developers/</link>
		<comments>http://www.blogfor.net/2008/08/10/hallmarks-of-great-developers/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 14:45:52 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[general]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=26</guid>
		<description><![CDATA[At my current employer we&#8217;ve spent a long time trying to refine our hiring process. While the process is by no means ideal, after conducting dozens of interviews a few key indictators of great developers have emerged. While not requirements, the developers we&#8217;ve hired who are successful and continue to innovate, improvise, and impress all [...]]]></description>
			<content:encoded><![CDATA[<p>At my current employer we&#8217;ve spent a long time trying to refine our hiring process. While the process is by no means ideal, after conducting dozens of interviews a few key indictators of great developers have emerged. While not requirements, the developers we&#8217;ve hired who are successful and continue to innovate, improvise, and impress all share these qualities.</p>
<ol>
<li>Reading books.<br />
This one sounds simple. One applicant I spoke with said &#8220;Books make a good reference but I find online resources better for learning and keeping up with technology&#8221;. This misses the point entirely. Books are indeed a great reference - they&#8217;re more than just a quick answer to a shortlived technical problem. Books help you avoid bothersome technical hurdles in the first place. Jeff Atwood from <a href="http://www.codinghorror.com/blog" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codinghorror.com');">coding horror</a> expresses this much better <a href="http://www.codinghorror.com/blog/archives/001108.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codinghorror.com');">here</a>. My team and I spent almost a year working extensively with javascript and the ASP.Net AJAX framework before we ever read a book on the subject. Not suprisingly we learned more from reading the book than we had from all the online references and tutorials. Granted, we were much more receptive to the author&#8217;s ideas because we&#8217;d already struggled so much with the technology, but reading this <a href="http://www.manning.com/gallo/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.manning.com');">book</a> made us better developers by helping us connect existing dots and drawing new pictures.There are numerous excellent books out there about everything that software developers do. From <a href="http://www.amazon.com/Beautiful-Code-Leading-Programmers-Practice/dp/0596510047/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1210733699&amp;sr=8-1" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');">books</a> that expand your horizons, <a href="http://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1210733781&amp;sr=8-1" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');">books</a> that help you write better code, <a href="http://www.amazon.com/Mythical-Man-Month-Software-Engineering-Anniversary/dp/0201835959/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1210733871&amp;sr=8-1" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');">books</a> that give you perspective on the bigger picture, <a href="http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1210734092&amp;sr=8-1" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');">books</a> on patterns and practices ,and even fictional <a href="http://www.amazon.com/Microserfs-Douglas-Coupland/dp/0060987049/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1210733965&amp;sr=8-1" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');">books</a> that reinforce what I love about developing software.Many people go out and buy the bible for the next version of some framework or technology. The version they wish they were using, but never end up reading because it doesn&#8217;t apply to their work. People who take an interest in doing what they spend 40+ hours a week better are more likely to do a better job for you.</li>
<li>Subscribe to blogs and follow websites<br />
Blogs keep you abreast of developments in technology. There are really smart people out there with facinating things to say. Following particular blogs shows you have an interest in the world around you and want to see beyond your immediate perspective.Steve Yegge&#8217;s <a href="http://steve-yegge.blogspot.com/atom.xml" onclick="javascript:pageTracker._trackPageview('/outbound/article/steve-yegge.blogspot.com');">blog</a> is brilliant. It&#8217;s also opinionated and ignorant of all things microsoft, but he has a lot of really cogent thoughts. Scott Gu&#8217;s <a href="http://weblogs.asp.net/scottgu/rss.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/weblogs.asp.net');">blog</a> is an invaluable resource to keep up with Microsoft technologies. For year&#8217;s Joel Spolsky has provided <a href="http://www.joelonsoftware.com/rss.xml" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.joelonsoftware.com');">original thoughts</a> on a wide variety of topics that software developers share in common. I&#8217;m glad these guys (and many others) share what they think because there&#8217;s a lot to learn from them.</li>
<li>Work to understand the frameworks that they use<br />
The following are interview questoins I&#8217;ve asked:</p>
<ul>
<li>How does the .net xmlSerializer work?</li>
<li>How does declarative databinding in the aspx markup work? e.g. &lt;%# DataBinder.Eval(Container.DataItem,&#8221;au_id&#8221;) %&gt;</li>
</ul>
<p>The questions themselves aren&#8217;t perfect judges of a developer&#8217;s caliber. They do, however, speak to other concerns- Are they using the framework(s) as designed? Is it all voodoo magic or do they know how it works? Before you can understand the limitations of a technology or framework you have to know how it works. Are dynamic languages better or worse than static languages? There are no right answer here, it depends on what you&#8217;re trying to do. <a href="http://memeagora.blogspot.com/feeds/posts/default" onclick="javascript:pageTracker._trackPageview('/outbound/article/memeagora.blogspot.com');">Neil Ford</a> (from Thoughtworks) said in a talk once that you should generally understand one level deeper than the the code you&#8217;re writing. If you&#8217;re using asp.net, how does the asp.net framework work? If you&#8217;re using a business layer, how does it retrieve and persist data? If you&#8217;re writing web pages, how do HTML, HTTP, and web servers work? Technology choices should be based on evidence and fact; learning how things work is a very basic part of that.</li>
<li>Find technology interesting and exciting in its own right<br />
Most of my time at work is spent with issues that involve code- developing software that is scalable, secure, and efficient while continually work more efficiently. I probably won&#8217;t use the next version of Java (I didn&#8217;t use the last one much either). I probably won&#8217;t make my living coding Ruby on Rails applications. That doesn&#8217;t mean that they don&#8217;t have interesting innovations, patterns, or paradigms. I love my job, I love doing my job well. Technologies that help me do my job better help make me better and that&#8217;s something to be excited about.</li>
</ol>
<p>The underlying quality in these traits is passion. People who love developing software, like learning, and want to improve as developers are people that we want to hire.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/08/10/hallmarks-of-great-developers/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Optimize UpdatePanel performance by avoiding unnecessary element disposal</title>
		<link>http://www.blogfor.net/2008/05/27/optimize-updatepanel-performance-by-avoiding-unnecessary-element-disposal/</link>
		<comments>http://www.blogfor.net/2008/05/27/optimize-updatepanel-performance-by-avoiding-unnecessary-element-disposal/#comments</comments>
		<pubDate>Tue, 27 May 2008 23:45:40 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=23</guid>
		<description><![CDATA[When an update panel is loaded the asp.net client side framework iterates over all the dom elements and disposes any ajax controls bound to them.  This is a method to bypass the default behavior when there are no ajax controls contained in the update panel.]]></description>
			<content:encoded><![CDATA[<p>I fought using <a href="http://ajax.asp.net/docs/overview/UpdatePanelOverview.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/ajax.asp.net');">update panels</a> for a long time. Every time someone demonstrates the MS AJAX framework they skip the amazing features and go right to update panels. They&#8217;d say &#8220;Look how easy they are to use!&#8221;, &#8220;They integrate right into the code you have now.&#8221;, and my personal favorite, &#8220;This is how you can AJAX enabled your website&#8221;. I thought they were a heavy solution filled with problems like <a href="http://msdn2.microsoft.com/en-us/library/system.web.ui.page.smartnavigation.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn2.microsoft.com');">smartnav</a> has in asp.net 1.1.<br />
The MS AJAX framework is much more than just update panels. There&#8217;s more to writing AJAX enabled web sites than wrapping your dynamic content inside update panels.  However, there&#8217;s something I failed to realize- for what they do, update panels are the best tool for the job.  If the goal is to asynchronously update content in a page using the same code used to render the content in the first place, updates panels are it.  Less obvious features include:</p>
<ul>
<li>Only the data being refreshed is transmitted from the web server</li>
<li>UI code uses the same controls to render synchronously or asynchronously</li>
<li>The framework manages the loading of additional javascript and css references</li>
<li>The framework only renders update panels that have been triggered for refresh</li>
<li>There is a simple and effective way to specify which panels get updated on postback</li>
<li>Update panels work almost seamlessly with the other parts of the MS AJAX framework - components, controls, and behaviors</li>
</ul>
<p>I have now accepted the fact that Microsoft has put more thought, time and money into making update panels better than any homegrown solution.</p>
<p>In the primer <a href="http://www.manning.com/gallo/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.manning.com');">Asp.Net AJAX IN ACTION</a>, the authors take great care to explain precisely how update panels work.  They describe how the ajax framework creates and disposes <a href="http://asp.net/AJAX/Documentation/Live/ClientReference/Sys/ComponentClass/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/asp.net');">components</a> when an update panel&#8217;s contents are updated.  For every element in the update panel being disposed, the ajax framework checks to see if there are any <a href="http://asp.net/AJAX/Documentation/Live/ClientReference/Sys.UI/ControlClass/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/asp.net');">controls</a> or <a href="http://asp.net/AJAX/Documentation/Live/ClientReference/Sys.UI/BehaviorClass/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/asp.net');">behaviors</a> bound to the element that needs to be disposed.</p>
<p><em>Note: any components not bound to elements are not disposed when update panels are refreshed. When the page_unload() event calls the dispose method of the components an error may occur because the DOM state has changed and the components don&#8217;t reflect it.</em></p>
<p>Why bother with object disposal? Why not just replace the innerHTML of the update panel&#8217;s div?  <a href="http://www.julienlecomte.net/blog" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.julienlecomte.net');">Julien Lecompte</a> (from Yahoo!) explains a few issues <a href="http://www.julienlecomte.net/blog/2007/12/38/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.julienlecomte.net');">here</a>. Basically, expando attributes on elements cause memory leaks when not disposed properly. <a href="http://www.crockford.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.crockford.com');">Douglas Crockford</a> (also from Yahoo!) describes the basic <a href="http://www.crockford.com/javascript/memory/leak.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.crockford.com');">workaround</a>.  Fortunately for us, however, the Microsoft framework does this already in part through the component <a href="http://asp.net/AJAX/Documentation/Live/ClientReference/Sys.UI/BehaviorClass/BehaviorDisposeMethod.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/asp.net');">dispose</a> method.</p>
<p>When the update panel is about to be loaded, the framework doesn&#8217;t know which objects need to be disposed. It has to iterate over all the elements about to be destroyed and check for objects to dispose.  The following code is from MicrosoftAjaxWebForms.debug.js (comments in code are mine):</p>
<pre name="code" class="javascript">function Sys$WebForms$PageRequestManager$_updatePanel(updatePanelElement, rendering) {
	//some code not germane to this post has been omitted here
	//this is where the existing content is disposed
	this._destroyTree(updatePanelElement);
	//and the content is updated
	updatePanelElement.innerHTML = rendering;
}
function Sys$WebForms$PageRequestManager$_destroyTree(element) {
	if (element.nodeType === 1) {
		var childNodes = element.childNodes;
		for (var i = childNodes.length - 1; i &gt;= 0; i--) {
			var node = childNodes[i];
			if (node.nodeType === 1) {
				//if the node has a dispose method, call it
				if (node.dispose &amp;&amp; typeof(node.dispose) === &#8220;function&#8221;) {
					node.dispose();
				}
				//if the node has a sys.ui.control associated with it, call its dispose method
				else if (node.control &amp;&amp; typeof(node.control.dispose) === &#8220;function&#8221;) {
					node.control.dispose();
				}
				//check for sys.ui.behaviors associated with the node and call dispose on each one
				var behaviors = Sys.UI.Behavior.getBehaviors(node);
				for (var j = behaviors.length - 1; j &gt;= 0; j&#8211;) {
					behaviors[j].dispose();
				}
				//recurse the contents of this node to do it again
				this._destroyTree(node);
			}
		}
	}
}</pre>
<p>If you know there are no objects bound to the content of the update panel, Asp.Net AJAX In Action suggests that you can avoid the performance penalty imposed by the framework&#8217;s memory leak prevention. They suggest removing the update panel div from the DOM after the asynchronous result is returned and before the framework applies the result to the DOM. We can use the <a href="http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.WebForms/PageRequestManagerClass/PageRequestManagerPageLoadingEvent.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.asp.net');">pageLoading</a> event to do this.</p>
<pre name="code" class="vb.net">'''
''' Exposes methods to increase update panel performance when the panel contains content without sys.ui.controls associated with it
'''
'''
Public NotInheritable Class UpdatePanelRemoveNodeOnPostback         

	'''
	''' returns string for script to remove the specified control on the client DOM before the page is loaded after an asyncronous postback
	''' this saves the atlas framework from having to traverse the existing dom elements and remove all behaviors, thereby increasing performance
	''' NOTE: THIS CAN ONLY BE USED WHEN THE CONTROL HAS NO CLIENT SIDE CONTROLS ASSOCIATED WITH IT, specifically, as is the case with some of our
	''' gridviews
	'''
	'''

	'''
	'''
	Public Shared Function CreateScriptToRemoveExistingNodeFromUpdatePanelBeforePageLoad(ByVal control As Control) As String
		Return String.Format(System.Globalization.CultureInfo.InvariantCulture, Resources.UpdatePanelRemoveNodeOnPageLoading.Script, control.ClientID, control.ClientID, control.ClientID)
	End Function
End Class</pre>
<p>The function references a script included as a resource:</p>
<pre name="code" class="javascript">&lt;script type="text/javascript"&gt;
	var pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
	pageRequestManager.add_pageLoading(onPageLoading{0});        

	function onPageLoading{1}(sender, e) {
		var itemToRemove = $('{2}');
		if (itemToRemove != null) {
			itemToRemove.remove();
		}
	}
&lt;/script&gt;</pre>
<p>One common place I use this is when an update panel contains a gridview. This is an ideal candidate because the amount of html being disposed can be quite large. In the gridview&#8217;s container&#8217;s preRender event:</p>
<pre name="code" class="vb.net">Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
	MyBase.OnPreRender(e)
	If GridView.Visible Then
		Dim script As String = UpdatePanelRemoveNodeOnPostback.CreateScriptToRemoveExistingNodeFromUpdatePanelBeforePageLoad(GridView)
		Me.Page.ClientScript.RegisterStartupScript(Me.GetType, "RemoveGridViewPrePostBackLoad", script)
	End If
End Sub</pre>
<p>When the update panel is loaded, the javascript code will fire removing the gridview element from the DOM before the disposal code is fired.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/05/27/optimize-updatepanel-performance-by-avoiding-unnecessary-element-disposal/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Time based Caching in a Load Balanced ASP.Net Application</title>
		<link>http://www.blogfor.net/2008/05/27/time-based-caching-in-a-load-balanced-aspnet-application/</link>
		<comments>http://www.blogfor.net/2008/05/27/time-based-caching-in-a-load-balanced-aspnet-application/#comments</comments>
		<pubDate>Tue, 27 May 2008 23:33:17 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=24</guid>
		<description><![CDATA[One method to work around caching issue when an asp.net application scales from a single server to a web farm.]]></description>
			<content:encoded><![CDATA[<p>When using the <a href="http://msdn.microsoft.com/en-us/library/ms178597.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">asp.net application cache</a> a common problem occurs when the application scales from a single web server to a web farm. This problem and more are more broadly discussed <a href="http://msdn.microsoft.com/en-us/magazine/cc500561.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">here</a>.</p>
<p>One common approach to keep cache items in sync across web servers is use of <a href="http://msdn.microsoft.com/en-us/library/67z4z916.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">file dependencies</a> on a central file server. When a depenency file is modified, all web servers in the farm remove the dependent items from their cache.</p>
<p>This works well until one tries to cache an item for a specified duration <em>without</em> a specific file dependency.  Consider a web site that shows &#8220;recent blog posts&#8221;. The list may be constantly changing and although some latency of the data is allowed(hence the caching), <em>the data must always be consistent no matter which web server serves the response</em>.</p>
<p>We can use the same file dependency strategy to keep the cache items in sync between web servers. The &#8220;trick&#8221; is to produce a hash of the data to be cached and include that information when synchronizing the servers.</p>
<p>If a web server receives a request and does not have the data in its application cache, it must retrieve it.  The server then compares a hash of the data against the contents of a dependency file (unique to that cache item) accessible to all web servers. If the contents of the file are different than the hash generated, the latest results retrieved for the cache item do not match the cache items on other web servers. By replacing the contents of the cache item dependency file with the value of the new hash we can guarantee that the cache items on other web servers will be invalidated and removed.</p>
<p>A sample project demonstrating this is <a href="File URL">here</a>.</p>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/05/27/time-based-caching-in-a-load-balanced-aspnet-application/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Class Table Inheritance: An Investigation into SQL Performance</title>
		<link>http://www.blogfor.net/2008/05/27/class-table-inheritance-an-investigation-into-sql-performance/</link>
		<comments>http://www.blogfor.net/2008/05/27/class-table-inheritance-an-investigation-into-sql-performance/#comments</comments>
		<pubDate>Tue, 27 May 2008 23:29:01 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=30</guid>
		<description><![CDATA[Class Table Inheritance is a powerful tool when persisting a strong object oriented business model, but what happens when the data size grows?  If we know the type of object we&#8217;re selecting, the query is straightforward and performs well:
select
	 base_class.id
	,base_class.sub_type
	,inheriting_class.column1
..
	,inheriting_class.columnn
from
	base_class inner join inheriting_class on base_class.id = inheriting_class.base_class_id
Using multiple tables, requires an inner join to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.martinfowler.com/eaaCatalog/classTableInheritance.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.martinfowler.com');" target="_blank">Class Table Inheritance</a> is a powerful tool when persisting a strong object oriented business model, but what happens when the data size grows?  If we know the type of object we&#8217;re selecting, the query is straightforward and performs well:</p>
<pre name="code" class="sql">select
	 base_class.id
	,base_class.sub_type
	,inheriting_class.column1
..
	,inheriting_class.columnn
from
	base_class inner join inheriting_class on base_class.id = inheriting_class.base_class_id</pre>
<p>Using multiple tables, requires an inner join to select data and multiple updates to persist it. Outside high volume transaction applications, however, this cost this is negligible.<br />
The problem begins when we need to select a potentially heterogeneous set of records. The longer the inheritance chain and the larger number of sub-classes the less performant our queries will be.<br />
Suppose we have a relatively simple object model as follows:<br />
<a href="http://www.blogfor.net/wp-content/uploads/2008/05/TableClassInheritance.gif" ><img class="alignnone size-medium wp-image-33" title="image002" src="http://www.blogfor.net/wp-content/uploads/2008/05/image002-300x169.gif" alt="" /></a><br />
click the links for scripts to <a href="http://www.blogfor.net/wp-content/uploads/2008/05/createtables.sql"  target="_blank">create</a> and <a href="http://www.blogfor.net/wp-content/uploads/2008/05/populatetables.sql"  target="_blank">populate</a>.</p>
<p>In order to select a set of records &#8220;inheriting&#8221; from base_class, the business layer or OR/M will generate a query similar to the following (note I&#8217;m not selecting all the records, just a subset akin to the filters one would use in a real application):</p>
<pre name="code" class="sql">select
	 base_class.id
	,A.base_class_id
	,B.base_class_id
	,C.base_class_id
	,case when A.base_class_id is not null then 1 when B.base_class_id is not null then 2 when C.base_class_id is not null then 3 end as clazz_
from
	base_class left join inheriting_class_a as A on base_class.id = A.base_class_id
	left join inheriting_class_b as B on base_class.id = B.base_class_id
	left join inheriting_class_c as C on base_class.id = C.base_class_id
where base_class.id % 7 = 1</pre>
<p>On average the query takes 700ms on my machine (dual quad-core x64 xp). If we add in our knowledge of the sub-type into the join, the performance does not improve.</p>
<pre name="code" class="sql">select
	 base_class.id
	,A.base_class_id
	,B.base_class_id
	,C.base_class_id
	,case when A.base_class_id is not null then 1 when B.base_class_id is not null then 2 when C.base_class_id is not null then 3 end as clazz_
from
	base_class as base_class left join inheriting_class_a as A on base_class.id = A.base_class_id and base_class.sub_type = 2
	left join inheriting_class_b as B on base_class.id = B.base_class_id and base_class.sub_type = 0
	left join inheriting_class_c as C on base_class.id = C.base_class_id and base_class.sub_type = 1
where base_class.id % 7 = 1</pre>
<p>In fact the query execution plan is still the same despite a unique composite index on id and sub_type. The left joins are simply expensive. We need them to return heterogeneous results but the cost has become prohibitive. The longer the inheritance chain and the larger the number of sub-types, the more drastically the performance will degrade beyond this simple example.<br />
One workaround is to perform the expensive outer joins on a smaller subset of date. If we execute the same query using a <a href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">Common Table Expression</a> and filter the rows before doing the outer joins, the cost decreases by 50% to an average of 371ms.</p>
<pre name="code" class="sql">select
	 base_class.id
	,base_class.sub_type
	,C.base_class_id
	,B.base_class_id
	,C.base_class_id
	,case when A.base_class_id is not null then 1 when B.base_class_id is not null then 2 when C.base_class_id is not null then 3 end as clazz_
from
	base_class as base_class left join inheriting_class_a as C on base_class.id = C.base_class_id
	left join inheriting_class_b as B on base_class.id = B.base_class_id
	left join inheriting_class_c as C on base_class.id = C.base_class_id
where base_class.id % 7 = 1</pre>
<p>By comparison, using Single Table inheritance (click links for <a href="http://www.blogfor.net/wp-content/uploads/2008/05/createsingletableinheritance.sql" >create</a> and <a href="http://www.blogfor.net/wp-content/uploads/2008/05/populatesingletableinheritance.sql" >populate</a> scripts), the performace on the following:</p>
<pre name="code" class="sql">	select id, 1 as clazz_
	from sub_class_a
	where id %7 = 1
union all
	select id, 2 as clazz_
	from sub_class_b
	where id %7 = 1
union all
	select id, 3 as clazz_
	from sub_class_c
	where id %7 = 1</pre>
<p>is far better than that of the Class Table Inheritance at an average of 140ms. It&#8217;s important to note that performance will vary dramatically depending on the size of your data, the &#8220;selectiveness&#8221; of your where clause and other specifc circumstances.<br />
From the perspective of query performance, Single Table Inheritance is far more efficient than Class Table Inheritance. Within the context of Class Table Inheritance, what is not so obvious is that the cost of returning heterogenous lists or simply not knowing the sub-type at query time can be quite high.  Filtering the records (if possible) before applying the outer joins can drastically improve performance.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/05/27/class-table-inheritance-an-investigation-into-sql-performance/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Howto: avoid binding the same eventhandler multiple times to an element event in the MS AJAX framework</title>
		<link>http://www.blogfor.net/2008/05/27/howto-avoid-binding-the-same-eventhandler-multiple-times-to-an-element-event-in-the-ms-ajax-framework/</link>
		<comments>http://www.blogfor.net/2008/05/27/howto-avoid-binding-the-same-eventhandler-multiple-times-to-an-element-event-in-the-ms-ajax-framework/#comments</comments>
		<pubDate>Tue, 27 May 2008 23:20:03 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/?p=22</guid>
		<description><![CDATA[A workaround to duplicate event handler binding in Microsoft AJAX and a brief explanation how to avoid such problems in the first place.]]></description>
			<content:encoded><![CDATA[<p>The Microsoft AJAX <a href="http://asp.net/AJAX/Documentation/Live/ClientReference/Global/AddHandlerShortcutMethod.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/asp.net');">$addHandler</a> method is a wrapper to the browser specific implementations of the <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.w3.org');">w3c standard</a> e.g. $addHandler(element, eventName, handler).</p>
<p>Once you&#8217;ve bound an event handler to an element, there is no standard way to retrieve the binding information.  Javascript frameworks work around this limitation by setting custom properties on the html elements to track handler bindings.  As long as handlers are added and removed through the framework things will work as expected with one minor exception. If $addHandler is called twice with the same handler, when the event fires, <em>the handler fires twice</em>.</p>
<p>The Microsoft AJAX framework doesn&#8217;t check whether or not a delegate is already bound before binding it a second time, nor does it provide a means to determine what handlers are already bound. The best way to avoid this condition is by following the MS AJAX pattern for binding behaviors and elements. The pattern dictates that elements are &#8220;wrapped&#8221; in a one-to-one relationship with <a href="http://asp.net/AJAX/Documentation/Live/ClientReference/Sys.UI/ControlClass/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/asp.net');">controls</a>.  When a control is initialized it binds element events to its own internal delegates.  When other <a href="http://asp.net/AJAX/Documentation/Live/ClientReference/Sys.UI/BehaviorClass/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/asp.net');">behaviors</a> need to listen for events, they use the <a href="http://asp.net/AJAX/Documentation/Live/ClientReference/Sys/EventHandlerListClass/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/asp.net');">event handling architecture</a> for controls and behaviors by binding against the control, not the element.  Mike Ormond&#8217;s <a href="http://blogs.msdn.com/mikeormond/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">blog</a> provides a good <a href="http://blogs.msdn.com/mikeormond/archive/2008/03/25/building-asp-net-ajax-controls-pt-1.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">explanation</a>.</p>
<p>Occasionally, you have the problem of adding the same handler multiple times. To work around this we need to know a little more about how the Microsoft framework tracks element event bindings.</p>
<p>When $addHandler is called, Microsoft AJAX adds an expando attribute to the element called &#8220;_events&#8221;. This is a hash table of the event bindings for the element. Element._events["eventName"] returns an array of delegates bound to the specified element event. The code below simply uses this internal implementation of the MS AJAX framework to avoid duplicate bindings. To use it, simply replace calls to $addHandler and $removeHandler with calls to $addHandlerIfNotDefined and $removeHandlerIfNotDefined.</p>
<pre name="code" class="javascript">$handlerDefined = function(elt, eventName, handler) {
	// returns true if an eventHandler has been defined for the given element and the given event
	if ( ( typeof( elt._events ) !== 'object' ) ||
		 ( elt._events === null ) ) {
		return false;
	}
	var cache = elt._events[eventName];
	if ( !(cache instanceof Array ) ) {
		return false;
	} else {
		for (var i=0, l = cache.length; i &lt; l; i+=1) {
				if (cache[i].handler === handler) {
					return true;
				}
		}
	}
}    

$addHandlerIfNotDefined = function(elt, eventName, handler) {
	// ensures the given handler is bound to the given element for the given event
	if ( !$handlerDefined( elt, eventName, handler ) ) {
		$addHandler(elt, eventName, handler);
	}
}    

$removeHandlerIfNotDefined = function(elt, eventName, handler) {
	// ensures the given handler is bound to the given element for the given event
	if ( $handlerDefined( elt, eventName, handler ) ) {
		$removeHandler(elt, eventName, handler);
	}
}</pre>
<p>Note: this solution does not handle new instances of anonymous delegates e.g.<br />
$addHandlerIfNotDefined(elt, &#8220;onclick&#8221;, new Function(evt){some code here});<br />
Since a new anonymous delegate is created each time the handler is added, we would need to compare both the &#8220;state&#8221; and &#8220;code of the delegate for instance equivalence. Determining delegate object equivalence is a difficult thing, the code above compares only delegate instance equivalence.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/05/27/howto-avoid-binding-the-same-eventhandler-multiple-times-to-an-element-event-in-the-ms-ajax-framework/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Applying for technical jobs? A rough guide</title>
		<link>http://www.blogfor.net/2008/04/21/applying-for-technical-jobs-a-rough-guide/</link>
		<comments>http://www.blogfor.net/2008/04/21/applying-for-technical-jobs-a-rough-guide/#comments</comments>
		<pubDate>Tue, 22 Apr 2008 01:58:09 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[general]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/2008/04/21/applying-for-technical-jobs-a-rough-guide/</guid>
		<description><![CDATA[Rough guideline to applying and interviewing for software development jobs. What to expect from process and common pitfalls.]]></description>
			<content:encoded><![CDATA[<p>For the last three years I&#8217;ve been involved in our company&#8217;s development team hiring process.  We&#8217;ve defined it, refined it, reworked it, and reworked it again.  We&#8217;ve made mistakes and made great hires.  I thought I&#8217;d share a few thoughts on the subject which you may find useful. </p>
<p>For every job posting online, we get 100+ applications.  For every diamond in the rough, there are many more applications we wish we didn&#8217;t spend time on.  We only want to hire great developers and have a rule: &#8220;no false positives&#8221;.  Although we may miss a &#8220;diamond in the rough&#8221; application, we try to make the time we spend hiring as effective as possible.  Usually we &#8220;ding&#8221; anyone who:</p>
<ol>
<li>Doesn&#8217;t have a cover letter.</li>
<li>Has numerous spelling errors on their resume or cover letter.</li>
<li>Submitted an application that takes us more than 30 seconds to determine what position you&#8217;re applying for and where you&#8217;re coming from (e.g. current job is &#8220;help desk&#8221;, but applying for a programmer position; went to school for art history).  For a better explanation check Rand In Repose&#8217;s <a href="http://www.randsinrepose.com/archives/2007/02/25/a_glimpse_and_a_hook.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.randsinrepose.com');">posting</a>.</li>
</ol>
<p>So how do you avoid these &#8220;dings&#8221;?</p>
<ol>
<li>Have someone proof read your resume</li>
<li>Check out other peoples resumes, e.g.  <a href="http://www.amazon.com/Resumes-That-KnockEm-Dead-Knock/dp/1580624227" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');" title="resumes that knock 'em dead">Resumes That Knock &#8216;Em Dead</a> and see formats that appear appropriate for the field you work in.</li>
<li>Use a cover letter customized to the position.  <a href="http://www.amazon.com/Cover-Letters-That-Knock-Dead/dp/1593377479/ref=pd_sim_b_img_2" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');">Cover Letters That Knock &#8216;Em Dead</a> has a number of samples to get an idea of the tone and content of what your cover letter should contain.  Make sure to have someone proof read your cover letter before you apply.</li>
<li>Put things on your resume that HR people, recruiters, and automated systems can find.  I don&#8217;t mean highlight or boldface all your references to technologies (who started that trend anyways?), use certifications, associations, conferences, and trainings.  HR people aren&#8217;t developers.  They don&#8217;t know the difference between C# and VB.net or smalltalk and Ruby.  They know keywords they&#8217;ve been asked to look for, so make their job easier. By getting certifications, you may not be advancing your education so much as easing the first barrier to entry at any organization - survive the resume screening process.  Certs, conferences, and user groups indicate you&#8217;re serious about what you do for a career and advancing yourself professionally. HR people like this.</li>
</ol>
<p>You&#8217;ve submitted your cover letter and resume, and you get a call back.  The usual process is something like this:</p>
<ol>
<li>HR person/recruiter calls to qualify the application.  They want to sell you on the job - the company, the job itself, the benefits and also determine if this is a good fit for both parties.  They&#8217;ll ask the standard personnel questions and more specific questions they&#8217;re told to ask. for example
<ol>
<li>Why are you looking for a job?</li>
<li>When can you start?</li>
<li>What salary are you looking for?</li>
<li>What kind of job are you looking for?</li>
<li>What are your professional goals? -this one is very important. I can&#8217;t tell you how many people have applied for developer positions and told me &#8220;I want to get into business analysis/project management/developer management&#8221; - the job posting was specifically for a software engineer. Why did you apply?</li>
<li>Suppose you and someone have similar resumes. What makes you different?</li>
<li>What books have you read recently?</li>
<li>What blogs do you subscribe to?</li>
</ol>
<p>Be prepared for all of these.  The last three are really where we begin to distinguish ambition/character from professional qualifications. They&#8217;re good indicators (like education and certification) about what it is you want to do, how motivated you are, and a rough guide to your technical skills.</li>
<li>The technical phone screen.  This person is usually the hiring manager.  His goal is to further qualify you as a potential hire and to help sell you on the job with more details. Expect more technical questions and questions on your experience with certain technologies. </li>
<li>In person interview.</li>
</ol>
<p>Hopefully you made it through the screening process and are asked for a personal interview.   Get there early - &#8220;if you&#8217;re on time, you&#8217;re late&#8221;.  Once there, relax, use the bathroom, and review your information again- who the company is, what they do, the job description, and what information you&#8217;ve given them (resume, cover letter, references etc.).</p>
<p>Steve Yegge has a good description of the general onsite interview process and a whole lot more at &#8220;<a href="http://steve-yegge.blogspot.com/2008/03/get-that-job-at-google.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/steve-yegge.blogspot.com');">get that job at google</a>.&#8221; From his posting:</p>
<blockquote><p>Every &#8220;experienced&#8221; interviewer has a set of pet subjects and possibly specific questions that he or she feels is an accurate gauge of a candidate&#8217;s abilities. The question sets for any two interviewers can be widely different and even entirely non-overlapping.</p>
<p> A classic example found everywhere is: Interviewer A always asks about C++ trivia, filesystems, network protocols and discrete math. Interviewer B always asks about Java trivia, design patterns, unit testing, web frameworks, and software project management. For any given candidate with both A and B on the interview loop, A and B are likely to give very different votes. A and B would probably not even hire each other, given a chance, but they both happened to go through interviewer C, who asked them both about data structures, unix utilities, and processes versus threads, and A and B both happened to squeak by.</p>
<p> That&#8217;s almost always what happens when you get an offer from a tech company. You just happened to squeak by. Because of the inherently flawed nature of the interviewing process, it&#8217;s highly likely that someone on the loop will be unimpressed with you, even if you are Alan Turing. Especially if you&#8217;re Alan Turing, in fact, since it means you obviously don&#8217;t know C++.</p>
<p> The bottom line is, if you go to an interview at any software company, you should plan for the contingency that you might get genuinely unlucky, and wind up with one or more people from your Interview Anti-Loop on your interview loop. If this happens, you will struggle, then be told that you were not a fit at this time, and then you will feel bad. Just as long as you don&#8217;t feel meta-bad, everything is OK. You should feel good that you feel bad after this happens, because hey, it means you&#8217;re human.</p></blockquote>
<p>It helps to understand the perspective of the employer on the interview process. Joel Spolsky is an excellent resource on hiring developers.  His book entitled &#8220;<a href="http://www.amazon.com/Smart-Gets-Things-Done-Technical/dp/1590598385/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1208662110&amp;sr=8-1" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');">Smart And Gets Things done</a>&#8220; and blog posting <a href="http://www.joelonsoftware.com/articles/GuerrillaInterviewing3.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.joelonsoftware.com');">The Guerrilla Guide to Interviewing</a> are essential resources for companies trying to find great talent. From his posting:</p>
<blockquote><p>You should always try to have at least six people interview each candidate that gets hired, including at least five who would be peers of that candidate (that is, other programmers, not managers). You know the kind of company that just has some salty old manager interview each candidate, and that decision is the only one that matters? These companies don’t have very good people working there. It’s too easy to fake out one interview, especially when a non-programmer interviews a programmer.<br />
 <br />
 If even two of the six interviewers thinks that a person is not worth hiring, don’t hire them. That means you can technically end the “day” of interviews after the first two if the candidate is not going to be hired, which is not a bad idea, but to avoid cruelty you may not want to tell the candidate in advance how many people will be interviewing them. I have heard of companies that allow any interviewer to reject a candidate. This strikes me as a little bit too aggressive; I would probably allow any senior person to reject a candidate but would not reject someone just because one junior person didn’t like them.</p>
<p>Look for passion. Smart people are passionate about the projects they work on. They get very excited talking about the subject. They talk quickly, and get animated. Being passionately negative can be just as good a sign. “My last boss wanted to do everything on VAX computers because it was all he understood. What a dope!” There are far too many people around that can work on something and not really care one way or the other. It’s hard to get people like this motivated about anything.</p>
<p>Bad candidates just don’t care and will not get enthusiastic at all during the interview. A really good sign that a candidate is passionate about something is that when they are talking about it, they will forget for a moment that they are in an interview.</p></blockquote>
<p>When interviewing we want to give the best impression possible. This is both easier and harder than it may seem.  According to Dave Munger in this <a href="http://scienceblogs.com/cognitivedaily/2006/05/the_sixsecond_teacher_evaluati.php" onclick="javascript:pageTracker._trackPageview('/outbound/article/scienceblogs.com');">post</a> and Malcolm Gladwell in his book <a href="http://www.amazon.com/Blink-Power-Thinking-Without/dp/0316010669/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1207198110&amp;sr=8-1" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.amazon.com');">Blink</a>(well worth reading), you&#8217;ll have about six seconds to make that first impression.  Presenting yourself with confidence and a humble smile will go a very long way to set the right tone for your interview.</p>
<p>Each individual interview will have several distinct sections.</p>
<ol>
<li>You&#8217;ll meet and shake hands.<br />
A recruiter once told me that at this moment, I should lean forward a little and stand on my toes.  He said it would make me stand up straighter and more importantly it would make me feel a little silly. This would in turn make me smile and relax. When I relaxed, the interviewer would relax.  After interviewing with 4 companies and 20 different people I will tell you, he was exactly right.  As the interviewer of 50+ people for two different companies, I can tell you the opposite is true- the candidates who don&#8217;t present themselves well usually have a harder interview as I try to draw them out.</li>
<li>The interviewer will tell you who they are and what they do. </li>
<li>They&#8217;ll ask you some questions. <br />
Be polite, be eager, and be positive during all of this. </li>
<li>Finally they&#8217;ll ask you if you have any questions.<br />
You should always have questions. Questions show you care about the position. It helps draw the interviewer into the conversation.  It&#8217;s also one of the only places during the interview process where you&#8217;ll get an idea what the job would actually be like.  Questions like: </p>
<ul>
<li>Who would I be working with? (Are they of your caliber? Are they as motivated as you are?)</li>
<li>What would be the first project/team I&#8217;d work on here?</li>
<li>What would I need to do to meet or exceed expectations after 6 months? (OK this one is a little cheesy, but sometimes effective)</li>
<li>Who would be my manager?</li>
<li>What feedback loop do you have for my performance?</li>
<li>What is the primary focus of the position (you may get a different answer depending on who you ask) - technical? interfacing with users? project management?</li>
</ul>
</li>
</ol>
<p>So you&#8217;re interview is done, and you&#8217;re on your way out.  Don&#8217;t forget to thank everyone you met, including their &#8220;staff&#8221;.  Take a moment when you finally get out of there and write down some notes of your impressions (you&#8217;ll forget things by the time you get home) what people said, the specifics of the actual job, etc. </p>
<p>A few final notes:</p>
<ul>
<li>2 weeks notice to your current employer is standard - if they expect you to leave without notice, it says something about how much they care about people.</li>
<li>Always get time to think about the offer- &#8220;I have to speak with my family&#8221; is a valid answer.  Anyone who goes for the hard sell is sketchy.</li>
<li>If things don&#8217;t pan out, it&#8217;s probably because someone (and it only takes one) thought you weren&#8217;t the best fit.  That may be true, it may not, but better no fit than a bad one. </li>
<li>Big companies can afford a longer ramp up time and better training.  Smaller ones are generally looking for you to hit the ground running.  Don&#8217;t be upset if someone thought you&#8217;d require a little too much training to be useful to them- it&#8217;s them, not you :)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/04/21/applying-for-technical-jobs-a-rough-guide/feed/</wfw:commentRss>
		</item>
		<item>
		<title>YSlow and ASP.NET - Expires Header - BuildProvider (Part 3 of 3)</title>
		<link>http://www.blogfor.net/2008/04/21/yslow-and-aspnet-expires-header-buildprovider-part-3-of-3/</link>
		<comments>http://www.blogfor.net/2008/04/21/yslow-and-aspnet-expires-header-buildprovider-part-3-of-3/#comments</comments>
		<pubDate>Tue, 22 Apr 2008 01:02:20 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/2008/04/21/yslow-and-aspnet-expires-header-buildprovider-part-3-of-3/</guid>
		<description><![CDATA[How to use a buildProvider to provide codebehind based support for dynamic location of static content.  Part three of three in series to utilize static content versioning to reduce http request through extended content caching.]]></description>
			<content:encoded><![CDATA[<p>For the last part of our quest to enable caching of static content by separating it out into directories by version, we want to provide an easy and intuitive way for developers to reference static content from the code behind. e.g.</p>
<pre name="code" class="vb.net">
Dim linkIcon As New System.Web.UI.WebControls.Image
linkIcon.ImageUrl = StaticContent.Images.rss_gif</pre>
<p>Under the covers StaticContent.Images.rss_gif resolves to a method call -StaticContent.PathBuilder.ConvertImageUrl(&#8221;rss.gif&#8221;) (the method is covered in part 2).<br />
To do this we need a <a href="http://msdn2.microsoft.com/en-us/library/system.web.compilation.buildprovider.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn2.microsoft.com');">buildProvider</a> (Note: this is not supported in Web Application Projects (WAP) see notes at the end).<br />
The code is mostly written for us on <a href="http://www.singular.co.nz/blog/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.singular.co.nz');">Dave Transom&#8217;s </a>excellent <a href="http://www.singular.co.nz/blog/archive/2008/02/03/build-providers-and-strongly-typed-page-urls-in-asp-net.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.singular.co.nz');">post</a>.<br />
The slightly modified code is <a href="http://www.blogfor.net/wp-content/uploads/2008/04/buildprovider.vb"  title="BuildProvider.vb">here</a>.<br />
Now that we have a buildProvider we wire it into the build using the web.config:</p>
<pre name="code" class="xml">
&lt;compilation debug="true" strict="true" explicit="true"&gt;
	&lt;buildProviders&gt;
		&lt;add extension=".hrefs" type="Savo.Framework.Web.StaticContent.BuildProvider"/&gt;
	&lt;/buildProviders&gt;
&lt;/compilation&gt;</pre>
<p>To configure our BuildProvider create a file with the extension &#8220;.hrefs&#8221; in your App_Code directory, using some variation on the following:</p>
<pre name="code" class="xml">
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;settings
	namespace=""
	className="StaticContent"
	minDepth="1"
	maxDepth="100"
	lowercaseUrls="true"
	includeExtension="true"
	truncatePathToStartingDepth="true"
	resourceResolutionFormat='StaticContent.PathBuilder.ConvertStaticContentUrl("{0}")'
	directoryNamesToIgnore="StaticContent"&gt;
	&lt;files include="\.(gif|jpg|png|css)$" exclude=""&gt;
	&lt;folders include="StaticContent" exclude="App_|Bin|\.svn"&gt;
&lt;/settings&gt;</pre>
<p>If you&#8217;re using a &#8220;Web Application Project&#8221;, this method won&#8217;t work as per this <a href="http://msdn2.microsoft.com/en-us/library/aa983464.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn2.microsoft.com');">MS post</a>.  My suggestion is to use a <a href="http://msdn2.microsoft.com/en-us/library/e2s2128d(VS.80).aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn2.microsoft.com');">pre-build event</a> (although this has a few extra gotchas) or another framework like <a href="http://bchavez.bitarmory.com/archive/2007/09/03/slink-framework---strongly-typed-urls-for-asp.net.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/bchavez.bitarmory.com');">slink</a> though I haven&#8217;t tried either method.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blogfor.net/2008/04/21/yslow-and-aspnet-expires-header-buildprovider-part-3-of-3/feed/</wfw:commentRss>
		</item>
		<item>
		<title>YSlow and ASP.NET - Expires Header - Expression Builders (Part 2 of 3)</title>
		<link>http://www.blogfor.net/2008/04/21/yslow-and-aspnet-expires-header-expression-builders-part-2-of-3/</link>
		<comments>http://www.blogfor.net/2008/04/21/yslow-and-aspnet-expires-header-expression-builders-part-2-of-3/#comments</comments>
		<pubDate>Tue, 22 Apr 2008 00:43:00 +0000</pubDate>
		<dc:creator>phil</dc:creator>
		
		<category><![CDATA[asp.net]]></category>

		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.blogfor.net/2008/04/21/yslow-and-aspnet-expires-header-expression-builders-part-2-of-3/</guid>
		<description><![CDATA[How to use expressionBuilders to provide markup based support for dynamic location of static content.  Part two of three in series to utilize static content versioning to reduce http request through extended content caching.]]></description>
			<content:encoded><![CDATA[<p>Continuing our task of caching indefinitely static content by versioning it, we want to build the framework so that instead of code like this:</p>
<pre name="code" class="xml">
&lt;asp:image imageurl="~/images/rose.jpg" runat="server" id="image1"&gt;</pre>
<p>we have this:</p>
<pre name="code" class="xml">
&lt;asp:Image id="image1" imageurl="&lt;%$ Image: rose.jpg %&gt;" runat="server"/&gt;</pre>
<p>The key difference is that we can dynamically assign where the image path for rose.jpg resolves in the latter case. Specifically, we can resolve to applicationPath/versionX.X.X/Images/rose.jpg (or whatever url scheme meets your fancy).</p>
<p>We need two things. First we create an expressionBuilder object and then tie the custom expressionBuilder into the build. I&#8217;m using the VS &#8220;WebSite&#8221; project, but this should work for &#8220;Web Application Projects&#8221;.</p>
<p>The following code draws heavily from this <a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/weblogs.asp.net');">post</a> on Dave Reed&#8217;s excellent blog <a href="http://weblogs.asp.net/infinitiesloop/default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/weblogs.asp.net');">infinitiesloop</a>.</p>
<pre name="code" class="vb.net">
Imports System.CodeDom
Imports System.Web         

Namespace StaticContent         

	Public NotInheritable Class PathBuilder         

		Private Shared CssPath As String = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/StaticContent/{1}/Css/{{0}}", System.Web.HttpContext.Current.Request.ApplicationPath, System.Configuration.ConfigurationManager.AppSettings("versionNumber")))
		Private Shared ImagePath As String = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/StaticContent/{1}/Images/{{0}}", System.Web.HttpContext.Current.Request.ApplicationPath, System.Configuration.ConfigurationManager.AppSettings("versionNumber")))
		Private Shared JavascriptPath As String = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/StaticContent/{1}/Javascripts/{{0}}", System.Web.HttpContext.Current.Request.ApplicationPath, System.Configuration.ConfigurationManager.AppSettings("versionNumber")))         

		Public Shared Function ConvertCssUrl(ByVal path As String) As String
			Return String.Format(System.Globalization.CultureInfo.InvariantCulture, CssPath, path)
		End Function         

		Public Shared Function ConvertImageUrl(ByVal path As String) As String
			Return String.Format(System.Globalization.CultureInfo.InvariantCulture, ImagePath, path)
		End Function         

		Public Shared Function ConvertJavascriptUrl(ByVal path As String) As String
			Return String.Format(System.Globalization.CultureInfo.InvariantCulture, JavascriptPath, path)
		End Function         

		Private Sub New()
		End Sub         

	End Class         

	MustInherit Class StaticContentExpressionBuilder
		Inherits Compilation.ExpressionBuilder         

		Protected Shared evaluationExpression As String         

		Protected MustOverride ReadOnly Property StaticContentExpression() As String         

		Public Overrides Function ParseExpression(ByVal expression As String, ByVal propertyType As System.Type, ByVal context As Compilation.ExpressionBuilderContext) As Object
			Return String.Format(System.Globalization.CultureInfo.InvariantCulture, StaticContentExpression, expression)
		End Function         

		Public Overloads Overrides Function GetCodeExpression(ByVal entry As System.Web.UI.BoundPropertyEntry, ByVal parsedData As Object, ByVal context As System.Web.Compilation.ExpressionBuilderContext) As System.CodeDom.CodeExpression
			Return New CodeSnippetExpression(parsedData.ToString())
		End Function         

	End Class         

	&lt;Compilation.ExpressionPrefix("Js")&gt; _
 Class JavascriptExpressionBuilder
		Inherits StaticContentExpressionBuilder         

		Protected Overrides ReadOnly Property StaticContentExpression() As String
			Get
				Return "StaticContent.PathBuilder.ConvertJavascriptUrl( ""{0}"" )"
			End Get
		End Property         

	End Class         

	&lt;Compilation.ExpressionPrefix("Image")&gt; _
	Class ImageExpressionBuilder
		Inherits StaticContentExpressionBuilder         

		Protected Overrides ReadOnly Property StaticContentExpression() As String
			Get
				Return "StaticContent.PathBuilder.ConvertImageUrl( ""{0}"" )"
			End Get
		End Property         

	End Class         

	&lt;Compilation.ExpressionPrefix("Css")&gt; _
	Class CssExpressionBuilder
		Inherits StaticContentExpressionBuilder         

		Protected Overrides ReadOnly Property StaticContentExpression() As String
			Get
				Return "StaticContent.PathBuilder.ConvertCssUrl( ""{0}"" )"
			End Get
		End Property         

	End Class         

End Namespace</pre>
<p>I&#8217;ve chosen to implement several types of static content (css, images, and js) but that&#8217;s just a matter of convenience. Clearly this could all be done with a single expression. Note the reason I have placed the content type specific methods on PathBuilder is that I need to call these methods in part three (code-behind) where accessing the expressionBuilder assemblies would be pretty awkward.</p>
<p>To tie our new expression builders into the build we need to add some entries to the web.config.</p>
<pre name="code" class="xml">
&lt;compilation debug="true" strict="true" explicit="true"&gt;
	&lt;expressionBuilders&gt;
		&lt;add expressionPrefix="Css" type="StaticContent.CssExpressionBuilder"/&gt;
		&lt;add expressionPrefix="Image" type="StaticContent.ImageExpressionBuilder"/&gt;
		&lt;add expressionPrefix="Js" type="StaticContent.JavascriptExpressionBuilder"/&gt;
	&lt;/expressionBuilders&gt;
&lt;/compilation&gt;</pre>
<p>That&#8217;s it. Now we can do things in our markup like:</p>
<pre name="code" class="xml">
&lt;asp:image imageurl="Image: rose.jpg" runat="server" id="image1"&gt;
&lt;link rel="stylesheet" href="Css: Fonts.css %&gt;" type="text/css" id="FontsCss" runat="server"&gt;</pre>
<p>the image &#8220;rose.jpg&#8221; and css file &#8220;Fonts.css&#8221; will be rendered to the page as urls:<br />
&#8220;applicationPath/StaticContent/1.0.0/Images/rose.jpg&#8221; and &#8220;applicationPath/StaticContent/1.0.0/Css/Fonts.css&#8221; respectively