<?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>Why Can&#039;t You Code?</title>
	<atom:link href="http://www.whycantyoucode.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.whycantyoucode.com</link>
	<description>The highest form of ignorance is when you reject something you don&#039;t know anything about.</description>
	<lastBuildDate>Thu, 25 Feb 2010 14:39:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>How to improve your YSlow &#8220;Add Expires Header&#8221; score in ASP.NET using T4 templates</title>
		<link>http://www.whycantyoucode.com/2010/02/how-to-improve-your-yslow-add-expires-header-score-in-asp-net-using-t4-templates/</link>
		<comments>http://www.whycantyoucode.com/2010/02/how-to-improve-your-yslow-add-expires-header-score-in-asp-net-using-t4-templates/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 14:28:51 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Performance Optimization]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[t4]]></category>
		<category><![CDATA[yslow]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=143</guid>
		<description><![CDATA[If you care about your website performance, I’m sure you must know about the YSlow addin for Firebug. One of its recommendations is to add an Expires header with a far future expiration date for your static content. You can read more about it here. If you use CSS for your layout (which you should) [...]]]></description>
			<content:encoded><![CDATA[<p>If you care about your website performance, I’m sure you must know about the <a href="http://developer.yahoo.com/yslow/" target="_blank">YSlow addin for Firebug</a>.</p>
<p>One of its recommendations is to add an Expires header with a far future expiration date for your static content. You can read more about it <a href="http://developer.yahoo.com/performance/rules.html#expires" target="_blank">here</a>.</p>
<p><a href="http://www.whycantyoucode.com/content/uploads/2010/02/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.whycantyoucode.com/content/uploads/2010/02/image_thumb.png" width="744" height="203" /></a></p>
<p>If you use CSS for your layout (which you should) you are probably using CSS background images as well. These images should very rarely change, so you could just make sure your entire <strong>/images/</strong> directory is served with an appropriate cache expiration header.</p>
<p>If you’re using IIS7, all you need to do is create a <strong>web.config</strong> in your<strong> /images/</strong> folder which contains something like the following:</p>
<pre class="brush: xml; ruler: true; smart-tabs: false;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;configuration&gt;
    &lt;system.webServer&gt;
        &lt;staticContent&gt;
            &lt;clientCache cacheControlMode=&quot;UseExpires&quot; httpExpires=&quot;Sun, 01 Dec 2019 00:00:00 GMT&quot; cacheControlCustom=&quot;&quot; /&gt;
        &lt;/staticContent&gt;
    &lt;/system.webServer&gt;
&lt;/configuration&gt;</pre>
<p>Now the client’s browser can cache your images until 2019, and your <strong>YSlow</strong> score should be dramatically improved.</p>
<p>But what happens when you <strong>need</strong> to change an image? All your returning visitors would have to clear their cache to see the updated version, so that’s something we’re trying to avoid.</p>
<h3>Enter T4 Templates</h3>
<p>To work around this, you can use a feature of IIS and request the static images and including a querystring. For example: <strong>/images/bg.png?something</strong> works the same as<strong> /images/bg.png</strong>, but it comes with the added benefit of the user’s browser thinking they’re entirely different files, so it will cache them <strong>separately</strong>.</p>
<p>Armed with this knowledge, it becomes apparent that we want our <strong>.css</strong> stylesheet to link to images with a versioned querystring, which we can easily just increment when we update our images so it’s all seamless for the visitor.</p>
<p>Using the <strong>Text Template Transformation Toolkit</strong> (T4) readily available in<strong> Visual Studio </strong>we can create a <strong>.tt</strong> file which autogenerates our <strong>.css </strong>and takes care of your versioning needs.</p>
<p>Simply add a new file with a<strong> .tt</strong> extension to your Website Project, and paste the following into it:</p>
<pre class="brush: css; ruler: true; smart-tabs: false;">&lt;#@ template inherits=&quot;Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation&quot; language=&quot;C#v3.5&quot; debug=&quot;true&quot; hostSpecific=&quot;true&quot; #&gt;
&lt;#@ output extension=&quot;.css&quot; #&gt;

/* example css */
body { background:url(&lt;#= GetImage(&quot;main_bg.jpg&quot;) #&gt;) }
/* other css */
.someclass { background:url(&lt;#= GetImage(&quot;main_box_top_bg.jpg&quot;) #&gt;) repeat-x top #FFF; width:960px; }

&lt;#+
// you can simply change the value of the 'version' variable below
// to something else when you update your images

static string version = &quot;1&quot;;

string GetImage(string image)
{

    // replace /images/ with your images directory name
    return &quot;/images/&quot; + image + &quot;?&quot; + version;
}#&gt;</pre>
<p>Notice the <strong>&lt;#= GetImage(“filename.png”) #&gt;</strong> embedded code blocks.</p>
<p>Now, when you <strong>Save </strong>the file in Visual Studio, if your t4 syntax is valid, you should see a generated <strong>.css</strong> file under the <strong>.tt</strong> file in Solution Explorer.</p>
<p><a href="http://www.whycantyoucode.com/content/uploads/2010/02/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.whycantyoucode.com/content/uploads/2010/02/image_thumb1.png" width="167" height="43" /></a></p>
<p>Here’s how the generated <strong>.css</strong> file looks like:</p>
<pre class="brush: css; ruler: true; smart-tabs: false;">/* example css */
body { background:url(/images/main_bg.jpg?1) }
/* other css */
.someclass { background:url(/images/main_box_top_bg.jpg?1) repeat-x top #FFF; width:960px; }</pre>
<p>
  <br />All your layout images should be now cached, and they won’t needlessly be downloaded on every page view. Your visitors will thank you!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2010/02/how-to-improve-your-yslow-add-expires-header-score-in-asp-net-using-t4-templates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Verbose steps to migrate a Silverlight application from .NET RIA Services (July 09) to WCF RIA Services (PDC 09)</title>
		<link>http://www.whycantyoucode.com/2009/11/verbose-steps-to-migrate-a-silverlight-application-from-net-ria-services-july-09-to-wcf-ria-services-pdc-09/</link>
		<comments>http://www.whycantyoucode.com/2009/11/verbose-steps-to-migrate-a-silverlight-application-from-net-ria-services-july-09-to-wcf-ria-services-pdc-09/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 19:25:00 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ria services]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=134</guid>
		<description><![CDATA[These are the steps I had to go through to migrate a Silverlight application that was running on the .NET RIA Services preview released in July 09, to the new WCF RIA Services released during PDC 09: Delete all HttpHandler references to DataService.axd from your web.config. Basically, these two need to go: &#60;system.webServer&#62; ... &#60;handlers&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>These are the steps I had to go through to migrate a <strong>Silverlight</strong> application that was running on the .NET RIA Services preview released in July 09, to the new <strong>WCF</strong> RIA Services released during PDC 09:</p>
<ol>
<li>Delete all HttpHandler references to DataService.axd from your web.config. Basically, these two need to go:
<pre class="brush: xml; ruler: true; smart-tabs: false;">&lt;system.webServer&gt;
  ...
  &lt;handlers&gt;
    ...
    &lt;add name=&quot;DataService&quot; verb=&quot;GET,POST&quot; path=&quot;DataService.axd&quot; type=&quot;System.Web.Ria.DataServiceFactory, System.Web.Ria, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot; /&gt;
  &lt;/handlers&gt;
&lt;/system.webServer&gt;</pre>
<pre class="brush: xml; ruler: true; smart-tabs: false;">&lt;httpHandlers&gt;
  ...
  &lt;add path=&quot;DataService.axd&quot; verb=&quot;GET,POST&quot; type=&quot;System.Web.Ria.DataServiceFactory, System.Web.Ria, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot; validate=&quot;false&quot; /&gt;
&lt;/httpHandlers&gt;</pre>
</li>
<li>Add/update your web.config along the lines of:
</p>
<p>.NET 3.5:</p>
<pre class="brush: xml; ruler: true; smart-tabs: false;">&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;configuration&gt;
  &lt;system.web&gt;
    &lt;httpModules&gt;
      &lt;add name=&quot;DomainServiceModule&quot; type=&quot;System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria,Version=2.0.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35&quot;/&gt;
    &lt;/httpModules&gt;
  &lt;/system.web&gt;
  &lt;system.webServer&gt;
    &lt;modules&gt;
      &lt;add name=&quot;DomainServiceModule&quot; preCondition=&quot;managedHandler&quot; type=&quot;System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria,Version=2.0.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35&quot;/&gt;
    &lt;/modules&gt;
  &lt;system.webServer&gt;
  &lt;system.serviceModel&gt;
    &lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&quot;true&quot;/&gt;
  &lt;/system.serviceModel&gt;
&lt;/configuration&gt;</pre>
<p>.NET 4.0: </p>
<p></p>
<pre class="brush: xml; ruler: true; smart-tabs: false;">&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;configuration&gt;

  &lt;system.web&gt;
    &lt;httpModules&gt;
      &lt;add name=&quot;DomainServiceModule&quot; type=&quot;System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot; /&gt;
    &lt;/httpModules&gt;
    &lt;compilation debug=&quot;true&quot; targetFramework=&quot;4.0&quot; /&gt;
  &lt;/system.web&gt;

  &lt;system.webServer&gt;
    &lt;validation validateIntegratedModeConfiguration=&quot;false&quot;/&gt;
    &lt;modules runAllManagedModulesForAllRequests=&quot;true&quot;&gt;
      &lt;add name=&quot;DomainServiceModule&quot; preCondition=&quot;managedHandler&quot;
          type=&quot;System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot; /&gt;
    &lt;/modules&gt;
    &lt;validation validateIntegratedModeConfiguration=&quot;false&quot; /&gt;
  &lt;/system.webServer&gt;

  &lt;system.serviceModel&gt;
    &lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&quot;true&quot; /&gt;
  &lt;/system.serviceModel&gt;
&lt;/configuration&gt;</pre>
</li>
<li>If you’re throwing <strong>DomainServiceException</strong>, take note that the class has been renamed to <strong>DomainException</strong>. Update your code accordingly. </li>
<li>Remove any reference you may have to <strong>System.Web.DomainServices.Providers.dll</strong>, you will need to add a new reference to either <strong>System.Web.DomainServices.EntityFramework.dll</strong> or <strong>System.Web.DomainServices.LinqToSql.dll</strong> depending on what you use. </li>
<li>Change this:
<pre class="brush: csharp; ruler: true; gutter: false; toolbar: false; smart-tabs: false;">using System.Web.DomainServices.LinqToEntities;</pre>
<p>To this:</p>
<pre class="brush: csharp; ruler: true; gutter: false; toolbar: false; smart-tabs: false;">using System.Web.DomainServices.Providers;</pre>
<p>Everywhere.</p>
</li>
<li>The DomainService.<strong>Context </strong>property has been renamed to <strong>ObjectContext</strong>. Update all your code accordingly.
<p>&#160;</p>
<p><strong>Now, your Web application should build, but you may still get this error while building the actual Silverlight application:</strong></p>
<pre>Error    5    The &quot;CreateRiaClientFilesTask&quot; task failed unexpectedly.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---&gt; System.InvalidOperationException: The AutoGenerateField property has not been set.  Use the GetAutoGenerateField method to get the value.
   at System.ComponentModel.DataAnnotations.DisplayAttribute.get_AutoGenerateField()</pre>
<p>In my case, this was a problem with <strong>the System.ComponentModel.DataAnnotations.dll</strong> reference. Remove it and re-add it from the <strong>Global Assembly Cache</strong>. </p>
</li>
<li>Remove the reference to <strong>System.Windows.Ria.Controls.dll </strong>and add one to <strong>System.Windows.Controls.Ria.dll</strong>. </li>
<li>You will need to update your XAML to reference the new assembly:
<p>Replace <strong>System.Windows.Ria.Controls</strong> with <strong>System.Windows.Controls.Ria</strong> in your namespace declarations in the header of the XAML file. Here’s how the old ones look:</p>
<pre class="brush: xml; ruler: true; gutter: false; toolbar: false; smart-tabs: false;">xmlns:riaControls=&quot;clr-namespace:System.Windows.Controls;assembly=System.Windows.Ria.Controls&quot; xmlns:System_Windows_Data=&quot;clr-namespace:System.Windows.Data;assembly=System.Windows.Ria.Controls&quot;</pre>
</li>
<li><strong>RiaContext </strong>(.Current) has been renamed to <strong>WebContextBase</strong>. It’s in the System.Windows.Ria namespace. </li>
<li><strong>The System.Windows.Ria.Data</strong> namespace has been removed. So make sure to remove it from your <strong>usings</strong> also. </li>
<li><strong>RiaContext.Current.User</strong> is now <strong>WebContextBase.Current.Authentication.User</strong> </li>
<li>In XAML, the namespace for the <strong>ControlParameter</strong> type has changed to <strong>System.Windows.Controls</strong> from <strong>System.Windows.Data</strong>, update accordingly. </li>
<li>If you use Forms Authentication, update the <strong>RiaContext</strong> reference in <strong>App.xaml</strong> to a <strong>WebContext</strong> reference such as:
<pre class="brush: xml; ruler: true; smart-tabs: false;">&lt;Application.ApplicationLifetimeObjects&gt;
    &lt;app:WebContext&gt;
        &lt;app:WebContext.Authentication&gt;
            &lt;appsvc:FormsAuthentication/&gt;
            &lt;!--&lt;appsvc:WindowsAuthentication/&gt;--&gt;
        &lt;/app:WebContext.Authentication&gt;
    &lt;/app:WebContext&gt;
&lt;/Application.ApplicationLifetimeObjects&gt;</pre>
</li>
</ol>
<p>With some luck, your project should be migrated to WCF RIA Services now. These were the steps I needed to get mine working.</p>
<p>Additional breaking changes in the new release can be found <a href="http://code.msdn.microsoft.com/RiaServices/Release/ProjectReleases.aspx?ReleaseId=3570" target="_blank">here</a>.</p>
<p>Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/verbose-steps-to-migrate-a-silverlight-application-from-net-ria-services-july-09-to-wcf-ria-services-pdc-09/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Workaround for Silverlight RIA Services DateTime discrepancy between server and client</title>
		<link>http://www.whycantyoucode.com/2009/11/workaround-for-silverlight-ria-services-datetime-discrepancy-between-server-and-client/</link>
		<comments>http://www.whycantyoucode.com/2009/11/workaround-for-silverlight-ria-services-datetime-discrepancy-between-server-and-client/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 12:07:32 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[ria services]]></category>
		<category><![CDATA[workaround]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=125</guid>
		<description><![CDATA[While working on a Silverlight application. I discovered that all the dates displayed in my DataGrid were skewed by a few hours from the real date stored in the database. Upon a closer look I noticed this skew was closely correlated to the time difference between the server’s time zone and the UTC date. I [...]]]></description>
			<content:encoded><![CDATA[<p>While working on a Silverlight application. I discovered that all the dates displayed in my DataGrid were skewed by a few hours from the real date stored in the database. Upon a closer look I noticed this skew was closely correlated to the time difference between the server’s time zone and the <a href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time" target="_blank">UTC date.</a></p>
<p><strong>I needed my Silverlight application to display and use the exact same dates as the database regardless of the time zone my users were in.</strong></p>
<p>Apparently, there’s a little known <span style="text-decoration: line-through">bug</span> “<a href="http://smehrozalam.wordpress.com/2009/08/07/ria-services-how-dates-are-handled-and-sent-across-the-wire/" target="_blank">feature</a>” in the latest <a href="http://silverlight.net/getstarted/riaservices/" target="_blank">RIA Services Beta</a> for Silverlight that involves dates:</p>
<p>RIA uses <strong>JSON</strong> to send data across the wire, and the Microsoft JSON serializers <a href="http://www.west-wind.com/weblog/posts/471402.aspx" target="_blank">always serialize dates as UTC</a>.</p>
<p>Dates retrieved from the database always seem to come up as <code>DateTimeKind.Unspecified</code>, meaning that the serializer will take a guess and treat them as local dates (in the <strong>server’s </strong>local time zone) and convert them to UTC time before sending out on the wire. </p>
<p>There’s an overridable property in the <code>DomainService</code> class called <code>UsesUtcDateTimes</code> which should in theory make the serializer leave your dates alone by treating them as UTC &#8211; which is still not ideal, but it means it won’t change them further &#8211; the property, however, <em>currently </em>doesn’t do anything.</p>
<p><font color="#cc0000" size="4">The gotcha here is that the <strong>original</strong> time zone of the date is <strong>lost</strong> on the wire. It’s not sent along with the date so there’s no way you could determine, on the client, what time zone the date was in originally!</font></p>
<p><strong>Example:</strong> if the server’s timezone is GMT+1, a date of December 21, 2012 <strong><u>12:21 PM</u></strong> will be converted to the UTC (GMT+0) date of December 21, 2012 <strong><u>11:21 AM</u></strong> before being sent out!</p>
<p>The Silverlight application will now display the UTC date of December 21, 2012 11:21 AM instead of the expected date from the database.</p>
<h4><strong>The easy workaround…</strong></h4>
<p>… is to mimic the behavior of the currently un-implemented <code>UsesUtcDateTimes</code> property and fool the serializer into thinking all of your dates are <strong>already</strong> in UTC so it doesn’t mess with them. Thanks to partial classes, you can do this.</p>
<p>Create new partial classes for each of your RIA Data Classes that hold <code>DateTime</code> values and override the <code>On(DateTimePropertyName)Changed()</code> methods like the following:</p>
<pre class="brush: csharp; ruler: true; smart-tabs: false;">public partial class MyDataClass
{
    partial void OnDateChanged()
    {
        _Date = DateTime.SpecifyKind(_Date, DateTimeKind.Utc);
    }

    partial void OnOtherDateChanged()
    {
        _OtherDate = DateTime.SpecifyKind(_OtherDate, DateTimeKind.Utc);
    }
}</pre>
<p>(Notice the <code>partial</code> keyword on the methods as well, not just on the class.)</p>
<h4>The technically correct workaround…</h4>
<p>.. is to pass the original time zone, as a property, along with the <a href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time" target="_blank">UTC</a> DateTime across the wire, and then re-apply the time zone to it on the client before using it.</p>
<p>I’m hoping for a future RIA Services release to address this issue better, and perhaps pass the time zone across by itself.</p>
<h4></h4>
<h3><font color="#cc0000"><strong>UPDATE:</strong> This appears to be fixed in the latest release of </font><a href="http://silverlight.net/riaservices/" target="_blank"><font color="#cc0000">WCF RIA Services</font></a><font color="#cc0000">. This workaround is no longer necessary unless your application still uses the older .NET RIA Services. </font></h3>
<h3><font color="#cc0000">I have written a verbose guide on </font><a href="http://www.whycantyoucode.com/2009/11/verbose-steps-to-migrate-a-silverlight-application-from-net-ria-services-july-09-to-wcf-ria-services-pdc-09/" target="_blank"><font color="#cc0000">upgrading an application to WCF RIA Services</font></a><font color="#cc0000">. Check it out </font><a href="http://www.whycantyoucode.com/2009/11/verbose-steps-to-migrate-a-silverlight-application-from-net-ria-services-july-09-to-wcf-ria-services-pdc-09/" target="_blank"><font color="#cc0000">here</font></a><font color="#cc0000">.</font></h3>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/workaround-for-silverlight-ria-services-datetime-discrepancy-between-server-and-client/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Extension method of the day: Inline using() { } block in C#</title>
		<link>http://www.whycantyoucode.com/2009/11/extension-method-of-the-day-inline-using-block-in-c/</link>
		<comments>http://www.whycantyoucode.com/2009/11/extension-method-of-the-day-inline-using-block-in-c/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 11:20:47 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[disposable]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[extension method]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[using]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=113</guid>
		<description><![CDATA[Linq-to-SQL is our ORM of choice until the Entity Framework matures &#8211; and in our projects we use a factory method to get a new reference to our database data context. Here’s what I mean: var db = Database.GetDataContext(); The DataContext class implements IDisposable, which means that (usually) it should be wrapped in an using [...]]]></description>
			<content:encoded><![CDATA[<p>Linq-to-SQL is our <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank"><acronym title="Object-relational mapping">ORM</acronym></a> of choice until the Entity Framework matures &#8211; and in our projects we use a factory method to get a new reference to our database data context. Here’s what I mean:</p>
<pre class="brush: csharp;">var db = Database.GetDataContext();</pre>
<p>
  <br />The DataContext class implements <code>IDisposable</code>, which means that (usually) it should be wrapped in an <code>using</code> block: </p>
<p></p>
<pre class="brush: csharp;">using (var db = Database.GetDataContext())
{
    ... code that uses the database here ...
}</pre>
<p>We discovered that we frequently have one liners inside the <code>using</code> block, and in most of these cases, we just return some quick value from the database. </p>
<p>This made me think if there was something I could do about this to make it into a more compact construct. The result is an extension method that lets me do all of this on one line, while also taking care of object disposal.</p>
<p><strong>Introducing &lt;IDisposable&gt;.Using() extension method:</strong></p>
<pre class="brush: csharp;">int userCount = Database.GetDataContext().Using(db =&gt; db.Users.Count()); // get a quick user count</pre>
<p>
  <br />Of course, this applies to any object implementing <code>IDisposable</code>, not just Linq-to-SQL – so it has lots of possible uses. Here’s another example: </p>
<p></p>
<pre class="brush: csharp;">

foreach (string file in Directory.GetFiles(@&quot;C:\TextFiles&quot;, &quot;*.txt&quot;))
{

    string firstLine = new StreamReader(file).Using(f =&gt; f.ReadLine());
    Console.WriteLine(firstLine);
}
</pre>
<p>We’re reading the first line of every file and making sure the file gets closed immediately afterwards. The extension method takes care of disposing the <code>StreamReader</code>, and allows you to focus on the functionality rather than the implementation.</p>
<p>That’s what functional programming is all about!</p>
<p><strong>Extension method follows:</strong></p>
<pre class="brush: csharp;">public static class DisposableExtensions
{
   /// &lt;summary&gt;
   /// Runs a delegate on the specified &lt;see cref=&quot;IDisposable&quot;/&gt; and returns its value.
   /// &lt;/summary&gt;
   /// &lt;typeparam name=&quot;T&quot;&gt;Type of the object implementing &lt;see cref=&quot;IDisposable&quot;/&gt;&lt;/typeparam&gt;
   /// &lt;typeparam name=&quot;TOut&quot;&gt;The type of the return value.&lt;/typeparam&gt;
   /// &lt;param name=&quot;disposable&quot;&gt;The object implementing &lt;see cref=&quot;IDisposable&quot;/&gt;.&lt;/param&gt;
   /// &lt;param name=&quot;func&quot;&gt;A delegate that takes &lt;paramref name=&quot;disposable&quot;/&gt; as a parameter and returns a value.&lt;/param&gt;
   /// &lt;returns&gt;Value returned by &lt;paramref name=&quot;func&quot;/&gt; delegate.&lt;/returns&gt;
   public static TOut Using&lt;T, TOut&gt;(this T disposable, Func&lt;T, TOut&gt; func) where T : IDisposable
   {
       using (disposable)
       {
           return func(disposable);
       }
   }

   /// &lt;summary&gt;
   /// Runs a delegate on the specified &lt;see cref=&quot;IDisposable&quot;/&gt; and does not return anything.
   /// &lt;/summary&gt;
   /// &lt;typeparam name=&quot;T&quot;&gt;Type of the object implementing &lt;see cref=&quot;IDisposable&quot;/&gt;&lt;/typeparam&gt;
   /// &lt;param name=&quot;disposable&quot;&gt;The object implementing &lt;see cref=&quot;IDisposable&quot;/&gt;.&lt;/param&gt;
   /// &lt;param name=&quot;action&quot;&gt;A delegate that takes &lt;paramref name=&quot;disposable&quot;/&gt; as a parameter.&lt;/param&gt;
   public static void Using&lt;T&gt;(this T disposable, Action&lt;T&gt; action) where T : IDisposable
   {
       using (disposable)
       {
           action(disposable);
       }
   }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/extension-method-of-the-day-inline-using-block-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easiest way to run IE6 on Windows 7 to test your websites.</title>
		<link>http://www.whycantyoucode.com/2009/11/easiest-way-to-run-ie6-on-windows-7-to-test-your-websites/</link>
		<comments>http://www.whycantyoucode.com/2009/11/easiest-way-to-run-ie6-on-windows-7-to-test-your-websites/#comments</comments>
		<pubDate>Sat, 14 Nov 2009 13:19:17 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/2009/11/easiest-way-to-run-ie6-on-windows-7-to-test-your-websites/</guid>
		<description><![CDATA[Although every neuron in my brain is trying to fight me from writing this post, I realized that in our company, the websites we produce are not necessarily for computer literate people. A huge chunk of our visitors still use IE6 and we need to provide them with a decent experience. We do have some [...]]]></description>
			<content:encoded><![CDATA[<p>Although every neuron in my brain is trying to fight me from writing this post, I realized that in our company, the websites we produce are not necessarily for computer literate people. </p>
<p>A huge chunk of our visitors still use IE6 and we need to provide them with a decent experience. We do have some plans to at least show some alert to these users telling them that their browser is outdated and they need to upgrade. A nice script to help us do that would be the one from <a title="http://code.google.com/p/ie6-upgrade-warning/" href="http://code.google.com/p/ie6-upgrade-warning/">http://code.google.com/p/ie6-upgrade-warning/</a>, pictured below:</p>
<p><a href="http://www.whycantyoucode.com/content/uploads/2009/11/image2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.whycantyoucode.com/content/uploads/2009/11/image_thumb2.png" width="791" height="391" /></a> </p>
<p>If, like us, you still need to support IE6, you can use the incredible <a href="http://www.spoon.net/Browsers/" target="_blank">Spoon.net Browser Sandbox</a> to launch IE6, or any other browser straight from their web page, after installing a small plugin. You can then just start any app right from the browser without needing to install it, one click and it just starts right up!</p>
<p>We find this tool invaluable to us as web developers.</p>
<p>Our WordPress theme already complains about IE6 by default, so that’s a step in the right direction. I wouldn’t even have noticed that if it weren’t for Spoon.net.</p>
<p>Here’s a screenshot of Internet Explorer 6 running on Windows 7:</p>
<p><a href="http://www.whycantyoucode.com/content/uploads/2009/11/image3.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.whycantyoucode.com/content/uploads/2009/11/image_thumb3.png" width="950" height="765" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/easiest-way-to-run-ie6-on-windows-7-to-test-your-websites/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Elegant foreach () with an index</title>
		<link>http://www.whycantyoucode.com/2009/11/elegant-foreach-with-an-index/</link>
		<comments>http://www.whycantyoucode.com/2009/11/elegant-foreach-with-an-index/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 14:43:00 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[elegant]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[foreach]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=39</guid>
		<description><![CDATA[I’ve seen various ways of handling the lack of support for an index in the foreach () construct over the years. By far the most used strategy is to declare an index yourself and increment it at the end of every loop iteration. Let me demonstrate: static void Main(string[] args) { var range = Enumerable.Range(0, [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve seen various ways of handling the lack of support for an index in the foreach () construct over the years.</p>
<p>By far the most used strategy is to declare an index yourself and increment it at the end of every loop iteration. Let me demonstrate:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    var range = Enumerable.Range(0, 100);

    int index = 0;
    foreach (int number in range)
    {
        Console.WriteLine(index + &quot; &quot; + number);
        index++;
    }

    // Output:
    // 0 0
    // 1 1
    // 2 2
}</pre>
<p>However, this becomes more of a problem if the code inside your loop conditionally breaks out of the loop, or if you need to use <code>continue;</code> to end the iteration early, requiring you to keep track of all of your exit points.</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    var range = Enumerable.Range(0, 100);

    int index = 0;
    foreach (int number in range)
    {
        if (number &lt; 50) continue; // &lt;- oops, the index will be out of sync now. shouldn't have forgotten to increment it
        Console.WriteLine(index + &quot; &quot; + number);
        index ++;
    }

    // Output:
    // 0 50 (should be 50 50 – remember, this would be the 50th loop iteration, but it was ended early, before the index got a chance to be incremented)
    // 1 51 (should be 51 51)
    // 2 52 (should be 52 52)
}</pre>
<p>You can get rid of these problems with a little known overload for the Linq <a href="http://msdn.microsoft.com/en-us/library/bb534869.aspx" target="_blank">Enumerable.Select()</a> method which will supply the much needed index. <span style="color: #800000">Behold the uglyness:</span></p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    var range = Enumerable.Range(0, 100);

    foreach (var c in range.Select((value, index) =&gt; new { Index = index, Value = value }))
    {
        if (c.Value &lt; 50) continue; // &lt;- the index will still be correct despite the early exit
        Console.WriteLine(c.Index + &quot; &quot; + c.Value);
    }

    // Output:
    // 50 50 (correct)
    // 51 51
    // 52 52
}</pre>
<p><strong><em>Damn code, you scary! (if you don’t want to get ate, see the elegant solution right below the video)</em></strong></p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:072a3fd2-20bd-48c2-badd-fe3f73212267" class="wlWriterEditableSmartContent">
<div><object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/dSBURkKin_8&amp;hl=en"></param><embed src="http://www.youtube.com/v/dSBURkKin_8&amp;hl=en" type="application/x-shockwave-flash" width="425" height="355"></embed></object></div>
</div>
<p>&#160;</p>
<p>Being someone who doesn’t particularly enjoy uglyness, I decided to wrap this into an extension method for <code>IEnumerable&lt;T&gt;</code>, so I can write this beautiful beautiful code below:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    var range = Enumerable.Range(0, 100);

    foreach (var c in range.WithIndex())
    {
        if (c.Index % 2 == 0) continue; // &lt;- the index will still be correct despite the early exit

        Console.WriteLine(c.Index + &quot; &quot; + c.Value);
    }
}</pre>
<p><strong>You want your index to go backwards? </strong>Easy, an overload does all the dirty work, you can specify the value to start at and the step as parameters. The step can even be negative if you want!</p>
<pre class="brush:csharp">foreach (var c in range.WithIndex(range.Count(), –1)) { }</pre>
<p>Here’s the code listing for the extension method, enjoy:</p>
<pre class="brush: csharp;">public static class EnumerableWithIndexExtension
{
    public static IEnumerable&lt;ValueWithIndex&lt;T&gt;&gt; WithIndex&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable)
    {
        return enumerable.Select((value, index) =&gt; new ValueWithIndex&lt;T&gt;(value, index));
    }

    public static IEnumerable&lt;ValueWithIndex&lt;T&gt;&gt; WithIndex&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, int startAt, int step)
    {
        return enumerable.Select((value, index) =&gt; new ValueWithIndex&lt;T&gt;(value, startAt + index * step));
    }

    public class ValueWithIndex&lt;T&gt;
    {
        public int Index { get; private set; }
        public T Value { get; private set; }

        public ValueWithIndex(T value, int index)
        {
            Value = value;
            Index = index;
        }
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/elegant-foreach-with-an-index/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Beware of the Lazy&lt;T&gt; .NET 4.0 type. The closure trap.</title>
		<link>http://www.whycantyoucode.com/2009/11/beware-of-the-lazyt-net-4-0-type-the-closure-trap/</link>
		<comments>http://www.whycantyoucode.com/2009/11/beware-of-the-lazyt-net-4-0-type-the-closure-trap/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 13:42:00 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[.net 4]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[lazy]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=69</guid>
		<description><![CDATA[The System.Lazy&#60;T&#62; type in the new .NET 4.0 framework came to my attention recently. This type is not at all revolutionary. In fact, everyone could have written it themselves in under 10 lines of code going as far back as the .NET 2.0 framework. Some less experienced programmers won’t realize however, that deferring the call [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/dd642331%28VS.100%29.aspx">System.Lazy&lt;T&gt;</a> type in the new .NET 4.0 framework <a href="http://weblogs.asp.net/fredriknormen/archive/2009/11/10/net-4-0-is-to-lazy.aspx">came to my attention</a> recently. This type is not at all revolutionary. In fact, everyone could have written it themselves in under 10 lines of code going as far back as the .NET 2.0 framework.</p>
<p>Some less experienced programmers won’t realize however, that deferring the call to a delegate could have nasty side effects.</p>
<p>Consider the following code snippet:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    List&lt;Lazy&lt;string&gt;&gt; lazyInit = new List&lt;Lazy&lt;string&gt;&gt;();
    for (char letter = 'A'; letter &lt;= 'Z'; letter++)
    {
        var lazy = new Lazy&lt;string&gt;(() =&gt; letter.ToString());
        lazyInit.Add(lazy);
    }
    foreach (var lazy in lazyInit)
    {
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}</pre>
<p>The code is pretty straight forward, but what gets printed here? Would you think it’s the alphabet? You would be very wrong.</p>
<p><a href="http://www.whycantyoucode.com/content/uploads/2009/11/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.whycantyoucode.com/content/uploads/2009/11/image_thumb1.png" width="678" height="375" /></a></p>
<p>The output is exactly<strong> ‘ZZZZZZZZZZZZZZZZZZZZZZZZZ’</strong>. Go ahead, run it yourself if you don’t trust me.</p>
<p>To understand why this happens, you need to understand how closures work.</p>
<p>In the constructor to the Lazy&lt;&gt; class, you’re passing in a delegate, in the form of a lambda. This delegate captures the <strong>letter</strong> variable (attention, <span style="text-decoration: underline">not its value at the time of the call, but the variable as a whole</span>) and creates a<strong> closure</strong> class around it behind the scenes. This may be counter-intuitive to the average programmer.&#160; For further information on what happens behind the scenes with captured variables and closures, <a href="http://marcgravell.blogspot.com/2009/08/using-reflector-to-understand-anonymous.html">read this great post by Marc Gravell</a>.</p>
<p>This is not specific behavior of the new Lazy&lt;T&gt; class, it’s what happens every time a delegate is stored for <strong>deferred</strong> execution.</p>
<p>If you rewrite the code without deferred execution, you’ll see that the problem doesn’t manifest itself:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    for (char letter = 'A'; letter &lt;= 'Z'; letter++)
    {
        var lazy = new Lazy&lt;string&gt;(() =&gt; letter.ToString());
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}
// Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ</pre>
<p>Same delegate is being used, but it is executed <strong>immediately</strong>. The output is now the complete English alphabet, as you would expect.</p>
<p>This isn’t very useful however, We’ve completely thrown away the advantages of the Lazy&lt;T&gt; class and we might as well not be using it.</p>
<p>So, how can we fix it? We need to use an intermediary variable inside the body of the<strong> for</strong> loop that is simply a copy of the outer variable. The inner variable’s scope is unique to each loop iteration, so it matters a whole lot where you define your variables.</p>
<p>Fixed code:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    List&lt;Lazy&lt;string&gt;&gt; lazyInit = new List&lt;Lazy&lt;string&gt;&gt;();

    // char letter2; // &lt;- for the sake of exercise, uncomment this line and remove the ‘char’ keyword from the initialization of the letter2 variable inside the for loop below. the ‘bug’ will manifest itself again
    for (char letter = 'A'; letter &lt;= 'Z'; letter++)
    {
        char letter2 = letter; // value re-captured in inner block (remove ‘char’ keyword and uncomment line above to see the ‘bug’ manifest itself again)
        var lazy = new Lazy&lt;string&gt;(() =&gt; letter2.ToString());
        lazyInit.Add(lazy);
    }
    foreach (var lazy in lazyInit)
    {
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}</pre>
<p>One tool that can automatically check for this condition so you can avoid headaches later is <a href="http://www.jetbrains.com/resharper/">JetBrain’s Resharper</a>. With <em>Resharper</em> installed, you’d see a warning underneath () =&gt; <span style="text-decoration: underline">letter.ToString()</span> which spells <strong>‘Access to modified closure’</strong> and suggests the same fix I described in this blog post.</p>
<p>If anyone’s interested in seeing how the same Lazy&lt;T&gt; class could be implemented in .NET 2.0 and up, leave a comment and I’ll post it here!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/beware-of-the-lazyt-net-4-0-type-the-closure-trap/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Introduction</title>
		<link>http://www.whycantyoucode.com/2009/11/introduction/</link>
		<comments>http://www.whycantyoucode.com/2009/11/introduction/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 13:39:16 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[Misc]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/2009/11/introduction/</guid>
		<description><![CDATA[Welcome to our blog. *yawn* Please head over to the About page to see more about what this blog is about. This post is not too exciting, but the About page is! So head over there now! Do it! Come on, Do it! Do it!]]></description>
			<content:encoded><![CDATA[<p>Welcome to our blog. *yawn*</p>
<p>Please head over to the <a href="http://www.whycantyoucode.com/about/">About</a> page to see more about what this blog is about.</p>
<p>This post is not too exciting, but the <a href="http://www.whycantyoucode.com/about/">About</a> page is! So head over there now!</p>
<p>Do it! </p>
<p>Come on, Do it! </p>
<p>Do it!</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:0e321a57-c0e2-49e3-ab81-9bafc0977a66" class="wlWriterEditableSmartContent">
<div><object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/lmUZGdi7Ty4&amp;hl=en"></param><embed src="http://www.youtube.com/v/lmUZGdi7Ty4&amp;hl=en" type="application/x-shockwave-flash" width="425" height="355"></embed></object></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

