<?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? &#187; C#</title>
	<atom:link href="http://www.whycantyoucode.com/tag/c/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>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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 needed [...]]]></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>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 to [...]]]></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>1</slash:comments>
		</item>
	</channel>
</rss>
