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

<channel>
	<title>Tallan&#039;s Technology Blog &#187; Enterprise .NET</title>
	<atom:link href="http://blog.tallan.com/category/enterprise-dot-net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tallan.com</link>
	<description>Tallan&#039;s Top Technologists Share Their Thoughts on Today&#039;s Technology Challenges</description>
	<lastBuildDate>Mon, 06 Feb 2012 02:15:46 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Automatically log errors with Elmah in Script0Service-WebService calls</title>
		<link>http://blog.tallan.com/2012/02/03/automatically-log-errors-with-elmah-in-script0service-webservice-calls/</link>
		<comments>http://blog.tallan.com/2012/02/03/automatically-log-errors-with-elmah-in-script0service-webservice-calls/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 17:23:33 +0000</pubDate>
		<dc:creator>Karl Schwirz</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2012/02/03/automatically-log-errors-with-elmah-in-script0service-webservice-calls/</guid>
		<description><![CDATA[If you’ve used Elmah logging in the past then you know it’s a very useful and easy to set up tool in your web applications.&#160; However, when we encounter errors in web services we sometimes do not get the desired logging into the xml file or database, depending on how you have Elmah configured.&#160; This [...]]]></description>
			<content:encoded><![CDATA[<p>If you’ve used Elmah logging in the past then you know it’s a very useful and easy to set up tool in your web applications.&#160; However, when we encounter errors in web services we sometimes do not get the desired logging into the xml file or database, depending on how you have Elmah configured.&#160; This is because when a error occurs in a script service enabled web service, the errors get serialized into JSON and returned to the ajax caller which is then take by the javascript to handle the exception.&#160; The application is left unaware of the exception occurrence. </p>
<p>There is a way however, to intercept the message before it is returned to the front-end and log the error automatically the way we are used to with Elmah.</p>
<p>First we set up an ErrorHandlerFilter class which will override the default error stream message ( {“Message”:”There was an error processing the request.”, “StackTrace”:””, “ExceptionType”:””})} with a more meaningful error message with details.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> <span style="color: #0000ff">using</span> System;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span> <span style="color: #0000ff">using</span> System.Collections.Generic;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span> <span style="color: #0000ff">using</span> System.IO;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span> <span style="color: #0000ff">using</span> System.Linq;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> <span style="color: #0000ff">using</span> System.Text;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span> <span style="color: #0000ff">namespace</span> Namespace.ElmahExtension</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span> {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   9:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ErrorHandlerFilter : Stream</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  10:</span>     {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  12:</span>         <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> Stream _responseFilter;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  13:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  14:</span>         <span style="color: #0000ff">public</span> List&lt;<span style="color: #0000ff">byte</span>&gt; OriginalBytesWritten { get; <span style="color: #0000ff">private</span> set; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  15:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  16:</span>         <span style="color: #0000ff">private</span> <span style="color: #0000ff">const</span> <span style="color: #0000ff">string</span> Content =</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  17:</span>           <span style="color: #006080">&quot;{\&quot;Message\&quot;:\&quot;There was an error processing the request.\&quot;&quot;</span> +</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  18:</span>           <span style="color: #006080">&quot;,\&quot;StackTrace\&quot;:\&quot;\&quot;,\&quot;ExceptionType\&quot;:\&quot;\&quot;}&quot;</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  19:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  20:</span>         <span style="color: #0000ff">public</span> ErrorHandlerFilter(Stream responseFilter)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  21:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  22:</span>             _responseFilter = responseFilter;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  23:</span>             OriginalBytesWritten = <span style="color: #0000ff">new</span> List&lt;<span style="color: #0000ff">byte</span>&gt;();</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  24:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  25:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  26:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Flush()</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  27:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  28:</span>             <span style="color: #0000ff">byte</span>[] bytes = Encoding.UTF8.GetBytes(Content);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  29:</span>             _responseFilter.Write(bytes, 0, bytes.Length);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  30:</span>             _responseFilter.Flush();</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  31:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  32:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  33:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">long</span> Seek(<span style="color: #0000ff">long</span> offset, SeekOrigin origin)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  34:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  35:</span>             <span style="color: #0000ff">return</span> _responseFilter.Seek(offset, origin);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  36:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  37:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  38:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> SetLength(<span style="color: #0000ff">long</span> <span style="color: #0000ff">value</span>)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  39:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  40:</span>             _responseFilter.SetLength(<span style="color: #0000ff">value</span>);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  41:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  42:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  43:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">int</span> Read(<span style="color: #0000ff">byte</span>[] buffer, <span style="color: #0000ff">int</span> offset, <span style="color: #0000ff">int</span> count)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  44:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  45:</span>             <span style="color: #0000ff">return</span> _responseFilter.Read(buffer, offset, count);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  46:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  47:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  48:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Write(<span style="color: #0000ff">byte</span>[] buffer, <span style="color: #0000ff">int</span> offset, <span style="color: #0000ff">int</span> count)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  49:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  50:</span>             <span style="color: #0000ff">for</span> (<span style="color: #0000ff">int</span> i = offset; i &lt; offset + count; i++)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  51:</span>             {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  52:</span>                 OriginalBytesWritten.Add(buffer[i]);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  53:</span>             }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  54:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  55:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  56:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">bool</span> CanRead</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  57:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  58:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.CanRead; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  59:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  60:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  61:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">bool</span> CanSeek</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  62:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  63:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.CanSeek; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  64:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  65:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  66:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">bool</span> CanWrite</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  67:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  68:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.CanWrite; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  69:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  70:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  71:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">long</span> Length</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  72:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  73:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.Length; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  74:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  75:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  76:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">long</span> Position</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  77:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  78:</span>             get { <span style="color: #0000ff">return</span> _responseFilter.Position; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  79:</span>             set { _responseFilter.Position = <span style="color: #0000ff">value</span>; }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  80:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  81:</span>     }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  82:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Now, we’re going to need to set up a class that implements I<em>HttpModule.&#160; </em>which we’ll use to intercept the message being passed after the <em>Request </em>and <em>EndRequest</em> handlers execute.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> <span style="color: #0000ff">using</span> System;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span> <span style="color: #0000ff">using</span> System.Diagnostics;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span> <span style="color: #0000ff">using</span> System.IO;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span> <span style="color: #0000ff">using</span> System.Text;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> <span style="color: #0000ff">using</span> System.Web;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span> <span style="color: #0000ff">using</span> System.Web.Services.Protocols;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span> <span style="color: #0000ff">using</span> Elmah;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   9:</span> <span style="color: #0000ff">namespace</span> Namespace.ElmahExtension</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  10:</span> {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ElmahExtension : IHttpModule</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  12:</span>     {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  13:</span>         <span style="color: #0000ff">private</span> HttpApplication _application;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  14:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  15:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Dispose()</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  16:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  17:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  18:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  19:</span>         <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Init(HttpApplication context)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  20:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  21:</span>             _application = context;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  22:</span>             _application.PostRequestHandlerExecute += OnPostRequestHandlerExecute;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  23:</span>             _application.EndRequest += OnEndRequest;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  24:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  25:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  26:</span>         <span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnPostRequestHandlerExecute(<span style="color: #0000ff">object</span> sender, EventArgs e)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  27:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  28:</span>             var context = sender <span style="color: #0000ff">as</span> HttpApplication;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  29:</span>             <span style="color: #0000ff">if</span>(context != <span style="color: #0000ff">null</span> &amp;&amp; (context.Request.Path.Contains(<span style="color: #006080">&quot;.asmx&quot;</span>) &amp;&amp; (context.Response.StatusCode &gt;= 400 &amp;&amp; context.Response.StatusCode &lt; 600)))</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  30:</span>             {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  31:</span>                 context.Response.Filter = <span style="color: #0000ff">new</span> ErrorHandlerFilter(context.Response.Filter);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  32:</span>             }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  33:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  34:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  35:</span>         <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> OnEndRequest(<span style="color: #0000ff">object</span> sender, EventArgs e) </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  36:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  37:</span>             var context = (HttpApplication)sender;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  38:</span>             var errorHandlerFilter = context.Response.Filter <span style="color: #0000ff">as</span> ErrorHandlerFilter;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  39:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  40:</span>             <span style="color: #0000ff">if</span> (errorHandlerFilter == <span style="color: #0000ff">null</span>)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  41:</span>             {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  42:</span>                 <span style="color: #0000ff">return</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  43:</span>             }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  44:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  45:</span>             var originalContent = Encoding.UTF8.GetString(errorHandlerFilter.OriginalBytesWritten.ToArray());</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  46:</span>             ErrorLog.GetDefault(context.Context).Log(<span style="color: #0000ff">new</span> Error(<span style="color: #0000ff">new</span> Exception(originalContent)));</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  47:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  48:</span>     }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  49:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  50:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Notice in the <em>OnPostRequestHandlerExecute </em>function we’re intercepting any request that comes from a Webservice (.asmx page) and has a status code of greater than 400 (All error code types).&#160; At his point we want to set the ErrorHandelerFilter to the current Response.Filter value.</p>
<p>Now in the OnEndRequest function we want to get the current context and set the error handler based on the filter which should now be persisting the values we set in the previous function.&#160; Once we have the error values all we have to do is call the Elmah manual logging API and log the exception. </p>
<p>The final piece you have to do is set up the webConfig to recognize and use your I<em>HttpModule </em>code. n In your config file navigate down to System.Web &gt;&gt; HttpModules and fill in the attribute accordingly.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">system.web</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">httpModules</span><span style="color: #0000ff">&gt;</span>    </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">add</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;ElmahExtension&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Namespace.ElmahExtension.ElmahExtension&quot;</span><span style="color: #0000ff">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span>     <span style="color: #0000ff">&lt;/</span><span style="color: #800000">httpModules</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">system.web</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></div>
</div>
<p>Once you compile and run, any errors encountered in your web services should now be logged by Elmah just like any others.</p>
<p>&#160;</p>
<p>Thanks to Reddy Kadasani, Mike Gerety and Dylan Barrett for their contributions to this solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2012/02/03/automatically-log-errors-with-elmah-in-script0service-webservice-calls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calling an ASP.Net web service using jQuery and JSON.</title>
		<link>http://blog.tallan.com/2012/01/29/calling-an-asp-net-web-service-using-jquery-and-json/</link>
		<comments>http://blog.tallan.com/2012/01/29/calling-an-asp-net-web-service-using-jquery-and-json/#comments</comments>
		<pubDate>Sun, 29 Jan 2012 19:09:27 +0000</pubDate>
		<dc:creator>Karl Schwirz</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2012/01/29/calling-an-asp-net-web-service-using-jquery-and-json/</guid>
		<description><![CDATA[Let’s say you have a webpage where you need to call a service but cannot perform a post back.&#160; Recently I was on a client engagement where we needed to improve page performance by dynamically loading a navigation tree with a potential for several thousand links.&#160; We implemented a solution that would load each branch [...]]]></description>
			<content:encoded><![CDATA[<p>Let’s say you have a webpage where you need to call a service but cannot perform a post back.&#160; Recently I was on a client engagement where we needed to improve page performance by dynamically loading a navigation tree with a potential for several thousand links.&#160; We implemented a solution that would load each branch as the user clicked on the expanding icon by calling a web service via ajax and passing the required links back to the page and render them client side.&#160; This saved immensely on the load time for the page and improved the user experience </p>
<p>This kind of solution can be applied to several situations such as complex data processing, dynamic loading, or combining them all into a seamless form submission process that would clear the form on post backs. </p>
<p>We can accomplish this process simply by grabbing an event, such as a button click, and collecting all the required information using jQuery.&#160; Next using a JSON call, we can pass all the parameters to the web service and execute our code from there.</p>
<p>Here, I’ll start with a simple .aspx page with jquery, a textbox, and link that will be used to call the web service.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> <span style="background-color: #ffff00">&lt;%@ Master Language=&quot;C#&quot; MasterPageFile=&quot;~/Site.Master&quot; AutoEventWireup=&quot;true&quot; CodeBehind=&quot;ThisPage.cs&quot; Inherits=&quot;ThisSolution.ThisProject.ThisFolder&quot; %&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">asp:Content</span> <span style="color: #ff0000">ID</span><span style="color: #0000ff">=&quot;Content1&quot;</span> <span style="color: #ff0000">ContentPlaceHolderID</span><span style="color: #0000ff">=&quot;HeadContent&quot;</span> <span style="color: #ff0000">runat</span><span style="color: #0000ff">=&quot;server&quot;</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">script</span> <span style="color: #ff0000">src</span><span style="color: #0000ff">=&quot;/Scripts/jquery-1.4.1.min.js&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;text/javascript&quot;</span><span style="color: #0000ff">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">asp:Content</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">asp:Content</span> <span style="color: #ff0000">ID</span><span style="color: #0000ff">=&quot;Content2&quot;</span> <span style="color: #ff0000">ContentPlaceHolderID</span><span style="color: #0000ff">=&quot;MainContent&quot;</span> <span style="color: #ff0000">runat</span><span style="color: #0000ff">=&quot;server&quot;</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">asp:TextBox</span> <font color="#ff0000">ID</font>=”<font color="#0000ff">textBox</font>” <span style="color: #ff0000">TextMode</span><span style="color: #0000ff">=&quot;MultiLine&quot;</span> <span style="color: #ff0000">runat</span><span style="color: #0000ff">=&quot;server&quot;</span><span style="color: #0000ff">&gt;&lt;/</span><span style="color: #800000">asp:TextBox</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></p>
<pre>

<span style="color: #606060">   9:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">a</span> <span style="color: #ff0000">href</span><span style="color: #0000ff">=&quot;#&quot;</span> <span style="color: #ff0000">class</span><span style="color: #0000ff">=&quot;buttonClass&quot;</span><span style="color: #0000ff">&gt;</span> Save <span style="color: #0000ff">&lt;/</span><span style="color: #800000">a</span><span style="color: #0000ff">&gt;</span>

<span style="color: #0000ff">  <font color="#a5a5a5">10</font>:     <span style="color: #0000ff">&lt;</span><span style="color: #800000">asp:Label</span> <font color="#ff0000">ID</font>=”<font color="#0000ff">successLabel</font>” <span style="color: #ff0000">runat</span><span style="color: #0000ff">=&quot;server&quot;</span><span style="color: #0000ff">&gt;&lt;/</span><span style="color: #800000">asp:Label</span><span style="color: #0000ff">&gt;</span></span>
</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">asp:Content</span><span style="color: #0000ff">&gt;</span></pre>
<p><!--CRLF--></div>
</div>
<p>Next, you will need to establish your web service and create an .asmx file.&#160; There are a couple of important things to note here. Line 5 will be by default commented out.&#160; So in order for us to make our JSON call we’re going to need this <em>uncommented</em>.&#160; Also, notice I’m returning a string.&#160; For the purposes of this demo I am going to return a string to the UI and display a message, but you can return any kind of object that can be serialized down to a primitive data type.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> [WebService(Namespace = <span style="color: #006080">&quot;http://tempuri.org/&quot;</span>)]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span> [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span> [System.ComponentModel.ToolboxItem(<span style="color: #0000ff">false</span>)]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span> <span style="color: #008000">// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. </span></pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span> [System.Web.Script.Services.ScriptService]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> wService : System.Web.Services.WebService</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span> {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span>     [WebMethod()]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   9:</span>     [ScriptMethod(UseHttpGet = <span style="color: #0000ff">false</span>, ResponseFormat = ResponseFormat.Json)]</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  10:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> UpdateComment(<span style="color: #0000ff">string</span> textBoxText)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span>     {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  12:</span>         var success = Service.CallToDb(textBoxText);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  13:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  14:</span>         <span style="color: #0000ff">if</span>(success)</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  15:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  16:</span>             <span style="color: #0000ff">return</span> <span style="color: #006080">&quot;Call to Database using text was successful&quot;</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  17:</span>         }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  18:</span>         <span style="color: #0000ff">else</span> </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  19:</span>         {</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  20:</span>             <span style="color: #0000ff">return</span> <span style="color: #006080">&quot;Call to Database using text was not successful&quot;</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  21:</span>         }    </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  22:</span>     }           </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  23:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>I use a jQuery selector to pick up on the mouse click of the link and gather our data into an javascript object.&#160; Note that when passing parameters through this object you have to name them the same way as you do in the parameter declaration of the web service.</p>
<p>When setting up the call to the service you’re going to want to remember to call the “JSON.stringify” function on your data object so that it serializes properly and that your contentType as well as dataType are configured properly as well.</p>
<div>
<div>
<pre><span style="color: #606060">   1:</span> &lt;script type=<span style="color: #006080">'text/javascript&gt;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   2:</span>     $('</span>.buttonClass<span style="color: #006080">').live('</span>click<span style="color: #006080">', function(){</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   3:</span>         var text = $('</span>#textBox<span style="color: #006080">').text();</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   4:</span>         var data = new Object();</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   5:</span>         data.textBoxText = text;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   6:</span>  </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   7:</span>         $.ajax({</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   8:</span>             type: &quot;POST&quot;,</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">   9:</span>             url: &quot;/Ajax/WbServcie.asmx/UpdateComment&quot;,</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  10:</span>             data: JSON.stringify(data),</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  11:</span>             contentType: &quot;application/json; charset=utf-8&quot;,</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  12:</span>             dataType: &quot;json&quot;,</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  13:</span>             success: function(msg){</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  14:</span>                 $('</span>#successLabel<span style="color: #006080">').val(msg);</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  15:</span>             },</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  16:</span>             error: function(msg){</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  17:</span>                 alert('</span>Something, somewhere, has gone terribly wrong');</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  18:</span>                 <span style="color: #0000ff">return</span> <span style="color: #0000ff">false</span>;</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  19:</span>             }</pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  20:</span>         });    </pre>
<p><!--CRLF--></p>
<pre><span style="color: #606060">  21:</span> &lt;/script&gt;</pre>
<p><!--CRLF--></div>
</div>
<p>Once you get a response from the service, you can set any of your data that is returned.&#160; In this case, we’re returning a string indicating the call to the database was successful and will set a label on the page to show that.</p>
<p>And that’s it.&#160; With just a few simple configurations we have a quick call back to the server without having to run an expensive post back. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2012/01/29/calling-an-asp-net-web-service-using-jquery-and-json/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Helpful Extension Method for Visibility in XAML</title>
		<link>http://blog.tallan.com/2012/01/21/creating-a-helpful-extension-method-for-visibility-in-xaml/</link>
		<comments>http://blog.tallan.com/2012/01/21/creating-a-helpful-extension-method-for-visibility-in-xaml/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 00:00:31 +0000</pubDate>
		<dc:creator>Lenni Lobel</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[User Experience Design]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Visibility]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=1478</guid>
		<description><![CDATA[In this post, I’ll show you how to create an extension method for the bool class that will simplify your .NET code in XAML-based apps (either WPF or Silverlight). In particular, this extension method addresses the fact that the Visibility property of UI controls in XAML is not a Boolean (true/false) value (as has traditionally [...]]]></description>
			<content:encoded><![CDATA[<p>In this post, I’ll show you how to create an extension method for the <em>bool</em> class that will simplify your .NET code in XAML-based apps (either WPF or Silverlight). In particular, this extension method addresses the fact that the <em>Visibility </em>property of UI controls in XAML is not a Boolean (true/false) value (as has traditionally been the case for both Windows Forms and ASP.NET). Instead, it’s one of three possible enumerated constant values: <em>Hidden</em>, <em>Collapsed</em>, and <em>Visible</em>.</p>
<p><em>Visible</em> obviously means “visible,” while both <em>Hidden</em> and <em>Collapsed </em>mean “invisible.” The difference between <em>Hidden</em> and <em>Collapsed</em> is merely whether or not the invisible control occupies blank space on the screen that it would occupy if it were visible. <em>Collapsed</em> consumes no space, while <em>Hidden</em> does.</p>
<p>It’s nice to have the three options, but in most cases you’ll find that you just need the two options <em>Visible </em>and <em>Collapsed</em>. If you’re setting visibility to XAML controls using these two enums, you’ve probably noticed that it’s just not as clean as it is with Windows Forms or ASP.NET controls. You typically already have a Boolean value—either as a simple variable, or an expression—that determines whether the control should be visible or not. You could use that value to enable or disable the control, as the <em>IsEnabled</em> property is also a Boolean, but you can’t assign it to the <em>Visibility </em>property because that property expects one of the three <em>Visibility </em>enumerations—not a Boolean. That’s frustrating, because from a UX (user experience) perspective, where these concepts are used to convey “availability” to the user, hiding/showing controls versus enabling/disabling them is a subtlety of UI design. So developers should be able to think (and code) freely in terms of Booleans for both <em>IsEnabled</em> and <em>Visibility</em>.</p>
<p>Consider the C# code to manipulate the <em>Visibility</em> and <em>IsEnabled</em> properties of a button control:</p>
<pre style="background-color: #fcfbe2;border: solid 1px black;padding: 8px">OpenCustomerButton.IsEnabled = <span style="color: blue">false</span>;
OpenCustomerButton.IsEnabled = <span style="color: blue">true</span>;
OpenCustomerButton.Visibility = <span style="color: #2b91af">Visibility</span>.Collapsed;
OpenCustomerButton.Visibility = <span style="color: #2b91af">Visibility</span>.Visible;

<span style="color: blue">bool</span> isAvailable = <span style="color: blue">true</span>;
OpenCustomerButton.IsEnabled = isAvailable;
OpenCustomerButton.Visibility =
  (isAvailable ? <span style="color: #2b91af">Visibility</span>.Collapsed : <span style="color: #2b91af">Visibility</span>.Visible);

<span style="color: #008014">// Set the visibility according another button's enabled/disabled state</span>
OpenCustomerButton.Visibility =
  (ManageCustomersButton.IsEnabled ? <span style="color: #2b91af">Visibility</span>.Visible : <span style="color: #2b91af">Visibility</span>.Collapsed);</pre>
<p>You can see that because <em>Visibility </em>takes the enum rather than a <em>bool</em>, it’s harder to work with than <em>IsEnabled</em>, and just isn’t as neat. But we can do something about this. How? By writing a simple (one-line!) extension method that adds a <em>ToVisibility </em>method to the <em>bool </em>class:</p>
<pre class="brush: plain;">public static class BoolExtensions
{
  public static Visibility ToVisibility(this bool isVisible)
  {
    return (isVisible ? Visibility.Visible : Visibility.Collapsed);
  }
}</pre>
<p>Now the same UI code is much easier to read and write:</p>
<pre style="border: 1px solid black;background-color: #fcfbe2;padding: 8px">OpenCustomerButton.IsEnabled = <span style="color: blue">false</span>;
OpenCustomerButton.IsEnabled = <span style="color: blue">true</span>;
OpenCustomerButton.Visibility = <span style="color: blue">false</span><span style="background-color: yellow">.ToVisibility()</span>;
OpenCustomerButton.Visibility = <span style="color: blue">true</span><span style="background-color: yellow">.ToVisibility()</span>;

<span style="color: blue">bool</span> isAvailable = <span style="color: blue">true</span>;
OpenCustomerButton.IsEnabled = isAvailable;
OpenCustomerButton.Visibility = isAvailable<span style="background-color: yellow">.ToVisibility()</span>;

<span style="color: #008014">// Set the visibility according to another button's enabled/disabled state</span>
OpenCustomerButton.Visibility = ManageCustomersButton.IsEnabled<span style="background-color: yellow">.ToVisibility()</span>;</pre>
<p>Like? Me too. Neatness counts!</p>
<p>It would be even better if we could instead extend every <em>UIElement </em>with a Boolean <em>property </em>called <em>IsVisible</em>, and embed the conversion logic bi-directionally in the property&#8217;s getter and setter. But, unfortunately, you cannot create extension properties in .NET, only extension methods. So extending <em>bool</em> with a <em>ToVisibility</em> method is the next best thing.</p>
<p>One more tip: Put the <em>BoolExtensions </em>class inside a common code namespace that all your XAML classes import, so <em>ToVisibility</em> is always available without needing to add an extra <em>using </em>statement.</p>
<p>Remember, abusing extension methods quickly leads to messy, buggy code. Instead, find appropriate uses for extension methods that yield cleaner, tighter code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2012/01/21/creating-a-helpful-extension-method-for-visibility-in-xaml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Overview of Simple Parallel Programming with .NET 4.0</title>
		<link>http://blog.tallan.com/2012/01/06/overview-of-simple-parallel-programming-with-net-4-0/</link>
		<comments>http://blog.tallan.com/2012/01/06/overview-of-simple-parallel-programming-with-net-4-0/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 22:33:17 +0000</pubDate>
		<dc:creator>Micael George</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=1937</guid>
		<description><![CDATA[Today’s modern day computers contain multi-core hardware capable of performing multiple tasks simultaneously, also known as parallel processing. Prior to .Net 4.0 the norm was to use synchronous operations to perform multi-threading. Although some level of synchronization logic is needed for data that is shared, the simple .NET 4.0 multi-threading technique presented in this article [...]]]></description>
			<content:encoded><![CDATA[<p>Today’s modern day computers contain multi-core hardware capable of performing multiple tasks simultaneously, also known as parallel processing. Prior to .Net 4.0 the norm was to use synchronous operations to perform multi-threading. Although some level of synchronization logic is needed for data that is shared, the simple .NET 4.0 multi-threading technique presented in this article is excellent for scenarios when you have large data and do not have shared dependencies between the data.</p>
<p>To use the parallel feature in .NET 4.0 you need to use the namespace <em>System.Threading.Tasks</em>. Then you simply take the list structure that you want to traverse and iterate through it using Parallel.ForEach(IEnumerable&lt;TSource&gt; source, Action&lt;TSource&gt; body). For example,</p>
<p style="text-align: left">Parallel.ForEach(someLargeList, item =&gt;</p>
<p style="text-align: left">{</p>
<p style="text-align: left">doSomething();</p>
<p style="text-align: left">});.</p>
<p>For information on synchronized parallel programming, take a look at <a title="Parallelism in .NET – Part 4, Imperative Data Parallelism: Aggregation" href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/" target="_self">http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/.</a> The author goes over how you can synchronize dependent data using the .NET 4.0 multithreading feature.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2012/01/06/overview-of-simple-parallel-programming-with-net-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Look at Optional Parameters, Named Parameters and Permanent Redirect in .NET 4.0</title>
		<link>http://blog.tallan.com/2012/01/05/a-look-at-optional-parameters-named-parameters-and-permanent-redirect-in-net-4-0/</link>
		<comments>http://blog.tallan.com/2012/01/05/a-look-at-optional-parameters-named-parameters-and-permanent-redirect-in-net-4-0/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 23:44:24 +0000</pubDate>
		<dc:creator>Micael George</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=1926</guid>
		<description><![CDATA[While getting acquainted with VS 2010 and .NET 4.0, I’ve come across some improvements that that I’ll be sharing in this blog. Three features in particular are Optional Parameters, Named Parameters and Permanent Redirect.
Before .NET 4.0 one would have to overload methods if they wanted the ability to implement optional parameters. With this latest version [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left">While getting acquainted with VS 2010 and .NET 4.0, I’ve come across some improvements that that I’ll be sharing in this blog. Three features in particular are Optional Parameters, Named Parameters and Permanent Redirect.</p>
<p style="text-align: left">Before .NET 4.0 one would have to overload methods if they wanted the ability to implement optional parameters. With this latest version of .NET, developers simply have to add the optional parameter in the last position of parameters as displayed below.</p>
<div id="attachment_1930" class="wp-caption aligncenter" style="width: 498px"><a href="http://blog.tallan.com/wp-content/uploads/2012/01/example11.png"><img class="size-full wp-image-1930 " src="http://blog.tallan.com/wp-content/uploads/2012/01/example11.png" alt="Example of Optional Parameters" width="488" height="149" /></a><p class="wp-caption-text">Example of Optional Parameters</p></div>
<p style="text-align: left">Another new feature in .NET 4.0 is named parameters, which allow you to ignore the parameter order and mention parameters with names in a different order. For example:</p>
<p style="text-align: left">
<div id="attachment_1931" class="wp-caption aligncenter" style="width: 461px"><a href="http://blog.tallan.com/wp-content/uploads/2012/01/sample21.png"><img class="size-full wp-image-1931 " src="http://blog.tallan.com/wp-content/uploads/2012/01/sample21.png" alt="Example of Named Parameters" width="451" height="134" /></a><p class="wp-caption-text">Example of Named Parameters</p></div>
<p>Although Microsoft coins this as an improvement, I find that this gives way for confusing code that may be hard to manage. For instance, imagine reading several lines of code, written by someone else, with methods having parameters all jumbled in no particular order.</p>
<p>Finally, in situations where we want to redirect users to a new page permanently and update the search engine’s indexes, a new command <em>Response.RedirectPermanent</em> can be used in .NET 4.0. In previous versions of .NET, <em>Response.Redirect</em> was used to do the redirection. The caveat in the aforementioned approach was that the header information for the page would not be updated, therefore allowing search engines to keep the old information of the page in their indexes for search. With the new command <em>Response.RedirectPermanent</em>, header information is updated on the server, the user is directly redirected to the new page and it saves a double trip to server as well. In addition, search engines, on re-indexing of that site and page, update the header information in their index for better performance on searches.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2012/01/05/a-look-at-optional-parameters-named-parameters-and-permanent-redirect-in-net-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Changing SharePoint Default ASP.NET compiler to use ASP.NET 3.5</title>
		<link>http://blog.tallan.com/2011/12/31/changing-sharepoint-default-asp-net-compiler-to-use-asp-net-3-5/</link>
		<comments>http://blog.tallan.com/2011/12/31/changing-sharepoint-default-asp-net-compiler-to-use-asp-net-3-5/#comments</comments>
		<pubDate>Sat, 31 Dec 2011 14:08:00 +0000</pubDate>
		<dc:creator>Michael Gerety</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[SharePoint 2010]]></category>
		<category><![CDATA[SharePoint Foundation]]></category>
		<category><![CDATA[SharePoint Server]]></category>
		<category><![CDATA[development]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2011/12/31/changing-sharepoint-default-asp-net-compiler-to-use-asp-net-3-5/</guid>
		<description><![CDATA[Overview
While SharePoint 2010 supports .NET 3.5, it uses the .NET 2.0 compiler by default for ASP.NET pages.&#160; If you write any UserControls or consume any DLLs in your hosted ASPX pages that utilizes .NET 3.5 features such as the var keyword, extension methods, and LINQ, you’ll get compilation error messages when attempting to access those [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>While SharePoint 2010 supports .NET 3.5, it uses the .NET 2.0 compiler by default for ASP.NET pages.&#160; If you write any UserControls or consume any DLLs in your hosted ASPX pages that utilizes .NET 3.5 features such as the var keyword, extension methods, and LINQ, you’ll get compilation error messages when attempting to access those pages.</p>
<p>To resolve this issue, you can edit the web.config in your site collection’s virtual directory (Usually under \inetpub\wwwroot\wss\virtualdirectories\&lt;site&gt;).&#160; Add the following snippet under the configuration element:</p>
<p>&#160;</p>
<pre><span class="kwrd">&lt;</span><span class="html">system.codedom</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">compilers</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">compiler</span> <span class="attr">language</span><span class="kwrd">=&quot;c#;cs;csharp&quot;</span> <span class="attr">extension</span><span class="kwrd">=&quot;.cs&quot;</span> <span class="attr">warningLevel</span><span class="kwrd">=&quot;4&quot;</span>
              <span class="attr">type</span><span class="kwrd">=&quot;Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0,
                    Culture=neutral, PublicKeyToken=b77a5c561934e089&quot;</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">providerOption</span> <span class="attr">name</span><span class="kwrd">=&quot;CompilerVersion&quot;</span> <span class="attr">value</span><span class="kwrd">=&quot;v3.5&quot;</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">providerOption</span> <span class="attr">name</span><span class="kwrd">=&quot;WarnAsError&quot;</span> <span class="attr">value</span><span class="kwrd">=&quot;false&quot;</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">compiler</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">compilers</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">system.codedom</span><span class="kwrd">&gt;</span> </pre>
<p>
.csharpcode, .csharpcode pre<br />
{<br />
	font-size: small;<br />
	color: black;<br />
	font-family: consolas, &#8220;Courier New&#8221;, courier, monospace;<br />
	background-color: #ffffff;<br />
	/*white-space: pre;*/<br />
}<br />
.csharpcode pre { margin: 0em; }<br />
.csharpcode .rem { color: #008000; }<br />
.csharpcode .kwrd { color: #0000ff; }<br />
.csharpcode .str { color: #006080; }<br />
.csharpcode .op { color: #0000c0; }<br />
.csharpcode .preproc { color: #cc6633; }<br />
.csharpcode .asp { background-color: #ffff00; }<br />
.csharpcode .html { color: #800000; }<br />
.csharpcode .attr { color: #ff0000; }<br />
.csharpcode .alt<br />
{<br />
	background-color: #f4f4f4;<br />
	width: 100%;<br />
	margin: 0em;<br />
}<br />
.csharpcode .lnum { color: #606060; }</p>
<p>Also, look under the Assemblies section and make sure you have the following entries:</p>
<div>
<div class="csharpcode">
<pre><span class="lnum">   1:</span> <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">assembly</span><span class="kwrd">=&quot;System.Web.Extensions, Version=3.5.0.0,Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span class="lnum">   2:</span> <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">assembly</span><span class="kwrd">=&quot;System.Xml.Linq, Version=3.5.0.0,Culture=neutral, PublicKeyToken=B77A5C561934E089&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span class="lnum">   3:</span> <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">assembly</span><span class="kwrd">=&quot;Microsoft.SharePoint, Version=14.0.0.0,Culture=neutral, PublicKeyToken=71e9bce111e9429c&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span class="lnum">   4:</span> <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">assembly</span><span class="kwrd">=&quot;System.Web.Extensions, Version=3.5.0.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span class="lnum">   5:</span> <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">assembly</span><span class="kwrd">=&quot;Microsoft.Web.CommandUI, Version=14.0.0.0,Culture=neutral, PublicKeyToken=71e9bce111e9429c&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span class="lnum">   6:</span> <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">assembly</span><span class="kwrd">=&quot;Microsoft.SharePoint.Search, Version=14.0.0.0,Culture=neutral, PublicKeyToken=71e9bce111e9429c&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span class="lnum">   7:</span> <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">assembly</span><span class="kwrd">=&quot;Microsoft.Office.Access.Server.UI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p><!--CRLF--></p>
<pre><span class="lnum">   8:</span> <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">assembly</span><span class="kwrd">=&quot;Microsoft.SharePoint.Publishing, Version=14.0.0.0,Culture=neutral, PublicKeyToken=71e9bce111e9429c&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p><!--CRLF--></div>
</div>
<p>&#160;</p>
<p><em>Note: You can also add other .NET 3.5 assemblies here as needed.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2011/12/31/changing-sharepoint-default-asp-net-compiler-to-use-asp-net-3-5/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to setup TFS Check-in alerts for specific folders in Visual Studio 2008 and 2010</title>
		<link>http://blog.tallan.com/2011/11/21/how-to-setup-tfs-check-in-alerts-for-specific-folders-in-visual-studio-2008-and-2010/</link>
		<comments>http://blog.tallan.com/2011/11/21/how-to-setup-tfs-check-in-alerts-for-specific-folders-in-visual-studio-2008-and-2010/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 23:27:00 +0000</pubDate>
		<dc:creator>rlanzilli</dc:creator>
				<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[Check-in Alerts]]></category>
		<category><![CDATA[TFS]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/2011/11/22/how-to-setup-tfs-check-in-alerts-for-specific-folders-in-visual-studio-2008-and-2010/</guid>
		<description><![CDATA[Overview
This walkthrough will explain how to setup email alerts in TFS when there is a check-in. Using this method, you can not only select a TFS Project, but you can also select an individual folder. This is useful if you are not interested in some folders in the project, but want alerts on others. 
TFS [...]]]></description>
			<content:encoded><![CDATA[<h1>Overview</h1>
<p>This walkthrough will explain how to setup email alerts in TFS when there is a check-in. Using this method, you can not only select a TFS Project, but you can also select an individual folder. This is useful if you are not interested in some folders in the project, but want alerts on others. </p>
<h1>TFS Check-In Alerts in Visual Studio 2008</h1>
<p>First, TFS Power Tools must be installed for Visual Studio 2008 (<a href="http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&amp;id=15836">Link</a>), and Team Explorer (<a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=16338">Link</a>).</p>
<p>First make sure you are connected to TFS.</p>
<blockquote><p>Tools &gt;&gt; Connect to Team Foundation Server…</p>
</blockquote>
<p>Open Source Control Explorer.</p>
<blockquote><p>View &gt;&gt; Other Windows &gt;&gt; Source Control Explorer.</p>
</blockquote>
<p>Navigate to the folder that you want notifications on.</p>
<p>Right click and select &quot;Alert on Change…&quot;</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0011.png"><img style="border-right-width: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image001" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image001_thumb1.png" width="233" height="484" /></a></p>
<p>The following popup window will display. From here you can set the alert name and the email that you want to send it to. It will try to default itself to the folder name and your email.</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0021.png"><img style="border-right-width: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image002" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image002_thumb1.png" width="446" height="208" /></a></p>
<p>After that, you can view and modify the alert from the &quot;Alerts Editor&quot;</p>
<blockquote><p>Team &gt;&gt; Alerts Editor&#8230;</p>
</blockquote>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0031.png"><img style="border-right-width: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image003" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image003_thumb1.png" width="245" height="272" /></a></p>
<p>You can also access that menu from the Team Explorer:</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image004.png"><img style="border-right-width: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image004" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image004_thumb.png" width="200" height="168" /></a></p>
<p>Once you open that, the original alert definition is as follows:</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0052.png"><img style="border-right-width: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image005" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image005_thumb2.png" width="644" height="219" /></a></p>
<p>I usually don’t mind getting an alert when I check-in, so I usually remove the second row from the grid. You can also specify this in the add dialog above, but I wanted to display it here as an example.</p>
<p>From here, you can modify the alert as necessary. If you have a nightly or weekly build you may not want notifications from that, so you can exclude those as shown below.</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0061.png"><img style="border-right-width: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image006" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image006_thumb1.png" width="644" height="220" /></a></p>
<p>From the Alerts Editor, you can also specify other event types shown below.</p>
<h3>Work Item Alerts</h3>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0071.png"><img style="border-right-width: 0px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image007" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image007_thumb1.png" width="445" height="414" /></a></p>
<h3>Check In Alerts</h3>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0081.png"><img style="border-right-width: 0px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image008" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image008_thumb1.png" width="445" height="370" /></a></p>
<h3>Build Alerts</h3>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0091.png"><img style="border-right-width: 0px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image009" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image009_thumb1.png" width="445" height="349" /></a></p>
<h1>TFS Check-In Alerts in Visual Studio 2010</h1>
<p>This can also be done in Visual Studio 2010, but you will need the TFS 2010 Power Tools (<a href="http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f">Link</a>)</p>
<p>The setup or modification of alerts is very similar to that in Visual Studio 2008. One difference shown below is how you access the Alerts Explorer from Team Explorer.</p>
<p>Instead of clicking on the &quot;Alerts&quot; button for a specific project, you have to right click on the TFS server, and select Alerts Explorer.</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0101.png"><img style="border-right-width: 0px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image010" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image010_thumb1.png" width="407" height="228" /></a></p>
<p>You can still access this menu from Team &gt;&gt; Alerts Explorer as in Visual Studio 2008.</p>
<p>You also still get the same &quot;Alert on Change…&quot; option from Source Control Explorer.</p>
<p><a href="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image0111.png"><img style="border-right-width: 0px;margin: 0px 0px 18px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="clip_image011" src="http://blog.tallan.com/wp-content/uploads/2011/11/clip_image011_thumb1.png" width="252" height="484" /></a></p>
<p>Hope this helps.</p>
<h3>Resources</h3>
<p>Visual Studio Power Tools: <a href="http://msdn.microsoft.com/en-us/vstudio/bb980963.aspx">http://msdn.microsoft.com/en-us/vstudio/bb980963.aspx</a></p>
<p>TFS 2008 Power Tools: <a href="http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&amp;id=15836">http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&amp;id=15836</a></p>
<p>Team System 2008 Team Explorer: <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=16338">http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=16338</a></p>
<p>TFS 2010 Power Tools: <a href="http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f">http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f</a></p>
<p>Robert Lanzilli (<a href="mailto:robert.lanzilli@tallan.com">robert.lanzilli@tallan.com</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2011/11/21/how-to-setup-tfs-check-in-alerts-for-specific-folders-in-visual-studio-2008-and-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using SqlFileStream with C# to Access SQL Server FILESTREAM Data</title>
		<link>http://blog.tallan.com/2011/08/22/using-sqlfilestream-with-c-to-access-sql-server-filestream-data/</link>
		<comments>http://blog.tallan.com/2011/08/22/using-sqlfilestream-with-c-to-access-sql-server-filestream-data/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 19:10:52 +0000</pubDate>
		<dc:creator>Lenni Lobel</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[FILESTREAM]]></category>
		<category><![CDATA[OpenSqlFilestream]]></category>
		<category><![CDATA[SqlFileStream]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=1303</guid>
		<description><![CDATA[FILESTREAM is a powerful feature in SQL Server that stores varbinary(max) column data (BLOBs) in the file system (where BLOBs belongs) rather than in the database&#8217;s structured file groups (where BLOBs kill performance). This feature was first introduced in SQL Server 2008, and is now being expanded with the new FileTable feature coming in SQL [...]]]></description>
			<content:encoded><![CDATA[<p>FILESTREAM is a powerful feature in SQL Server that stores <em>varbinary(max)</em> column data (BLOBs) in the file system (where BLOBs belongs) rather than in the database&#8217;s structured file groups (where BLOBs kill performance). This feature was first introduced in SQL Server 2008, and is now being expanded with the new FileTable feature coming in SQL Server 2012 (code-named “Denali”). This post contains abbreviated updated FILESTREAM coverage that I&#8217;ll be adding to Tallan&#8217;s new book <em>Programming SQL Server 2012</em> (to be published, hopefully, shortly after the first quarter of 2012).</p>
<p>If you’re not already familiar with FILESTREAM, you can get the necessary background by reading these two articles: <a href="http://bit.ly/lenniblog_FILESTREAM1" target="_blank">Introducing FILESTREAM</a> and <a href="http://bit.ly/lenniblog_FILESTREAM2" target="_blank">Enabling and Using FILESTREAM</a>. In this post, I’ll show you how to use the <em>SqlFileStream </em>class to achieve high-performance streaming of SQL Server FILESTREAM data in your .NET applications (the code is shown in C#, but can be written in VB .NET as well).</p>
<h3>What Is SqlFileStream?</h3>
<p><em>SqlFileStream</em> is a class in the .NET Framework (.NET 3.5 SP1 and higher) that wraps the <em>OpenSqlFilestream </em>function exposed by the SQL Server Native Client API. This lets you stream BLOBs directly between SQL Server and your .NET application (written in C# or VB .NET). <em>SqlFileStream</em> is always used within a transaction. You create a <em>SqlFileStream</em> object when you are ready to store and retrieve BLOBs from <em>varbinary(max) FILESTREAM</em> columns. Just at that point in time, SQL Server will “step aside” and let you stream directly against the server&#8217;s file system—a native environment optimized for streaming. This provides you with a streaming “tunnel” between your application and SQL Server’s internally-managed file system. Using <em>SqlFileStream</em> will give your application lightning-fast BLOB performance. Let&#8217;s dive in!</p>
<h3>Creating the Database</h3>
<p>Before getting started, be sure that FILESTREAM is enabled for remote file system access at both the Windows Service and SQL Server instance levels (as explained in <a href="http://bit.ly/lenniblog_FILESTREAM2" target="_blank">Enabling and Using FILESTREAM</a>). Then create a FILESTREAM-enabled database as follows (be sure to create the directory, C:\DB in this example, before creating the database):</p>
<pre class="brush: plain;">CREATE DATABASE PhotoLibrary
 ON PRIMARY
  (NAME = PhotoLibrary_data,
   FILENAME = 'C:\DB\PhotoLibrary_data.mdf'),
 FILEGROUP FileStreamGroup CONTAINS FILESTREAM
  (NAME = PhotoLibrary_blobs,
   FILENAME = 'C:\DB\Photos')
 LOG ON
  (NAME = PhotoLibrary_log,
   FILENAME = 'C:\DB\PhotoLibrary_log.ldf')</pre>
<p>Next, use the database and create a table for BLOB storage as follows:</p>
<pre class="brush: plain;">USE PhotoLibrary
GO

CREATE TABLE PhotoAlbum(
 PhotoId int PRIMARY KEY,
 RowId uniqueidentifier ROWGUIDCOL NOT NULL UNIQUE DEFAULT NEWID(),
 Description varchar(max),
 Photo varbinary(max) FILESTREAM DEFAULT(0x))</pre>
<p>In this table, the <em>Photo</em> column is declared as <em>varbinary(max) FILESTREAM</em>, and will hold pictures that will be stored in the file system behind the scenes. (Refer to <a href="http://bit.ly/lenniblog_FILESTREAM2" target="_blank">Enabling and Using FILESTREAM</a> for a complete explanation of the <em>varbinary(max) FILESTREAM</em> and <em>ROWGUIDCOL</em> columns.) Notice the default value we&#8217;ve established for the BLOB column. The value 0x represents a zero-length binary stream, which is different than <em>NULL</em>. Think of it as the difference between a zero-length string and a null string in .NET; the two are not the same. Similarly, you won’t be able to use <em>SqlFileStream</em> against <em>NULL</em> instances of <em>varbinary(max)</em> FILESTREAM columns, and you’ll soon see why.</p>
<h3>Writing SqlFileStream Code</h3>
<p>Start Visual Studio, create a new Class Library project, and add a <em>PhotoData</em> class as follows:</p>
<pre class="brush: plain;">
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Drawing;
using System.IO;
using System.Transactions;

namespace PhotoLibraryApp
{
  public class PhotoData
  {
    private const string ConnStr =
      &quot;Data Source=.;Integrated Security=True;Initial Catalog=PhotoLibrary;&quot;;

    public static void InsertPhoto
      (int photoId, string desc, string filename)
    {
      const string InsertTSql = @&quot;
        INSERT INTO PhotoAlbum(PhotoId, Description)
          VALUES(@PhotoId, @Description);
        SELECT Photo.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT()
          FROM PhotoAlbum
          WHERE PhotoId = @PhotoId&quot;;

      string serverPath;
      byte[] serverTxn;

      using (TransactionScope ts = new TransactionScope())
      {
        using (SqlConnection conn = new SqlConnection(ConnStr))
        {
          conn.Open();

          using (SqlCommand cmd = new SqlCommand(InsertTSql, conn))
          {
            cmd.Parameters.Add(&quot;@PhotoId&quot;, SqlDbType.Int).Value = photoId;
            cmd.Parameters.Add(&quot;@Description&quot;, SqlDbType.VarChar).Value = desc;
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
              rdr.Read();
              serverPath = rdr.GetSqlString(0).Value;
              serverTxn = rdr.GetSqlBinary(1).Value;
              rdr.Close();
            }
          }
          SavePhotoFile(filename, serverPath, serverTxn);
        }
        ts.Complete();
      }
    }

    private static void SavePhotoFile
      (string clientPath, string serverPath, byte[] serverTxn)
    {
      const int BlockSize = 1024 * 512;

      using (FileStream source =
        new FileStream(clientPath, FileMode.Open, FileAccess.Read))
      {
        using (SqlFileStream dest =
          new SqlFileStream(serverPath, serverTxn, FileAccess.Write))
        {
          byte[] buffer = new byte[BlockSize];
          int bytesRead;
          while ((bytesRead = source.Read(buffer, 0, buffer.Length)) &gt; 0)
          {
            dest.Write(buffer, 0, bytesRead);
            dest.Flush();
          }
          dest.Close();
        }
        source.Close();
      }
    }

    public static Image SelectPhoto(int photoId, out string desc)
    {
      const string SelectTSql = @&quot;
        SELECT
            Description,
            Photo.PathName(),
            GET_FILESTREAM_TRANSACTION_CONTEXT()
          FROM PhotoAlbum
          WHERE PhotoId = @PhotoId&quot;;

      Image photo;
      string serverPath;
      byte[] serverTxn;

      using (TransactionScope ts = new TransactionScope())
      {
        using (SqlConnection conn = new SqlConnection(ConnStr))
        {
          conn.Open();

          using (SqlCommand cmd = new SqlCommand(SelectTSql, conn))
          {
            cmd.Parameters.Add(&quot;@PhotoId&quot;, SqlDbType.Int).Value = photoId;

            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
              rdr.Read();
              desc = rdr.GetSqlString(0).Value;
              serverPath = rdr.GetSqlString(1).Value;
              serverTxn = rdr.GetSqlBinary(2).Value;
              rdr.Close();
            }
          }
          photo = LoadPhotoImage(serverPath, serverTxn);
        }

        ts.Complete();
      }

      return photo;
    }

    private static Image LoadPhotoImage(string filePath, byte[] txnToken)
    {
      Image photo;

      using (SqlFileStream sfs =
        new SqlFileStream(filePath, txnToken, FileAccess.Read))
      {
        photo = Image.FromStream(sfs);
        sfs.Close();
      }

      return photo;
    }

  }
}</pre>
<p>Let’s explain the code in detail. We’ll start at the top with some required namespace inclusions. The two <em>using</em> statements to take notice of are <em>System.Data.SqlTypes</em> and <em>System.Transactions</em>. The <em>System.Data.SqlTypes</em> namespace defines the <em>SqlFileStream</em> class that we’ll be using to stream BLOBs. No special assembly reference is required to use this class, because it is provided by the System.Data.dll assembly that our project is already referencing (Visual Studio set this reference automatically when it created our project). The <em>System.Transactions </em>namespace defines the <em>TransactionScope</em> class that lets us code implicit transactions against the database. This class is provided by the <em>System.Transactions.dll</em> assembly, which is not referenced automatically. You’ll need to add a reference to it now, or the code will not compile. Right-click the project in Solution Explorer and choose Add Reference. In the Add Reference dialog, click the .NET tab, and scroll to find the <em>System.Transactions</em> component. Then double-click it to add the reference.</p>
<p>At the top of the class, we define a connection string as a hard-coded constant named <em>ConnStr</em>. This is just for demonstration purposes; a real-world application would store the connection string elsewhere (such as in a configuration file, possibly encrypted), but we’re keeping our example simple.</p>
<h3>Streaming Into SQL Server</h3>
<p>The first method defined in the class is <em>InsertPhoto</em>, which accepts a new photo integer ID, string description, and full path to an image file to be saved to the database. Notice that the <em>InsertTSql</em> string constant defined at the top of the method specifies an <em>INSERT</em> statement that includes the <em>PhotoId</em> and <em>Description</em> columns, but not the actual <em>Photo</em> BLOB column itself. Instead, the <em>INSERT</em> statement is followed immediately by a <em>SELECT</em> statement that retrieves two pieces of information we’ll use to stream the BLOB into <em>Photo</em> column much more efficiently than using ordinary T-SQL—namely, a logical UNC path name to the file and the transactional context token. These are the two values needed to use <em>SqlFileStream</em>, and you’re about to see how exactly. But all we’ve done so far is define a constant holding two T-SQL statements. The constant is followed by two variables declarations <em>serverPath</em> and <em>serverTxn</em> that will receive the two special values when we later execute those T-SQL statements.</p>
<p>The method then creates and enters a new <em>TransactionScope </em>block. This does not actually begin the database transaction (we’ve not even connected to the database yet), but rather declares that all data access within the block (and in any code called from within the block) must participate in a database transaction. Inside the <em>TransactionScope</em> block, the code creates and opens a new <em>SqlConnection</em>. <a>Being the first data access code inside the <em>TransactionScope</em> block, this also implicitly begins the database transaction.</a> Next, it creates a <em>SqlCommand</em> object associated with the open connection and prepares its command text to contain our T-SQL statements (the <em>INSERT</em> followed by the <em>SELECT</em>).</p>
<p>Invoking the <em>ExecuteReader</em> method executes the T-SQL statements and returns a reader from which we can retrieve the values returned by the <em>SELECT</em> statement. The transaction is still pending at this time. Our <em>INSERT</em> statement does not provide a value for <em>RowId</em> and instead allows SQL Server to automatically generate and assign a new <em>uniqueidentifier ROWGUID</em> value by default just like before when we used T-SQL to insert the first two rows. We’ve also pointed out that no value is provided for the <em>Photo</em> column—and this is exactly how the default 0x value that we defined earlier for the <em>Photo</em> column comes into play (we said we’d come back to it, and here we are).</p>
<p>Although the row has been added by the <em>INSERT</em> statement, it will rollback (disappear) if a problem occurs before the transaction is committed. Because we didn’t provide a BLOB value for the <em>Photo</em> column in the new row, SQL Server honors the default value 0x that we established for it in the <em>CREATE TABLE </em>statement for <em>PhotoAlbum</em>. This represents a zero-length binary stream, which is completely different than <em>NULL</em>. Being a <em>varbinary(max)</em> column decorated with the <em>FILESTREAM</em> attribute, an empty file gets created in the file system that SQL Server associates with the new row. At the same time, SQL Server initiates an NTFS file system transaction over this new empty file and synchronizes it with the database transaction. So just like the new row, the new file will disappear if the database transaction does not commit successfully.</p>
<p>Immediately following the <em>INSERT</em> statement, the <em>SELECT</em> statement returns <em>Photo.PathName</em> and <em>GET_FILESTREAM_TRANSACTION_CONTEXT</em>. What we’re essentially doing with the <em>WHERE</em> clause in this <em>SELECT</em> statement is reading back the same row we have just added (but not yet committed) to the <em>PhotoAlbum</em> table in order to reference the BLOB stored in the new file that was just created (also not yet committed) in the file system.</p>
<p>The value returned by <em>Photo.PathName</em> is a fabricated path to the BLOB for the selected <em>PhotoId</em>. The path is expressed in UNC format, and points to the network share name established for the server instance when we first enabled FILESTREAM (this is <em>MSSQLSERVER</em> in our example, as shown in Figure 9-1). It is not a path the file’s physical location on the server, but rather contains information SQL Server can use to derive the file’s physical location. For example, you’ll notice that it always contains the GUID value in the <em>uniqueidentifier ROWGUIDCOL</em> column of the BLOB’s corresponding row. We retrieve the path value from the reader’s first column and store it in the <em>serverPath </em>string variable.</p>
<p>We just explained how SQL Server initiated an NTFS file system transaction over the FILESTREAM data in the new row’s <em>Photo</em> column when we started our database transaction. The <em>GET_FILESTREAM_TRANSACTION_CONTEXT</em> function returns a handle to that NTFS transaction (if you’re not inside a transaction, this function will return NULL and your code won’t work). We obtain the transaction context, which is returned by the reader’s second column as a <em>SqlBinary</em> value, and store it in the byte array named <em>serverTxn</em>.</p>
<p>Armed with the BLOB path reference in <em>serverPath</em> and the transaction context in <em>serverTxn</em>, we have what we need to create a <em>SqlFileStream</em> object and perform direct file access to stream our image into the <em>Photo</em> column. We close the reader, terminate its <em>using</em> block, then terminate the enclosing <em>using</em> block for the <em>SqlConnection</em> as well. This would normally close the database connection implicitly, but that gets deferred in this case because the code is still nested inside the outer <em>using</em> block for the <em>TransactionScope</em> object. So the connection is still open at this time, and the transaction is still pending. It is precisely at this point that we call the <em>SavePhotoFile</em> method to stream the specified image file into the <em>Photo</em> column of the newly inserted <em>PhotoAlbum</em> row, overwriting the empty file just created by default. When control returns from <em>SavePhotoFile</em>, the <em>TransactionScope</em> object’s <em>Complete</em> method is invoked and its <em>using</em> block is terminated, signaling the transaction management API that everything worked as expected. This implicitly commits the database transaction (which in turn commits the NTFS file system transaction) and closes the database connection.</p>
<p>The <em>SavePhotoFile</em> method reads from the source file and writes to the database FILESTREAM storage in 512 KB chunks at a time using ordinary .NET streaming techniques. The method begins by defining a <em>BlockSize</em> integer constant that is set to a reasonable value of 512 KB. Picture files larger than this will be streamed to the server in 512 KB blocks at a time. The local source image file (in <em>clientPath</em>) is then opened on an ordinary read-only <em>FileStream</em> object.</p>
<p>Then the destination file is opened by passing the two special values (<em>serverPath</em> and <em>serverTxn</em>), along with a <em>FileAccess.Write</em> enumeration requesting write access, into the <em>SqlFileStream</em> constructor. Like the source <em>FileStream</em> object, <em>SqlFileStream</em> inherits from <em>System.IO.Stream</em>, so it can be treated just like any ordinary stream. Thus, you attain write access to the destination BLOB on the database server’s NTFS file system. Remember that this output file is enlisted in an NTFS transaction and nothing you stream to it will be permanently saved until the database transaction is committed by the terminating <em>TransactionScope</em> block, after <em>SavePhotoFile</em> completes. The rest of the <em>SavePhotoFile</em> method implements a simple loop that reads from the source <em>FileStream</em> and writes to the destination <em>SqlFileStream</em>, one 512 KB block at a time until the entire source file is processed, and then it closes both streams.</p>
<h3>Streaming Out From SQL Server</h3>
<p>The rest of the code contains methods to retrieve existing photos and stream their content from the file system into an <em>Image</em> object for display. You’ll find that this code follows the same pattern as the last, only now we’re performing read access.</p>
<p>The <em>SelectPhoto</em> method accepts a photo ID and returns the string description from the database in an output parameter. The actual BLOB itself is returned as the method’s return value in a <em>System.Drawing.Image</em> object. We populate the <em>Image</em> object with the BLOB by streaming into it from the database server’s NTFS file system using <em>SqlFileStream</em>. Once again, we start things off by entering a <em>TransactionScope</em> block and opening a connection. We then execute a simple <em>SELECT</em> statement that queries the <em>PhotoAlbum</em> table for the record specified by the photo ID and returns the description and full path to the image BLOB, as well as the FILESTREAM transactional context token. And once again we use the path name and transactional context with <em>SqlFileStream</em> to tie into the server’s file system in the <em>LoadPhotoImage</em> method.</p>
<p>Just as when we were inserting new photos (only this time using <em>FileAccess.Read</em> instead of <em>FileAccess.ReadWrite</em>), we create a new <em>SqlFileStream</em> object from the logical path name and transaction context. We then pull the BLOB content directly from the NTFS file system on the server into a new <em>System.Drawing.Image</em> object using the static <em>Image.FromStream</em> method against the <em>SqlFileStream</em> object. The populated image can then be passed back up to a Windows Forms application, where it can be displayed using the <em>Image</em> property of a <em>PictureBox</em> control.</p>
<p>Or, to stream a photo over HTTP from a simple ASP.NET service:</p>
<pre class="brush: plain;">using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Transactions;
using System.Web.UI;

namespace PhotoLibraryHttpService
{
  public partial class PhotoService : Page
  {
    private const string ConnStr =
      &quot;Data Source=.;Integrated Security=True;Initial Catalog=PhotoLibrary&quot;;

    protected void Page_Load(object sender, EventArgs e)
    {
      int photoId = Convert.ToInt32(Request.QueryString[&quot;photoId&quot;]);
      if (photoId == 0)
      {
        return;
      }

      const string SelectTSql = @&quot;
        SELECT Photo.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT()
         FROM PhotoAlbum
         WHERE PhotoId = @PhotoId&quot;;

      using (TransactionScope ts = new TransactionScope())
      {
        using (SqlConnection conn = new SqlConnection(ConnStr))
        {
          conn.Open();

          string serverPath;
          byte[] serverTxn;

          using (SqlCommand cmd = new SqlCommand(SelectTSql, conn))
          {
            cmd.Parameters.Add(&quot;@PhotoId&quot;, SqlDbType.Int).Value = photoId;

            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
              rdr.Read();
              serverPath = rdr.GetSqlString(0).Value;
              serverTxn = rdr.GetSqlBinary(1).Value;
              rdr.Close();
            }
          }

          this.StreamPhotoImage(serverPath, serverTxn);
        }
        ts.Complete();
      }
    }

    private void StreamPhotoImage(string serverPath, byte[] serverTxn)
    {
      const int BlockSize = 1024 * 512;
      const string JpegContentType = &quot;image/jpeg&quot;;

      using (SqlFileStream sfs =
        new SqlFileStream(serverPath, serverTxn, FileAccess.Read))
      {
        byte[] buffer = new byte[BlockSize];
        int bytesRead;
        Response.BufferOutput = false;
        Response.ContentType = JpegContentType;
        while ((bytesRead = sfs.Read(buffer, 0, buffer.Length)) &gt; 0)
        {
          Response.OutputStream.Write(buffer, 0, bytesRead);
          Response.Flush();
        }
        sfs.Close();
      }
    }
  }
}</pre>
<h3>Conclusion</h3>
<p>The <em>OpenSqlFilestream</em> function provides native file streaming capabilities between FILESTREAM storage in the file system managed by SQL Server and any native-code (e.g., C++) application. <em>SqlFileStream </em>provide a managed code wrapper around <em>OpenSqlFilestream</em> that simplifies direct FILESTREAM access from .NET applications (e.g., C# and VB .NET). This post explained how this API works in detail, and showed the complete data access code that uses <em>SqlFileStream</em> for both reading and writing BLOBs to and from SQL Server. That’s everything you need to know to get the most out of FILESTREAM. I hope you enjoyed it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2011/08/22/using-sqlfilestream-with-c-to-access-sql-server-filestream-data/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Three .NET Best Practices to Keep in Mind</title>
		<link>http://blog.tallan.com/2011/06/29/three-net-best-practices-to-keep-in-mind/</link>
		<comments>http://blog.tallan.com/2011/06/29/three-net-best-practices-to-keep-in-mind/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 19:37:54 +0000</pubDate>
		<dc:creator>Michael Gerety</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Best Practices]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=1173</guid>
		<description><![CDATA[Practice #1: Catch Exceptions at the Highest Possible Level (Tier)
In general, exceptions should be bubbled up to the highest possible level to be caught and processed.  For example, in our project, a search goes through the following logical tiers:
UI -&#62; Services -&#62; Data/SharePoint/Refinement -&#62; Web Services
There are quite a few instances where we’re catching exceptions [...]]]></description>
			<content:encoded><![CDATA[<h1>Practice #1: Catch Exceptions at the Highest Possible Level (Tier)</h1>
<p>In general, exceptions should be bubbled up to the highest possible level to be caught and processed.  For example, in our project, a search goes through the following logical tiers:</p>
<p>UI -&gt; Services -&gt; Data/SharePoint/Refinement -&gt; Web Services</p>
<p>There are quite a few instances where we’re catching exceptions in the Data or Services layer, logging them using common logging components or configurations, and then swallowing the exception one way or another.</p>
<p>This is a bad practice for few reasons:</p>
<ul>
<li>This behavior is not transparent to developers that may be using the DLL but do not have access to the source code.</li>
<li> Logging from lower tier components is generally a bad idea, as it either requires a static logging location embedded in the dll or creates a dependency on the UI to provide pre-determined logging mechanism (i.e. EntLib).   (This can get especially ugly with EntLib, and EntLib Logging and ExceptionHandling blocks generally use named “policies” for handling and logging exceptions, and referencing them from a middle-tier component requires any UI consuming it to implement the exact same logging configuration.</li>
<li>Applications consuming the DLL do not know about or are not given the ability to choose how to react to exceptions in the code.</li>
<li>Swallowing exceptions dilutes the effectiveness of unit tests testing these functions, as tests can’t explicitly test for scenarios that might cause specific exceptions,</li>
<li>Swallowing exceptions can make debugging issues a nightmare (if not impossible) for developers that might consume this middle-tier component and not have access to the source code.</li>
<li>Catch blocks have an inherent performance cost.  Catching exceptions unnecessarily results in unnecessary performance degredataion.</li>
</ul>
<p>There are a few legitimate cases where this best practice might not be followed:</p>
<p><strong>1. </strong><strong>The Exception contains potentially sensitive information</strong></p>
<p>If the exception or exception message contains potentially sensitive information such as user credentials, server names, or any other sensitive information, it likely makes sense to catch the exception, create an exception that accurately describes the issue without the sensitive information, then throw that exception.  <em>Note however, there are very few scenarios where this should not occur at the UI layer.</em></p>
<p><em> </em></p>
<p>2. <strong>The exception is too vague or needs more metadata to be meaningful to the code consuming it.</strong></p>
<p>If the exception by itself is too vague or requires rebadging or augmented metadata to be useful to the code consuming it, it generally makes sense to wrap the exception by creating an exception that allows the original exception to be set as an “InnerException”, and augments the original exception with more information.  This new exception should then be thrown.</p>
<p><strong>3. </strong><strong>The exception that was caught should not affect the execution of the code</strong></p>
<p>If an exception occurs that should not affect the execution of the code, it may be swallowed or ignored in limited cases.  However, exceptions really should not be being thrown unless there is a severe enough issue to potentially interrupt program execution, so I’d suggest reviewing the code throwing the exception you are swallowing in this case.</p>
<p>4. <strong>The Exception Occurs At A Physical Tier Boundary</strong></p>
<p>Your multi-tier applications may not only contain multiple logical tiers, but physical tiers as well.  (for example, your web application may rely on a web service layer on a separate physical server).  While your web service layer may be “middle-tier” as far as the overall application is concerned, exceptions should be caught, processed, and logged at the boundary to that physical tier.  Logging on the machine where the services resides aides in issue resolution, and it gives an opportunity to review exceptions for sensitive information before sending them over the network, where they may be intercepted.</p>
<h1>Practice #2: You Should (Almost Never) Catch System.Exception</h1>
<p>You should almost never write the following:</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px;float: none;padding: 0px">
<div style="border: #000080 1px solid;color: #000;font-family: 'Courier New', Courier, Monospace;font-size: 10pt">
<div style="background: #000080;color: #fff;font-family: Verdana, Tahoma, Arial, sans-serif;font-weight: bold;padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd;overflow: auto">
<ol style="background: #ffffff;margin: 0 0 0 2em;padding: 0 0 0 5px">
<li><span style="color: #0000ff">try</span></li>
<li>{</li>
<li> <span style="color: #008000">//Some code here.</span></li>
<li>}</li>
<li><span style="color: #0000ff">catch</span> (System.<span style="color: #2b91af">Exception</span> ex)</li>
<li>{</li>
<li> <span style="color: #008000">//Do something with this exception</span></li>
<li>}</li>
</ol>
</div>
</div>
</div>
<p>This code says that you don’t know what type of exception to expect, so catch them all.</p>
<p>Any exception that the code is not expecting is, by definition, an unexpected or unhandled exception.  <em>You probably want your application to crash (or gracefully exit) with an “Unhandled Exception” message if an unexpected exception occurs! </em>How can you be certain of the stability of the currently running instance of your code if an exception occurred somewhere that you didn’t expect?</p>
<p>Also, catching specific exceptions helps greatly in diagnosing issues, and displaying useful and meaningful error messages to your users.  I think we all know how frustrating a generic error message such as “An error occurred.” can be.</p>
<p>If you think an exception might occur but you don’t know the type, either determine the type and catch it or don’t implement a handler at all!   If you need to throw an exception and there’s not an exception type available that is specific to the error that occurred, create a new one.</p>
<p><strong><em> </em></strong></p>
<p><strong> </strong></p>
<h1>Practice #3: Always Null-Check Objects Returned from a Function Call</h1>
<p>Review the 5 lines of code below.</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px;float: none;padding: 0px">
<div style="border: #000080 1px solid;color: #000;font-family: 'Courier New', Courier, Monospace;font-size: 10pt">
<div style="background: #000080;color: #fff;font-family: Verdana, Tahoma, Arial, sans-serif;font-weight: bold;padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd;overflow: auto">
<ol style="background: #ffffff;margin: 0 0 0 2em;padding: 0 0 0 5px">
<li><span style="color: #0000ff">var</span> result = SomeFunctionThatReturnsAnObject();</li>
<li></li>
<li> <span style="color: #0000ff">if</span> (!<span style="color: #2b91af">String</span>.IsNullOrEmpty(result.SomeValue))</li>
<li> {</li>
<li> <span style="color: #008000">//Do Something</span></li>
<li> }</li>
</ol>
</div>
</div>
</div>
<p>What’s wrong with this picture?</p>
<p>If you said <strong><em>Null Reference Exception</em></strong> you’re right.  <strong><em>Never</em></strong>,<strong><em> ever</em></strong> access any member of any object that has been returned from a function without checking for null.  You should <strong><em>never</em></strong> assume that a function will return an instantiated object.</p>
<p><strong><em>Never. </em></strong></p>
<p><em> </em></p>
<p><strong><em>Even if you wrote the function you’re calling.</em> </strong></p>
<p>We all work on projects with multiple developers, and at any given time another developer (or even you) may alter the code and end up returning a null object without realizing that there is some expectation that an instantiated object be returned by some callers.</p>
<p>Taking the extra time to type 15-20 extra characters can mean the difference between stable software and buggy, error-prone code.</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px;float: none;padding: 0px">
<div style="border: #000080 1px solid;color: #000;font-family: 'Courier New', Courier, Monospace;font-size: 10pt">
<div style="background: #000080;color: #fff;font-family: Verdana, Tahoma, Arial, sans-serif;font-weight: bold;padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd;overflow: auto">
<ol style="background: #ffffff;margin: 0 0 0 2em;padding: 0 0 0 5px">
<li><span style="color: #0000ff">var</span> result = SomeFunctionThatReturnsAnObject();</li>
<li></li>
<li> <span style="color: #0000ff">if</span> (result != <span style="color: #0000ff">null</span> &amp;&amp; !<span style="color: #2b91af">String</span>.IsNullOrEmpty(result.SomeValue))</li>
<li> {</li>
<li> <span style="color: #008000">//Do Something</span></li>
<li> }</li>
</ol>
</div>
</div>
</div>
<h2>Conclusion</h2>
<p>I wrote this as an e-mail to my team after doing some refactoring and realized that it could be beneficial to a wider audience being that violations of these practices are so common.  I’ve made these mistakes (as I’m sure many of us have) numerous times in the past, so writing this up was a good reminder for me to focus on these points when writing code.</p>
<p>Please feel free to post additions, corrections, questions, and concerns in the comments section below!  The dialogue will benefit all involved!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2011/06/29/three-net-best-practices-to-keep-in-mind/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Slides and Code from NYC (Winter) Code Camp 2011&#8211;(How to) Put your Code First with Entity Framework</title>
		<link>http://blog.tallan.com/2011/02/23/slides-and-code-from-nyc-winter-code-camp-2011how-to-put-your-code-first-with-entity-framework/</link>
		<comments>http://blog.tallan.com/2011/02/23/slides-and-code-from-nyc-winter-code-camp-2011how-to-put-your-code-first-with-entity-framework/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 05:19:00 +0000</pubDate>
		<dc:creator>Max Weber</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[User Groups]]></category>
		<category><![CDATA[Code Camp]]></category>
		<category><![CDATA[EF Code First]]></category>
		<category><![CDATA[Entity Data Model]]></category>
		<category><![CDATA[Entity Framework 4]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[MVC 3]]></category>
		<category><![CDATA[NuGet]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[WCF Data Services 4]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=1043</guid>
		<description><![CDATA[I would like to thank everyone for attending my presentation this Saturday at the NYC (Winter) Code Camp! I really enjoyed the high level of interest and participation from the attendees. Unfortunately, we only had 75 minutes to talk about Entity Framework and EF Code First but thankfully we have the internet! 
Thanks to all [...]]]></description>
			<content:encoded><![CDATA[<p>I would like to thank everyone for attending my presentation this Saturday at the NYC (Winter) Code Camp! I really enjoyed the high level of interest and participation from the attendees. Unfortunately, we only had 75 minutes to talk about Entity Framework and EF Code First but thankfully we have the internet! </p>
<p>Thanks to all of the organizers at the NYC Code Camp for an excellent day of learning and networking! This year, it “sold out” in 27 hours! The speakers were excellent and the event was run very smoothly.</p>
<p>I have posted the slide deck (including the demo code) for your viewing pleasure. </p>
<p>Material:</p>
<p>
<div style="padding-bottom: 0px;margin: 0px;padding-left: 0px;padding-right: 0px;float: none;padding-top: 0px" class="wlWriterEditableSmartContent">
<div><a href="http://blog.tallan.com/wp-content/uploads/2011/02/EF.Code_.First_1.pptx" target="_blank">EF Code First.pptx</a></div>
</div>
<div style="padding-bottom: 0px;margin: 0px;padding-left: 0px;padding-right: 0px;float: none;padding-top: 0px" class="wlWriterEditableSmartContent">
<div><a href="http://blog.tallan.com/wp-content/uploads/2011/02/EFCodeFirst.Key_.Solution.zip" target="_self">EFCodeFirst.Key.Solution.zip</a></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2011/02/23/slides-and-code-from-nyc-winter-code-camp-2011how-to-put-your-code-first-with-entity-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

