<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" version="2.0">

<channel>
	<title>YTechie - C#, ASP.NET, and Adobe Flex Blog</title>
	
	<link>http://www.ytechie.com</link>
	<description>Productive software development using ASP.NET, C#, and Adobe Flex</description>
	<lastBuildDate>Thu, 28 Oct 2010 05:10:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Ytechie" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="ytechie" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">Ytechie</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FYtechie" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FYtechie" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2FYtechie" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.bloglines.com/sub/http://feeds.feedburner.com/Ytechie" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FYtechie" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FYtechie" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FYtechie" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><item>
		<title>Why I Would no Longer Choose Silverlight</title>
		<link>http://www.ytechie.com/2010/10/why-i-would-no-longer-choose-silverlight.html</link>
		<comments>http://www.ytechie.com/2010/10/why-i-would-no-longer-choose-silverlight.html#comments</comments>
		<pubDate>Thu, 28 Oct 2010 05:10:19 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2010/10/why-i-would-no-longer-choose-silverlight.html</guid>
		<description><![CDATA[I recently spoke to some of the wonderful guys on the ASP.NET team over at Microsoft (@shanselman @haacked and others). Somebody asked if anyone had any complaints they wanted to share. I brought up the topic of Silverlight since it’s been on my mind recently. I would like to make it clear that the product [...]]]></description>
			<content:encoded><![CDATA[<p>I recently spoke to some of the wonderful guys on the ASP.NET team over at Microsoft (@<a href="http://twitter.com/shanselman" onclick="pageTracker._trackPageview('/outgoing/twitter.com/shanselman?referer=');">shanselman</a> @<a href="http://twitter.com/haacked" onclick="pageTracker._trackPageview('/outgoing/twitter.com/haacked?referer=');">haacked</a> and others). Somebody asked if anyone had any complaints they wanted to share. I brought up the topic of Silverlight since it’s been on my mind recently.</p>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.webmonkey.com/wp-content/uploads/2010/09/Microsoft_Silverlight.jpg" width="143" height="159" /></p>
<p>I would like to make it clear that the product we built with it is still amazing, and Silverlight has a lot to do with that. Silverlight is a solid product that has reflected the amount of effort that the developers put into it.</p>
<p>When I was originally confronted with the decision of building our user interface in Silverlight or HTML, I chose Silverlight for the following reasons:</p>
<ul>
<li>It’s the cool thing to do </li>
<li>Perceived fast development </li>
<li>User interface performance without having to touch “icky” JavaScript </li>
</ul>
<p>Now that the first commercially available version of our software is available, I can’t help but admit some regret with the choice to use Silverlight.</p>
<p>The bottom line for me comes down to the fact that HTML runs <strong>everywhere</strong>, and Silverlight runs <strong>some</strong> places.</p>
<p>It’s becoming abundantly clear that the future of computing is in a wide variety of form factors, and they’re getting smaller. iPads, tablets/slates, iPhones, Android Phones, Microsoft phones, etc. are all widely available. Even Microsoft&#8217;s own Windows CE devices don’t support the Silverlight we know and love. These new types of mobile devices are showing us that the future it not just staring at a 19” screen. Our own Silverlight front-end is not only un-optimized for these devices, but worse yet, it doesn’t work, period.</p>
<p>So is the HTML story better? I believe it is. Let’s examine my original reasons for going to Silverlight:</p>
<ul>
<li><strong>It’s the cool thing to do </strong>– I believe this gap is closing. jQuery and other animation and scripting tools are making cross platform development reliable and easy to develop. The proliferation of web standards has been helpful as well.</li>
<li><strong>Perceived fast development</strong> – My mistake here was thinking that since we didn’t have to deal with HTML, CSS, and JavaScript issues, we would be able to develop much quicker. The reality is that the time we would have spent on those issues is now spent dealing with another layer of misdirection. We now have to get the data from our database to the web server, but then we have to get it to the client. This is all while managing the subtleties of RIA services and LINQ to SQL objects. ASP.NET MVC removes one layer of mapping and complexity (we can <em>optionally</em> add layers obviously).
<p>On notable exception to this is our scheduling interface. We’re using the wonderful <a href="http://demos.telerik.com/silverlight/#Scheduler/FirstLook" onclick="pageTracker._trackPageview('/outgoing/demos.telerik.com/silverlight/_Scheduler/FirstLook?referer=');">Telerik scheduler</a>, which really shows when Silverlight can shine compared to an equivalent HTML page.</p>
</li>
<li>
<p><strong>User interface performance</strong> – Silverlight wins this one. We’re doing some amazing things with layout transforms that really wows our customers. The easy animations will be about the same amount of work in JavaScript, but the more complex animations will likely be easier in Silverlight. </p>
</li>
</ul>
<p>Most of my reasons make common scenarios a wash (or possibly in favor of Silverlight). However, there are reasons that I’m avoiding Silverlight going forward:</p>
<ul>
<li><strong>It doesn’t run well on Linux, CE, iPad, etc</strong> – This is huge. Unless you have a captive audience, you’ll want to make sure that your application runs on the newest devices. HTML is the only sure bet. </li>
<li><strong>Memory leaks/issues</strong> – This one really irks me. I’m sure that there are issues in our code that cause some leaks, and I’m sure some can be attributed to this <a href="http://forums.silverlight.net/forums/t/171739.aspx" onclick="pageTracker._trackPageview('/outgoing/forums.silverlight.net/forums/t/171739.aspx?referer=');">seemly unsolvable issue</a>. We have a screen that stays open on a touchscreen, and it consumes all the memory on the machine within half a day. The bottom line is that these simply don’t happen in HTML.</li>
<li><strong>Initial load hit</strong> – I know there are ways to mitigate this in Silverlight by spreading your application over multiple XAP files. However, HTML is the better choice for slow connections. The slow speed is spread throughout the screens, instead of switching between fast and slow.</li>
</ul>
<p>In conclusion, all of the amazing reasons that I went with Silverlight have faded, and now I’m left with the reality of a platform that will never achieve 100% accessibility. There are plenty of situations where Silverlight may be the perfect fit, but next time I wont be as quick to lean toward Silverlight without serious consideration as to the potential audience and goals.</p>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/9PLGecdzE44" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2010/10/why-i-would-no-longer-choose-silverlight.html/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Introduction to Distributed Source Control</title>
		<link>http://www.ytechie.com/2009/11/introduction-to-distributed-source-control.html</link>
		<comments>http://www.ytechie.com/2009/11/introduction-to-distributed-source-control.html#comments</comments>
		<pubDate>Fri, 06 Nov 2009 21:16:21 +0000</pubDate>
		<dc:creator>Jason Young</dc:creator>
				<category><![CDATA[software]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/11/introduction-to-distributed-source-control.html</guid>
		<description><![CDATA[Version control systems manage the changes of documents. In software development, their primary purpose is to store the source code for an application, as well as every revision created during its development. Currently, many developers use a centralized version control system such as Visual Studio Team System (VSTS) or Subversion. With such systems there is [...]]]></description>
			<content:encoded><![CDATA[<p>Version control systems manage the changes of documents. In software development, their primary purpose is to store the source code for an application, as well as every revision created during its development.</p>
<p>Currently, many developers use a centralized version control system such as Visual Studio Team System (VSTS) or Subversion. With such systems there is a central repository (i.e., Team Foundation Server (TFS)), usually located remotely, that houses the different versions of source code.</p>
<p align="center"><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.ytechie.com/post-images/2009/11/image.png" width="365" height="314" /> </p>
<p>Unfortunately, a number of issues accompany typical source control systems that are based on a centralized repository, including, but not limited to the following:</p>
<ul>
<li>Many operations such as checking code in or out can perform poorly over slow connections. </li>
<li>Working offline results in a reduced set of functionality, such as branching or committing multiple features or bug fixes. </li>
<li>Moving the repository can be difficult due to the fact that there is front-end <b>and</b> back-end management. </li>
<li>Working between networks that may never become bridged is impossible or difficult, since a connection must be made to the central repository. </li>
<li>Private work is typically not under source control. </li>
<li>There is often a single point of failure. </li>
<li>Security must be managed, and may become complex due to multiple permission sets and projects. </li>
</ul>
<p>Distributed source control systems (or distributed version control systems, &quot;DVCS&quot; for short) are starting to gain popularity because they offer many advantages over the traditional, centralized repository.</p>
<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.ytechie.com/post-images/2009/11/image1.png" width="498" height="282" /> </p>
<p>They allow users to work independently in either a connected or disconnected environment. There is a tremendous amount of flexibility in regards to merging, managing different branches of development, and managing product features. </p>
<p>Adopters of this technology include Google Code and Sourceforge. Moreover, many major projects such as GNOME, Perl, MySQL, Python, and Ubuntu are also using a distributed source control system.</p>
<p>You may have already heard about some of the popular implementations. Git, Mercurial, and Bazaar are a few choices that have started to become mainstream. If you&#8217;ve worked with Subversion, you&#8217;ll find that migrating to this new generation of source control systems doesn&#8217;t mean giving up the features that you&#8217;re used to.</p>
<p>There are many problems with centralized repositories that simply disappear when you&#8217;re working with a distributed system:</p>
<ul>
<li>Merging is a core feature and works <i>how</i> and <i>when</i> you want. </li>
<li>Security is trivial since everyone works in their own sandbox. You simply choose who you allow pushing and pulling changes to and from. In open source projects, this typically means allowing certain trusted individuals to push changes to the project repositories. When needed, additional security models such as authentication can be imposed. </li>
<li>Working disconnected doesn&#8217;t require any preparation. You are working offline by default. The only online operation is synchronizing with other repositories. </li>
<li>All operations are near-instantaneous. Synchronizing is the only operation that is dependent on the speed of your connection. </li>
</ul>
<p>&#160;</p>
<p> <b>What is a Distributed Source Control System?</b>
<p>Distributed source control systems have the same purpose, but work much differently than systems like Team Foundation Server (TFS), SourceSafe, Subversion, and CVS. Instead of having a single repository that contains the source code and history, there are many repositories that have the source code, and some or all of its revision history. One or more peers have repositories for a project, and synchronize what they want, when they want to. There are really no requirements or restrictions. The focus is on synchronizing and working independently.</p>
<p><strong>Workflow</strong></p>
<p style="border-bottom: black 2px solid; border-left: black 2px solid; padding-bottom: 4px; background-color: #ffffcc; margin: 5px; padding-left: 4px; padding-right: 4px; border-top: black 2px solid; border-right: black 2px solid; padding-top: 4px">Examples &amp; screenshots included here are from Mercurial using the TortoiseHg explorer extension. Git has similar functionality using TortoiseGit. You can also use the command line for all/some operations if you prefer.</p>
<p>1. <b>Clone a repository</b> &#8211; To create your own local repository, you have to clone (copy) all or part of an existing repository. Since each developer has a copy of the repository, you can clone it from anyone.</p>
<p align="center"><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.ytechie.com/post-images/2009/11/image2.png" width="350" height="427" /> </p>
<p>2. <b>Create a &quot;working copy&quot; of the code</b> &#8211; Even though you have the full repository from another developer, you still need to &quot;check-out&quot; or get the latest version of the code. Since the repository is local, this operation is quick and can be done <b>offline</b>.</p>
<p>3. <b>Make changes</b> &#8211; Simply make any changes you like, without concerning yourself about how your source control works. This is similar to Subversion, and contrasts sharply with TFS which needs to track any changes you make by interfacing with Visual Studio.</p>
<p>4. <b>Check-in changes</b> &#8211; When it&#8217;s time to check in your local changes, they are simply committed to your local repository. They <b>do not affect any other repository</b>. Changes are detected by comparing the newest committed revision with the current version on disk.</p>
<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.ytechie.com/post-images/2009/11/image3.png" width="494" height="216" /> </p>
<p>5. <b>Push or pull changesets</b> &#8211; To actually send your changesets to another repository, you need to &quot;push&quot; or &quot;pull&quot; them. In the Mercurial dialog below, there are options labeled &quot;Incoming&quot; and &quot;Outgoing&quot; which simply compare the local changes with the remote changes and determine what will get pushed or pulled. The &quot;Push&quot; and &quot;Pull&quot; operations send your changesets to another repository, or pull changesets from another repository respectively.</p>
<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.ytechie.com/post-images/2009/11/image4.png" width="480" height="264" /> </p>
<p>When changesets are transferred between repositories, they <b>do not affect any working copies</b>. This flexibility allows changes to be synchronized without affecting work in progress.</p>
<p><b>Online/Offline Operations</b> </p>
<p>
<table style="border-collapse: collapse" border="2" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top" width="143">
<p><b>Operation</b></p>
</td>
<td valign="top" width="167">
<p><b>TFS</b></p>
</td>
<td valign="top" width="166">
<p><b>Subversion</b></p>
</td>
<td valign="top" width="163">
<p><b>Mercurial/GIT/Bazaar</b></p>
</td>
</tr>
<tr>
<td valign="top" width="143">
<p><b>Get/Update</b></p>
</td>
<td style="background-color: red" valign="top" width="167">
<p>Online</p>
</td>
<td style="background-color: red" valign="top" width="166">
<p>Online</p>
</td>
<td style="background-color: green" valign="top" width="163">
<p>Offline</p>
</td>
</tr>
<tr>
<td style="background-color: red" valign="top" width="143">
<p><b>Check-out</b></p>
</td>
<td style="background-color: red" valign="top" width="167">
<p>Online</p>
</td>
<td style="background-color: red" valign="top" width="166">
<p>Online</p>
</td>
<td style="background-color: green" valign="top" width="163">
<p>Offline</p>
</td>
</tr>
<tr>
<td valign="top" width="143">
<p><b>Check-in</b></p>
</td>
<td style="background-color: red" valign="top" width="167">
<p>Online</p>
</td>
<td style="background-color: red" valign="top" width="166">
<p>Online</p>
</td>
<td style="background-color: green" valign="top" width="163">
<p>Offline</p>
</td>
</tr>
<tr>
<td valign="top" width="143">
<p><b>View History</b></p>
</td>
<td style="background-color: red" valign="top" width="167">
<p>Online</p>
</td>
<td style="background-color: red" valign="top" width="166">
<p>Online</p>
</td>
<td style="background-color: green" valign="top" width="163">
<p>Offline</p>
</td>
</tr>
<tr>
<td valign="top" width="143">
<p><b>Revert</b></p>
</td>
<td style="background-color: red" valign="top" width="167">
<p>N/A</p>
</td>
<td style="background-color: green" valign="top" width="166">
<p>Offline</p>
</td>
<td style="background-color: green" valign="top" width="163">
<p>Offline</p>
</td>
</tr>
<tr>
<td valign="top" width="143">
<p><b>Compare working changes</b></p>
</td>
<td style="background-color: red" valign="top" width="167">
<p>Online</p>
</td>
<td style="background-color: green" valign="top" width="166">
<p>Offline</p>
</td>
<td style="background-color: green" valign="top" width="163">
<p>Offline</p>
</td>
</tr>
<tr>
<td valign="top" width="143">
<p><b>Change tracking</b></p>
</td>
<td style="background-color: yellow" valign="top" width="167">
<p>Limited*</p>
</td>
<td style="background-color: green" valign="top" width="166">
<p>Offline</p>
</td>
<td style="background-color: green" valign="top" width="163">
<p>Offline</p>
</td>
</tr>
</tbody>
</table>
<p>* Changes can be made in a special &quot;offline&quot; mode, and edited files will be checked-out when returning to &quot;online&quot; mode.</p>
<p> <b>Merging Divergent Development Branches</b>
<p>In traditional, centralized source control systems, the only way for a divergence in code paths was to explicitly create a branch. While this is still possible in a distributed source control system, it is also possible for multiple developers to make independent changes that may or may not conflict.</p>
<p>The beauty of the system is that divergent code paths can be merged at any time. It is possible for the developers to make multiple changes, perform multiple synchronizations (pulls), yet not have to merge until they want to, or until they need to push their changes to another repository.</p>
<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.ytechie.com/post-images/2009/11/image5.png" width="488" height="179" /> </p>
<p><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.ytechie.com/post-images/2009/11/image6.png" width="496" height="279" /> </p>
<p> <b>Where Is My Repository?</b>
<p>If you&#8217;re working with a team of 20 developers, and each one has a full copy of the repository, you don&#8217;t <b><i>need</i></b> a central repository. However, there are a few reasons why it is recommended:</p>
<ol>
<li><b>Central backup location</b> &#8211; Even though you have numerous copies of the repository, it is still useful to have a single location that can be used as a place where an automated backup process is able to find it. </li>
<li><b>Central communication hub</b> &#8211; The logistics of pushing and pulling code between a number of developers can get complicated. Distributing your repository simplifies many of these problems, but is not perfect by itself. Having a central &quot;authoritative&quot; repository can make it quick and easy for developers to collaborate. </li>
<li><b>Central location for builds</b> &#8211; Automated builds and continuous integration servers need a location to pull source code from, which an authoritative repository provides. </li>
<li><b>Central merge location</b> &#8211; If multiple developers are pulling changes from one another, implicit branches can be created. A central repository serves as location where all of these branches are merged into one development line. </li>
</ol>
<p>Repositories can typically be easily hosted internally using Apache, a built in daemon, CGI script, or simply just a file share. For simplicity, there are many services that provide repository hosting. For Git, there is GitHub and SourceForge. For Mercurial, there is BitBucket, Google Code, and SourceForge.</p>
<p>The beauty of distributed source control is apparent when you take into account the administrative overhead of a central server. Since the central server is no different than any other peer, <b>it can be easily moved or modified</b>. For example, you can start out with no central server, then you can use BitBucket to store your revisions, then you can move to another service within minutes. Changing providers simply means pushing your changes to another server.</p>
<p> <b><u>Common Operations</u></b>
<p><strong>Importing Existing Code</strong></p>
<p>Importing existing code is an extremely simple operation. If it is new code that is not yet under source control, you can simply create a new repository within the folder that contains your code. You can then check in your code as desired.</p>
<p style="border-bottom: black 2px solid; border-left: black 2px solid; padding-bottom: 4px; background-color: #ffffcc; margin: 5px; padding-left: 4px; padding-right: 4px; border-top: black 2px solid; border-right: black 2px solid; padding-top: 4px">In Subversion, the import process involved importing the code into the repository, and then checking out a working copy. Mercurial does not have this complexity.</p>
<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.ytechie.com/post-images/2009/11/image7.png" width="407" height="300" /> </p>
<p>Mercurial also comes with built in support for converting existing Subversion repositories to Mercurial repositories, including the entire revision history. <a href="http://www.selenic.com/mercurial/wiki/ConvertExtension" onclick="pageTracker._trackPageview('/outgoing/www.selenic.com/mercurial/wiki/ConvertExtension?referer=');">More information is available here</a>.</p>
<p style="border-bottom: black 2px solid; border-left: black 2px solid; padding-bottom: 4px; background-color: #ffffcc; margin: 5px; padding-left: 4px; padding-right: 4px; border-top: black 2px solid; border-right: black 2px solid; padding-top: 4px">To convert from an older source control system such as Visual Source Safe, you can first <a href="http://www.pumacode.org/projects/vss2svn" onclick="pageTracker._trackPageview('/outgoing/www.pumacode.org/projects/vss2svn?referer=');">convert the repository to Subversion</a>, and then to Mercurial.</p>
<p> <b>&#160;</b> <b>Checking-in Code</b>
<p>It is worth mentioning a typical philosophical difference between how some source control systems promote the check-in process for changes. Systems like TFS and Visual Source Safe only provide <a href="http://msdn.microsoft.com/en-us/library/ms194956(VS.80).aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/ms194956_VS.80_.aspx?referer=');"><b>limited functionality for reverting</b></a> and re-applying specific changesets. For this reason, developers tend to check-in groups of unrelated changes. This tends to lead to less useful generic or incomplete comments such as &quot;done for the day&quot;.</p>
<p>Flexible source control systems such as Subversion, Mercurial, and Git provide a lot more value when changesets are fine-grained, and represent a single change to the system. For example, renaming a page and changing the tab order are two changes that should be checked-in separately. If needed, either feature can be pulled in or out, moved, synchronized, or used to patch other versions. It also reduces the likelihood of conflicts, and typically makes conflict resolution easier. Other developers can quickly scan through the changelog and get a clear list of the features that were added, or bugs that were fixed. In an ideal world, all commits should be tied to a bug or feature to increase traceability.</p>
<p> <b>Managing Branches &amp; Releases</b>
<p>It is simple to create <b>explicit branches</b> that allow you to maintain parallel development of different features or versions. Branching simply involves entering a branch name when you commit your code. Switching between branches is as easy as performing an update to the latest revision of a branch. In contrast, TFS requires a branch to be created before you can commit changes to it. TFS also keeps a copy of each branch on the developers machine, which is optional with Subversion, Mercurial, and others.</p>
<p>Since changes can be made independently, there is also a concept of <b>implicit branching</b>. If we have two users, Ann and Bob, they are free to make changes independently of each other. If Ann checks in her changes, and then Bob pulls down those changes while having changes of his own, there are now two implicit branches of development. In this case <b>pulling</b> changes will automatically create multiple parallel lines of development. Changes cannot be <b>pushed</b> unless the code has been merged. The system is designed this way so that merging is only necessary when pushing, typically to a central repository or build server. The effect is that repositories that are only &quot;pushed to&quot; can be easily and cleanly maintained remotely.</p>
<p>Most distributed source control systems include tools that allow a visual display of code branches. This functionality is also likely to be included in Team Foundation Server 2010.</p>
<p> <b>Tagging Revisions</b>
<p>In order to mark the significance of certain revisions, they can be tagged with a specific label. For example, when you release a specific version of your project, you can tag that revision with the label &quot;v1.2&quot; as seen below. Additional flexibility is provided by the &quot;local tag&quot; functionality, which lets you tag code on your computer without sharing the tag with others.</p>
<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.ytechie.com/post-images/2009/11/image8.png" width="381" height="296" /> </p>
<p> <b>Terminology</b>
<p><b>Distributed Version Control System (DVCS)</b> &#8211; Version control systems manage the changes of documents. In software development, their primary purpose is to store the source code for an application, as well as every revision created during its development.</p>
<p><b>Repository</b> &#8211; A container for a set of changes that represent the history of the source code for a project. A repository may have the ability to store a partial history of the project, or the entire history. The repository is typically optimized by using compression and by only storing deltas or changes of files.</p>
<p><b>Changeset/Revision</b> &#8211; A particular &quot;delta&quot; or change in the codebase. This can include any type of change, in any number of files. Visual Source Safe stored revision numbers for each file. Team Foundation Server and Subversion have global revision numbers for the entire repository. Distributed source control systems often use GUID&#8217;s or hash codes to represent specific revisions.<b></b></p>
<p><b>Working copy</b> &#8211; A particular revision of the code that has been extracted or checked out from the repository. This revision includes the full version of all the files involved so that the developer can load and make changes to the code.</p>
<p><b>Bundle</b> &#8211; A bundle is a file that contains a set of changes that is intended to be sent to another user to update their repository. This technology allows users to be physically disconnected yet pass code changes to each other. This file typically employs some form of compression to minimize file size.</p>
<p><b>Patch/diff</b> &#8211; A patch is a file that shows the changes between two versions of a file or multiple files. It contains enough information to transform the old version into the new version, or vice-versa. It&#8217;s a quick way of sending someone a changeset. Patches are usually in the &quot;unified diff&quot; format, which looks like the following:</p>
<pre style="border-bottom: black 2px solid; border-left: black 2px solid; padding-bottom: 4px; background-color: lightgrey; margin: 5px; padding-left: 4px; padding-right: 4px; border-top: black 2px solid; border-right: black 2px solid; padding-top: 4px">--- /path/to/original timestamp
+++ /path/to/new      timestamp
@@ -1,3 +1,9 @@
+This is an important
+notice! It should
+therefore be located at
+the beginning of this
+document!
+
 This part of the
 document has stayed the
 same from version to
@@ -5,16 +11,10 @@
 be shown if it doesn't
 change.  Otherwise, that
 would not be helping to
-compress the size of the
-changes.
-
-This paragraph contains
-text that is outdated.
-It will be deleted in the -near future.
+compress anything. 

 It is important to spell
-check this dokument. On
+check this document. On
 the other hand, a
 misspelled word isn't
 the end of the world.
@@ -22,3 +22,7 @@
 this paragraph needs to
 be changed. Things can
 be added after it.
+
+This paragraph contains
+important new additions
+to this document. </pre>
<h4>&#160;</h4>
<h4>References</h4>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms194956(VS.80).aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/ms194956_VS.80_.aspx?referer=');">http://msdn.microsoft.com/en-us/library/ms194956(VS.80).aspx</a> </li>
<li><a href="http://www.pumacode.org/projects/vss2svn" onclick="pageTracker._trackPageview('/outgoing/www.pumacode.org/projects/vss2svn?referer=');">http://www.pumacode.org/projects/vss2svn</a> </li>
<li><a href="http://www.selenic.com/mercurial/wiki/PublishingRepositories" onclick="pageTracker._trackPageview('/outgoing/www.selenic.com/mercurial/wiki/PublishingRepositories?referer=');">http://www.selenic.com/mercurial/wiki/PublishingRepositories</a> </li>
<li><a href="http://betterexplained.com/articles/intro-to-distributed-version-control-illustrated/" onclick="pageTracker._trackPageview('/outgoing/betterexplained.com/articles/intro-to-distributed-version-control-illustrated/?referer=');">http://betterexplained.com/articles/intro-to-distributed-version-control-illustrated/</a> </li>
<li><a href="http://code.google.com/p/tortoisegit/" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/tortoisegit/?referer=');">http://code.google.com/p/tortoisegit/</a> </li>
<li><a href="http://bitbucket.org/tortoisehg/stable/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tortoisehg/stable/wiki/Home?referer=');">http://bitbucket.org/tortoisehg/stable/wiki/Home</a> </li>
<li><a href="http://msmvps.com/blogs/vstsblog/archive/2008/08/17/how-microsoft-uses-team-foundation-server-internally.aspx" onclick="pageTracker._trackPageview('/outgoing/msmvps.com/blogs/vstsblog/archive/2008/08/17/how-microsoft-uses-team-foundation-server-internally.aspx?referer=');">http://msmvps.com/blogs/vstsblog/archive/2008/08/17/how-microsoft-uses-team-foundation-server-internally.aspx</a> </li>
<li><a href="http://blogs.msdn.com/bharry/archive/2007/09/15/update-on-microsoft-tfs-adoption.aspx" onclick="pageTracker._trackPageview('/outgoing/blogs.msdn.com/bharry/archive/2007/09/15/update-on-microsoft-tfs-adoption.aspx?referer=');">http://blogs.msdn.com/bharry/archive/2007/09/15/update-on-microsoft-tfs-adoption.aspx</a> </li>
<li><a href="http://blogs.msdn.com/bharry/archive/2008/09/15/september-08-devdiv-tfs-dogfood-statistics.aspx" onclick="pageTracker._trackPageview('/outgoing/blogs.msdn.com/bharry/archive/2008/09/15/september-08-devdiv-tfs-dogfood-statistics.aspx?referer=');">http://blogs.msdn.com/bharry/archive/2008/09/15/september-08-devdiv-tfs-dogfood-statistics.aspx</a> </li>
</ul>
<p><b>Recommended Reading</b> </p>
<ul>
<li><a href="http://betterexplained.com/articles/intro-to-distributed-version-control-illustrated/" onclick="pageTracker._trackPageview('/outgoing/betterexplained.com/articles/intro-to-distributed-version-control-illustrated/?referer=');">Illustrated introduction to distributed version control</a> </li>
<li><a href="http://www.selenic.com/mercurial/wiki/QuickStart" onclick="pageTracker._trackPageview('/outgoing/www.selenic.com/mercurial/wiki/QuickStart?referer=');">Mercurial QuickStart</a> </li>
<li><a href="http://hgbook.red-bean.com/read/" onclick="pageTracker._trackPageview('/outgoing/hgbook.red-bean.com/read/?referer=');">Mercurial: The Definitive Guide</a> </li>
<li><a href="http://bitbucket.org/tortoisehg/stable/wiki/install" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tortoisehg/stable/wiki/install?referer=');">TortoiseHg Download</a> </li>
<li><a href="http://code.google.com/p/support/wiki/DVCSAnalysis" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/support/wiki/DVCSAnalysis?referer=');">Google&#8217;s Analysis of Git vs Mercurial</a> </li>
</ul>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/mAONX0bI_XA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/11/introduction-to-distributed-source-control.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Speeding up data access by using Linq to SQL or EF</title>
		<link>http://www.ytechie.com/2009/10/speeding-up-data-access-by-using-linq-to-sql-or-ef.html</link>
		<comments>http://www.ytechie.com/2009/10/speeding-up-data-access-by-using-linq-to-sql-or-ef.html#comments</comments>
		<pubDate>Mon, 26 Oct 2009 20:53:53 +0000</pubDate>
		<dc:creator>Jason Young</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/10/speeding-up-data-access-by-using-linq-to-sql-or-ef.html</guid>
		<description><![CDATA[Recall that LINQ based object relational mappers (ORM) use expression trees to effectively translate your C# (or other language) LINQ code into SQL. Many DBA’s and developers that don’t fully understand this technology are often quick to discredit it. I’m going to show how significant performance, simplicity, and clarity can be gained by using Linq [...]]]></description>
			<content:encoded><![CDATA[<p>Recall that LINQ based object relational mappers (ORM) use expression trees to effectively translate your C# (or other language) LINQ code into SQL. Many DBA’s and developers that don’t fully understand this technology are often quick to discredit it. I’m going to show how significant performance, simplicity, and clarity can be gained by using Linq to SQL.</p>
<p>A recent DBA asked me the question “I thought inline SQL was bad, so why are we using it again?” LINQ may *smell* like inline SQL, but it is not. Let’s first take a look at some simple LINQ that is easy to read: </p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:0511d0cf-0c6f-4895-961f-7ab27960207d" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">from d in Devices
where d.CZone == 4
&amp;&amp; d.Type == "X"
select d.Id</pre>
</div>
<p>So how is this different than inline SQL? To be technical, you’re writing a query against a data model, with full intellisense. You’re also writing a provider agnostic query. This same query can be performed against SQL Server, Oracle, or even the Facebook API if there was a supporting framework in place. We now have a truly unified query architecture.</p>
<p>Let’s keep taking about this simple LINQ query, and see how you would write it if you didn’t want to use LINQ. Most developers before the days of LINQ would probably use a stored procedure. Stored procedures are great. They’re efficient, reusable, and easily updatable. Here is what it may look like:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:4e3748fa-09f3-42ae-9b35-05ea2bc23f29" class="wlWriterEditableSmartContent">
<pre name="code" class="sql">Create Procedure GetMyStuff
As
Select Id
From Devices
Where CZone = 4
And Type = 'X'
Select Id
GO</pre>
</div>
<p>A nice, simple SQL query. There are a few disadvantages that may not be immediately apparent:</p>
<ul>
<li>If you need a second, similar query, you have to either have to create and maintain two stored procedures. As an alternative, you could modify the stored procedure to operate differently based on a parameter. Both of these options are not idea, but LINQ does give us an alternative that I’ll discuss in a bit. </li>
<li>You don’t get intellisense when you’re writing your code. </li>
<li>You have to be concerned with two different “programming” paradigms, and also have to manually manage the translation in both directions. </li>
</ul>
<p>Now, let’s take our example to the other end of the spectrum, which will help show where LINQ can really shine where straight SQL does not. This example is a query for a search page. I set up a simple ASPX page to demonstrate. Here is a sample of the user interface:</p>
<p><a href="http://www.ytechie.com/post-images/2009/10/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.ytechie.com/post-images/2009/10/image_thumb.png" width="477" height="211" /></a> </p>
<p>The user enters a number of search criteria, and the results are displayed. I literally coded this in under 5 minutes. If you’re used to using stored procedures to retrieve this type of data, think about how you would go about creating this. You have a couple of options that I’m aware of:</p>
<ul>
<li>Write a separate stored procedure for every combination of parameters. In this case that would be 7 stored procedures. This would certainly not be ideal. </li>
<li>Write a single stored procedure that can handle each parameter as nullable parameters, and use “Where @Param Is Null Or Param = @Param”. This option is easy, but has some potential performance implications. </li>
<li>Write a single stored procedure that can handle each parameter as nullable parameter, and “If” statements to handle each scenario. This would be time consuming an error prone. </li>
</ul>
<p>In LINQ, we’re able to <strong>dynamically build up a query</strong>. For the search example, my LINQ looks like this:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:3f959401-5933-40c2-9b78-fdfdf1f457d9" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var dataContext = new DataClassesDataContext();

var query = (IQueryable&lt;Device&gt;) dataContext.Devices;

if (txtCZone.Text.Length &gt; 0)
    query = query.Where(device =&gt; device.CZone == int.Parse(txtCZone.Text));
if (txtUCZone.Text.Length &gt; 0)
    query = query.Where(device =&gt; device.UCZone == int.Parse(txtUCZone.Text));
if (txtLZone.Text.Length &gt; 0)
    query = query.Where(device =&gt; device.LZone == int.Parse(txtLZone.Text));

dgResults.DataSource = query.ToList();
dgResults.DataBind();</pre>
</div>
<p>And of course we can use the query syntax instead (replacing lines 5-10 above):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:bcfec0c3-d2bc-49b0-b45a-9878b8717f6f" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">if (txtCZone.Text.Length &gt; 0)
	query = from device in query where device.CZone == int.Parse(txtCZone.Text) select device;
if (txtUCZone.Text.Length &gt; 0)
	query = from device in query where device.UCZone == int.Parse(txtUCZone.Text) select device;
if (txtLZone.Text.Length &gt; 0)
	query = from device in query where device.LZone == int.Parse(txtLZone.Text) select device;</pre>
</div>
<p>The result is that the SQL code is specifically written to support only the parameters that the user has entered. No extra SQL, and no specific SQL to maintain. Remember that LINQ can be chained together without querying the underlying data. The actual querying of the data only occurs when enumerating the results, using an operation like “ToList()”.</p>
<p>To support paging we need to run 3 different types of underlying queries. Here is where LINQ is really going to shine. We can use the same base query for all of these operations, and not have to worry about the drastically different underlying SQL statements.</p>
<ol>
<li><strong>Result count</strong> &#8211; Simply by calling the “.Count()” method, we can retrieve the number of rows the query will return in total. The underlying SQL will be a simple and efficient <em>Count</em> operation. </li>
<li><strong>Page n query</strong> – By utilizing <em>Skip</em> and <em>Take</em>, any page within the results can be queried. The work of generating a common table expression is handled for you. </li>
<li><strong>First page query</strong> – If the underlying provider has an optimization for using the SQL <em>TOP</em> command, the first page of data you query will be able to avoid a common table expression. This has the advantage of being more efficient when the first (and often most common) page of results is displayed. </li>
</ol>
<p><strong>Real-world Results</strong></p>
<p>I initially ran into this in a real application that was primarily used to search through a large table of records. It had originally used the stored procedure approach, and was causing the entire system to slow down to the point of being unusable. Thanks to LINQ, we were able to make the search usable. In fact, the results were drastic:</p>
<table border="1" cellspacing="0" cellpadding="2" width="309" align="center">
<tbody>
<tr>
<td valign="top" width="66">&#160;</td>
<td valign="top" width="136"><strong>Stored Procedure</strong> </td>
<td valign="top" width="105"><strong>LINQ to SQL</strong> </td>
</tr>
<tr>
<td valign="top" width="66"><strong>Reads</strong></td>
<td valign="top" width="136">Over 4,000,000 </td>
<td valign="top" width="105">8948 </td>
</tr>
<tr>
<td valign="top" width="66"><strong>Duration</strong></td>
<td valign="top" width="136">3249ms </td>
<td valign="top" width="105">189ms </td>
</tr>
</tbody>
</table>
<p>In addition to the improved performance, the code was easier to maintain. The stored procedure was extremely cluttered, had large <em>where</em> clauses, and even contained two nearly identical copies of the query. One for calculating the count, and one for paging support.</p>
<p><strong>Conclusion</strong></p>
<p>LINQ gives us much more than “inline SQL”. It gives us a unified query syntax, delayed execution, query expression building, and dynamically created SQL output. Additionally, the generated queries are optimized based on the exact query being performed instead of making generic SQL that is optimized for multiple scenarios. </p>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/zETDN4LHdbQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/10/speeding-up-data-access-by-using-linq-to-sql-or-ef.html/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL &amp; Entity Framework Pitfalls</title>
		<link>http://www.ytechie.com/2009/09/linq-to-sql-entity-framework-pitfalls.html</link>
		<comments>http://www.ytechie.com/2009/09/linq-to-sql-entity-framework-pitfalls.html#comments</comments>
		<pubDate>Thu, 01 Oct 2009 02:03:06 +0000</pubDate>
		<dc:creator>Jason Young</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/09/linq-to-sql-entity-framework-pitfalls.html</guid>
		<description><![CDATA[In my last post describing the differences between LINQ to objects and LINQ to SQL, I mentioned how LINQ to SQL and Entity Framework “interpret” your LINQ code, and create the corresponding SQL. Forgetting this fact is extremely dangerous, because LINQ to SQL and other object relational mappers are extremely leaky abstractions. LINQ is obviously [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post describing the <a href="http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html">differences between LINQ to objects and LINQ to SQL</a>, I mentioned how LINQ to SQL and Entity Framework “interpret” your LINQ code, and create the corresponding SQL. Forgetting this fact is extremely dangerous, because LINQ to SQL and other object relational mappers are extremely leaky abstractions. LINQ is obviously a wonderful technology, but this post will be talking about some potential pitfalls you may run into.</p>
<p><strong>SQL Query Complexity Disproportional to LINQ Complexity</strong></p>
<p>Recall the example from my last post:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:5641d3eb-6590-4d9a-8cac-c0db294cd564" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Query Syntax:
from device in Devices
where device.Type != null
select device.DeviceId

//SQL Syntax:
SELECT [t0].[DeviceId]
FROM [Devices] AS [t0]
WHERE [t0].[Type] IS NOT NULL</pre>
</div>
<p>In this case, LINQ to SQL has done something wonderful. It’s saved us from having to understand or worry about the translation of syntax between C# and SQL. Now, what happens when we write something a little more advanced, such as a nested group by?</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:62df480a-95e2-4910-95b5-9ec5eb45f0be" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">from d in Devices
group d by d.CZone into czoneGroup
select new { Key = czoneGroup.Key, val = from d2 in czoneGroup
	group d2 by d2.LZone into lzoneGroup
	select lzoneGroup.Key }</pre>
</div>
<p>And the corresponding SQL:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f50bc355-9467-4d6a-9aaa-63ff31cecff9" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">SELECT [t0].[CZone] AS [Key]
FROM [Devices] AS [t0]
GROUP BY [t0].[CZone]
GO

DECLARE @x1 Int = 3
SELECT [t0].[LZone]
FROM [Devices] AS [t0]
WHERE ((@x1 IS NULL) AND ([t0].[CZone] IS NULL)) OR ((@x1 IS NOT NULL) AND ([t0].[CZone] IS NOT NULL) AND (@x1 = [t0].[CZone]))
GROUP BY [t0].[LZone]
GO

DECLARE @x1 Int = 1
SELECT [t0].[LZone]
FROM [Devices] AS [t0]
WHERE ((@x1 IS NULL) AND ([t0].[CZone] IS NULL)) OR ((@x1 IS NOT NULL) AND ([t0].[CZone] IS NOT NULL) AND (@x1 = [t0].[CZone]))
GROUP BY [t0].[LZone]
GO

//Reminaing SQL removed....</pre>
</div>
<p>What just happened? Our innocent nested join has turned into a monster! This is an example of a query that is simple to do in LINQ, but has no translation to a simple SQL statement. Instead of just bombing, the LINQ to SQL engine comes up with a solution that a user may not have written themselves. A typical SQL developer may have looked for a different approach.</p>
<p><em>Side note: In the nested group-by, notice that LINQ to SQL uses multiple queries. This differs from the Entity Framework approach, which uses outer joins to achieve the same effect.</em></p>
<p>Does it matter? The answer isn’t so simple. In this simplified example, the performance impact is minimal. Unfortunately, with a large amount of data in this type of query, you could start to experience terrible performance. I personally saw a nested query that was only a few lines of code turn into a 27 page SQL statement. The SQL statement was technically correct, but took seconds to execute, when it should have taken a fraction of a second.</p>
<p>One simple solution that I have found to be very effective, yet not intuitive, is breaking apart the initial query and forcing it to execute using the ToList() method. You’ll have to have a decent “where” clause to avoid excessive amounts of data being returned. Once we have the raw data, LINQ to objects will provide us the same set of tools to further manipulate our data. For instance, here is a modified version of the example presented earlier:</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:fe1b1c69-41cf-42f9-9ab2-feed64283c70" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Simple &amp; fast initial query from the database
var rawData = (from d in Devices
where d.Location = 'B3').ToList();

//This operation happens "disconnected"
var results = from d in rawData
group d by d.CZone into czoneGroup
select new { Key = czoneGroup.Key, val = from d2 in czoneGroup
	group d2 by d2.LZone into lzoneGroup
	select lzoneGroup.Key };</pre>
</div>
<p>The reason this works well is that it’s taking advantage of the strength of SQL Server, which is to query data, and the strength of .NET, which is to process and manipulate data.</p>
<p><strong>LINQ Abstracting Away Problems it Can’t Solve</strong></p>
<p>Here is a simplified version of a query I saw recently:</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:6b58a736-2368-485e-ad30-4726c9267ae1" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">int sum = (from d in Devices
where 1 == 2 &amp;&amp; d.CZone != null
select d.CZone.Value).Sum()</pre>
</div>
<p>To make it extremely clear what I’m trying to accomplish, I put “1 == 2” in the “where” clause, so that no rows match the condition. The “Sum()” method returns the type that it’s acting on. For example, if you’re summing integers, the result is an integer. If you’re summing nullable integers, the result is a nullable integer. This is perfectly valid LINQ. This is effectively the SQL that is generated (I simplified it for clarity):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:8e0404af-4082-4891-80e6-4e96545bd024" class="wlWriterEditableSmartContent">
<pre name="code" class="sql">Select SUM(CZone)
From Devices
Where 1 = 2</pre>
</div>
<p>Since the result of this SQL statement is NULL, it can’t be converted back to an integer. The exception is “<em>InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.</em>”</p>
<p>When the LINQ is translated to SQL, there is no such operation as converting a nullable value to a non-nullable, so the “.Value” operation is ignored. This would be fine if the sum function still expected a nullable return type, but it’s now expecting an integer. When it can’t find any rows to return, it tries to return NULL. Since it’s trying to package up a NULL value into a standard integer type, it has no choice but to throw an exception.</p>
<p><strong>Conclusion</strong></p>
<p>Getting started with LINQ is fairly straightforward, but you can’t forget the fact that whatever query you’re writing must be converted into a SQL statement, and the results must be converted back to data that is understandable to .NET. Every LINQ query you write should be checked with a tool such as <a href="http://www.linqpad.net/" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.linqpad.net/?referer=');">LINQPad</a> to ensure that the SQL is efficient, and matches what you expect.</p>
<p>Also keep in mind that when you upgrade your data provider, your queries can change. For example, converting a statement from LINQ to SQL to Entity Framework can generate different SQL queries, just as updating to a newer version of the same ORM can.</p>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/M66YegmWpl0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/09/linq-to-sql-entity-framework-pitfalls.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Understanding LINQ and LINQ to SQL (and EF)</title>
		<link>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html</link>
		<comments>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html#comments</comments>
		<pubDate>Thu, 17 Sep 2009 15:17:44 +0000</pubDate>
		<dc:creator>Jason Young</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html</guid>
		<description><![CDATA[Back to basics for this post. Developers often throw around the word LINQ when talking about a number of different technologies. Now that I have been comfortably using a wide variety of LINQ technologies for a fair amount of time, I’m now able to convey some of the key differences that are critical to using [...]]]></description>
			<content:encoded><![CDATA[<p>Back to basics for this post. Developers often throw around the word LINQ when talking about a number of different technologies. Now that I have been comfortably using a wide variety of LINQ technologies for a fair amount of time, I’m now able to convey some of the key differences that are critical to using LINQ technologies efficiently. I’m also using this as a foundation and reference for some exciting upcoming posts.</p>
<p>The first key point is to know what the heck LINQ is. LINQ itself is a number of separate features. One of these key features is being able to write SQL-like syntax (query syntax) in your code. At a basic level, that’s all you need to know for now.</p>
<p><strong>LINQ (to objects)</strong></p>
<p>First, we’re going to talk about LINQ to objects, which I typically just refer to as LINQ (possibly making the matter more confusing). It has absolutely nothing to do with SQL Server, Oracle, or any other kind of relational database. I’m talking about LINQ to objects, because I think that understanding it and contrasting it with LINQ to SQL is critical to understanding both.</p>
<p>For a moment, forget that LINQ exists. Let’s say that you wanted to filter a list of names, to only get names that start with the letter “J”. You could write the following “utility” function: (if you don’t understand <a href="http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html">“yield return”, see this post on that topic</a>).</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:74dcd1eb-c170-4d76-b6e8-441fc9f40dba" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public static IEnumerable&lt;string&gt; GetNamesStartingWithJ(IEnumerable&lt;string&gt; names)
{
    foreach(var name in names)
        if(name.StartsWith("J"))
            yield return name;
}</pre>
</div>
<p>A new feature in C# introduced in .NET 3.0, is a concept known as an extension method. This lets us turn my handy dandy static utility method into a method that can be called on a list of names. By changing the signature to this:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:b27c9cbc-7f0a-4fb5-be05-8f5946380254" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public static IEnumerable&lt;string&gt; GetNamesStartingWithJ(this IEnumerable&lt;string&gt; names)</pre>
</div>
<p>I can then call it like this (Sweet!):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:9b70c490-45ef-40a4-903b-4cbd3b3470ed" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var myListOfNames = new List&lt;T&gt; {"Abe", "Jack", "Jason"};
var jNames = myListOfNames.GetNamesStartingWithJ();</pre>
</div>
<p>We haven’t even talked about LINQ yet, but we’ve basically reinvented a portion of it. As an exercise for the reader, think about how you could use a Lambda parameter to pass in a filter criteria to create a &quot;.Where” method. All the pieces are in place to re-create this form of LINQ yourself.</p>
<p>One actual new feature for LINQ is known as query syntax. Basically, it gives us an alternative way to write our query. It makes the code look more like SQL, and less like a long chain of extension methods.</p>
<p>Lambda Syntax:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a76b3655-6a72-4fa3-b147-38bfd8dedf80" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var uppercaseJNames = names.Where(name =&gt; name.StartsWith("J")).Select(name =&gt; name.ToUpper());</pre>
</div>
<p>Query Syntax (same query):</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:7e10587a-ba5f-4062-bba8-cab816b7eb3e" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var uppercaseJNames = from name in names
	where name.StartsWith("J")
	select name.ToUpper();</pre>
</div>
<p>In both of those examples, the exact same operations are occurring, and you get the result. The one you choose will most likely come down to personal preference. It’s also worth noting that some of the extension methods provided out of the box are not available in query syntax. You can either avoid the query syntax in those cases, or use a hybrid approach.</p>
<p><strong>How is LINQ to SQL (and Entity Framework, etc) Different?</strong></p>
<p>Now, I hope you understand that there isn’t really any magic going on in LINQ. Microsoft has simply given us a new set of easy to use tools that make working with sets a breeze.</p>
<p>LINQ to SQL is a different matter. Instead of executing code, you’re building an expression. An expression is simply a “picture” of what you’re trying to accomplish. It can interpreted in many different ways. To understand the underlying technology, you’ll have to read up on expression trees, which I’m intentionally keeping outside the scope of this post.</p>
<p>If we have a “picture” of a query, what happens to it when we want to “run” it? LINQ to SQL, Entity Framework, and other LINQ implementations look at your query, and basically translate it into something else. How about an example?:</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:fc8658fb-f565-47dc-af0c-f5c4007c3a89" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Query Syntax
var deviceIds = from device in Devices
where device.Type == "I"
select device.DeviceId

//Lambda Sytax (extension methods)
var deviceIds = Devices
   .Where (device =&gt; (device.Type == "I"))
   .Select (device =&gt; device.DeviceId)

//SQL
SELECT [t0].[DeviceId]
FROM [Devices] AS [t0]
WHERE [t0].[Type] = "I"</pre>
</div>
<p>I’ve provided the query syntax and the lambda syntax. At the bottom is the resulting translation into a SQL statement.</p>
<p>In this last example, I’ll try to make it clear that your code is simply interpreted and translated:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a87dc611-83a7-4e29-ad97-f2b3ecff5f57" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Query Syntax:
from device in Devices
where device.Type != null
select device.DeviceId

//SQL Syntax:
SELECT [t0].[DeviceId]
FROM [Devices] AS [t0]
WHERE [t0].[Type] IS NOT NULL</pre>
</div>
<p>Notice that the C# operator “!=” translates in SQL to “IS NOT NULL”. This was handled automatically for us. Our expression did NOT get back all the rows and apply a conditional to it.</p>
<p>Why is this important? To use either technology effectively, you have to understand that when you’re working with objects, it’s simply a chain of methods, and often behaves as you would expect. When working with LINQ to SQL (or a related technology), the expression is evaluated, and might not execute like you expected.</p>
<p>Understanding the internal workings of these technologies will let us fully take advantage of all the wonderful features it has to offer. In upcoming posts, I’ll be warning you of some potential pitfalls related to how your queries are interpreted and translated. I’ll also be showing you how to get significant performance gains by using LINQ to SQL or Entity Framework efficiently (over traditional SQL based solutions). I’ll also be showing you how I write LINQ queries to query an AutoCAD document!</p>
<p>Related Posts:</p>
<ul>
<li><a href="http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html">Using Yield Return for readability and performance</a></li>
<li><a href="http://www.ytechie.com/2008/06/using-var-to-simplify-code-and-avoid-redundancy.html">Using “var” to simplify code and avoid redundancy</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/-GHBHvcAFQ8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Determine if a point is contained within a polygon</title>
		<link>http://www.ytechie.com/2009/08/determine-if-a-point-is-contained-within-a-polygon.html</link>
		<comments>http://www.ytechie.com/2009/08/determine-if-a-point-is-contained-within-a-polygon.html#comments</comments>
		<pubDate>Tue, 18 Aug 2009 17:47:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/08/determine-if-a-point-is-contained-within-a-polygon.html</guid>
		<description><![CDATA[One of my recent projects had a requirement to take a list of points and a list of polygons (of any order), and determine which points were in which polygons. I find this problem interesting, because the solution is not apparent, but it is easy to implement. One common algorithm is called the ray casting [...]]]></description>
			<content:encoded><![CDATA[<p>One of my recent projects had a requirement to take a list of points and a list of polygons (of any order), and determine which points were in which polygons. I find this problem interesting, because the solution is not apparent, but it is easy to implement.</p>
<p>One common algorithm is called the ray casting algorithm. <a href="http://en.wikipedia.org/wiki/Point_in_polygon" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Point_in_polygon?referer=');">You can read more about the ray casting algorithm on Wikipedia</a>. My buddy Google was able to find <a href="http://alienryderflex.com/polygon/" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/alienryderflex.com/polygon/?referer=');">another great resource</a> with some sample Java code.</p>
<p>After an initial performance test, I found this algorithm to be extremely fast. I was able to process over 200,000 checks in under a second.</p>
<p>I converted the code to something a little more object oriented. I wanted a class that would represent a Polygon, and also have a method that would tell me if a point was contained within it. I’m including the code in the hopes that it may help someone else one day:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:4d16a27b-51d1-4abc-8272-117ce166f9e1" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">/// &lt;summary&gt;
///		Represents a geometric polygon made up of any number of sides, defined by &lt;see cref="PointF"/&gt; structures
///		between those points.
/// &lt;/summary&gt;
public class Polygon
{
    private readonly PointF[] _vertices;

    /// &lt;summary&gt;
    ///		Creates a new instance of the &lt;see cref="Polygon"/&gt; class with the specified vertices.
    /// &lt;/summary&gt;
    /// &lt;param name="vertices"&gt;
    ///		An array of &lt;see cref="PointF"/&gt; structures representing the points between the sides of the polygon.
    /// &lt;/param&gt;
    public Polygon(PointF[] vertices)
    {
        _vertices = vertices;
    }

    /// &lt;summary&gt;
    ///		Determines if the specified &lt;see cref="PointF"/&gt; if within this polygon.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    ///		This algorithm is extremely fast, which makes it appropriate for use in brute force algorithms.
    /// &lt;/remarks&gt;
    /// &lt;param name="point"&gt;
    ///		The point containing the x,y coordinates to check.
    /// &lt;/param&gt;
    /// &lt;returns&gt;
    ///		&lt;c&gt;true&lt;/c&gt; if the point is within the polygon, otherwise &lt;c&gt;false&lt;/c&gt;
    /// &lt;/returns&gt;
    public bool PointInPolygon(PointF point)
    {
        var j = _vertices.Length - 1;
        var oddNodes = false;

        for (var i = 0; i &lt; _vertices.Length; i++)
        {
            if (_vertices[i].Y &lt; point.Y &amp;&amp; _vertices[j].Y &gt;= point.Y ||
                _vertices[j].Y &lt; point.Y &amp;&amp; _vertices[i].Y &gt;= point.Y)
            {
                if (_vertices[i].X +
                    (point.Y - _vertices[i].Y)/(_vertices[j].Y - _vertices[i].Y)*(_vertices[j].X - _vertices[i].X) &lt; point.X)
                {
                    oddNodes = !oddNodes;
                }
            }
            j = i;
        }

        return oddNodes;
    }
}</pre>
</div>
<p>Of course I can’t write a class without the appropriate unit tests:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:89be2ab7-4fb8-4efe-af79-b22559ce957e" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">[TestClass]
public class PolygonTests
{
    [TestMethod]
    public void PointInPolygon_InnerPoint_ContainedWithinPolygon()
    {
        var vertices = new PointF[4]
                            {
                                new PointF(1, 3),
                                new PointF(1, 1),
                                new PointF(4, 1),
                                new PointF(4, 3)
                            };

        var p = new Polygon(vertices);

        Assert.AreEqual(true, p.PointInPolygon(new PointF(2,2)));
    }

    [TestMethod]
    public void PointInPolygon_OuterPoint_NotContainedWithinPolygon()
    {
        var vertices = new PointF[4]
                            {
                                new PointF(1, 3),
                                new PointF(1, 1),
                                new PointF(4, 1),
                                new PointF(4, 3)
                            };

        var p = new Polygon(vertices);

        Assert.AreEqual(false, p.PointInPolygon(new PointF(5,3)));
    }

    [TestMethod]
    public void PointInPolygon_DiagonalPointWithin()
    {
        var vertices = new PointF[3]
                            {
                                new PointF(1, 3),
                                new PointF(1, 1),
                                new PointF(4, 1)
                            };

        var p = new Polygon(vertices);

        Assert.AreEqual(true, p.PointInPolygon(new PointF(2, 2)));
    }

    [TestMethod]
    public void PointInPolygon_DiagonalPointOut()
    {
        var vertices = new PointF[3]
                            {
                                new PointF(1, 3),
                                new PointF(1, 1),
                                new PointF(4, 1)
                            };

        var p = new Polygon(vertices);

        Assert.AreEqual(false, p.PointInPolygon(new PointF(3, 3)));
    }

    [TestMethod]
    public void PointInPolygon_PerformanceTest()
    {
        var vertices = new PointF[4]
                            {
                                new PointF(1, 3),
                                new PointF(1, 1),
                                new PointF(4, 1),
                                new PointF(4, 3)
                            };

        var p = new Polygon(vertices);

        var sw = new Stopwatch();
        sw.Start();

        for(var i = 0; i &lt; 200000; i++)
            p.PointInPolygon(new PointF(2, 2));

        sw.Stop();

        Assert.IsTrue(sw.Elapsed.TotalSeconds &lt; 1);
    }
}</pre>
</div>
<p>The last unit test was only to determine if this method was going to be performant enough for the scenario I wanted to use it in. You may want to remove it or mark it as explicit if you can to avoid timing issues affecting your test outcomes.</p>
<p>If anyone see’s a bug, let me know!</p>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/1DpuVGiySBc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/08/determine-if-a-point-is-contained-within-a-polygon.html/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Delayed execution vs ToList() in LINQ Database Queries</title>
		<link>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html</link>
		<comments>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html#comments</comments>
		<pubDate>Tue, 23 Jun 2009 16:46:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[entity framwork]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html</guid>
		<description><![CDATA[LINQ to SQL and Entity framework allow us to build a query, which gets translated into an expression tree, and executed once the full query is built. The beauty is that we can build up a query using multiple expressions and Lambdas, without actually querying the data. Since these types of queries are delay loaded, [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ to SQL and Entity framework allow us to build a query, which gets translated into an expression tree, and executed once the full query is built. The beauty is that we can build up a query using multiple expressions and Lambdas, without actually querying the data. Since these types of queries are delay loaded, why not avoid executing them until the last possible moment? Read on to see why this is usually a bad idea.</p>
<p>First, let’s take a look the code for a repository method that builds a query, executes the query, and returns the results in a list:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:3a31321f-f9b9-4c17-91c2-43d838b3f22a" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public IEnumerable&lt;Cat&gt; FindAllCats()
{
	var query = from c in db.Cats
		select c;

	return query.ToList();
}</pre>
</div>
<p align="center"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Execute in Repository" border="0" alt="Execute in Repository" src="http://www.ytechie.com/post-images/2009/06/image1.png" width="486" height="142" /> </p>
<p>The “ToList” is forcing the IQueryable&lt;Cat&gt; query to execute and put the results in a list <strong>immediately</strong>. However, we know that IQueryable&lt;T&gt; inherits from IEnumerable&lt;T&gt;, so what happens if we avoid the list creation completely?</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:10d24797-5a70-435a-85bc-c076fe3c457b" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public IEnumerable&lt;Cat&gt; FindAllCats()
{
	var query = from c in db.Cats
		select c;

	return query;
}</pre>
</div>
<p align="center"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Execute in UI" border="0" alt="Execute in UI" src="http://www.ytechie.com/post-images/2009/06/image2.png" width="486" height="142" /></p>
<p align="left">In this scenario, our method is returning the same interface, but the underlying type is now a LINQ database iterator instead of a List&lt;T&gt;.</p>
<p><strong>Delaying execution can lead to</strong> <strong><em>multiple</em></strong> <strong>executions</strong></p>
<p>If the code is not explicitly putting the results into a list, we’re actually passing back a form of an iterator. This works great if we only need to execute the query once. However, if we iterate through the list more than once, <strong>we actually end up executing our query multiple times</strong>. This can obviously lead to poor performance.</p>
<p>If you’re writing fast queries, you may not even notice if they’re being called too many times. However, there may be a worse problem lurking in your code. <strong>Each time you iterate through the enumerator, you’re getting a different set of objects</strong>. The same query is being made with the same results, but the objects are re-built each time. This leads to objects that are <strong>equivalent, but not the same</strong>. For example, you may get back Cat objects with the names “Bill” and “Ted”, but if you actually check them for equality using “==”, they will not be the same object <strong>instance</strong>. <font color="#ff0000"><strong>Correction: Scott points out in the comments that this isn’t necessarily the case. Keep in mind that it can still occur if projecting types and not working with the original objects.</strong></font></p>
<p><strong>Delaying execution may mean you no longer have a database connection when attempting to execute the query</strong></p>
</p>
<p>If you delegate the task of initiating your query to another layer, you better be sure that the database connection is still around, and is in a queryable state. If you’re using the standard repository pattern and a short-lived database connection pattern, you may quickly run into problems when you try to iterate through the results of the enumerator you receive from your repository layer.</p>
<p><strong>Conclusion</strong></p>
<p>If you’re thinking about moving the execution of your queries to another layer, make sure you understand the consequences. You’ll need to weigh those consequences against the tiny benefit that you’ll receive from the delayed execution. There may be cases where delaying the execution or possibly avoiding it completely will improve your application, but those are probably very rare cases.</p>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/fwUif-yxxow" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Common Pitfalls when working with DateTime’s</title>
		<link>http://www.ytechie.com/2009/06/common-pitfalls-when-working-with-datetimes.html</link>
		<comments>http://www.ytechie.com/2009/06/common-pitfalls-when-working-with-datetimes.html#comments</comments>
		<pubDate>Tue, 02 Jun 2009 19:05:49 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/06/common-pitfalls-when-working-with-datetimes.html</guid>
		<description><![CDATA[In .NET, the DateTime structure provides us wonderful functionality, but this seemingly simple structure can cause a lot of headaches if you don’t fully understand how to use it properly. Understand the terminology First, UTC, GMT, and even Zulu time are all the same thing. They’re basically a universal time clock that is not subject [...]]]></description>
			<content:encoded><![CDATA[<p>In .NET, the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.datetime.aspx?referer=');">DateTime</a> structure provides us wonderful functionality, but this seemingly simple structure can cause a lot of headaches if you don’t fully understand how to use it properly.</p>
<p align="center"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Clock" border="0" alt="Clock" src="http://www.ytechie.com/post-images/2009/06/clock.jpg" width="244" height="163" /> </p>
<p><strong>Understand the terminology</strong></p>
<p>First, UTC, GMT, and even Zulu time are all the same thing. They’re basically a universal time clock that is not subject to changes in time zones or time changes. Each tick of the universal clock represents a moment in our perception of time. </p>
<p><strong>Use UTC as long as possible</strong></p>
<p><strong>UTC</strong> is very useful when developing software because it removes the need to know where the time was from, or where it’s going to be used. We don’t even care <em>when</em> it was from, or <em>when</em> we’re displaying it. You can think of your <strong>local</strong> clock as a view of the time right now, where you are. It has already taken into account the time zone and daylight savings time.</p>
<p>These properties of your local clock suggest that we should always convert from the local clock to universal time as early as possible when accepting user input, and convert it back to the users time only when displaying it. This is a simple, easy to use pattern that may be enough to avoid some of the potential problems that other projects face. This pattern will give you the ability to cope with time changes and time zones much more easily.</p>
<p>Converting between local time and UTC is pretty easy. <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx?referer=');">ToLocalTime</a> will convert from universal time to local time. <a href="http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx?referer=');">ToUniversalTime</a> will convert to UTC. Just be aware that these methods have a certain amount of logic in them that only has the rules that were in effect when they were written. They are not perfect for all scenarios. You’ll also want to take a look at the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx?referer=');">Kind</a> property, which affects which conversions you can perform, as well as providing a nice way to keep track of whether or not he time has been adjusted to UTC.</p>
<p><strong>Daylight Savings Time &amp; Time Changes</strong></p>
<p>Every year in many parts of the world, the time changes. Apparently the idea is to save gobs of money by using the sunlight more efficiently instead of using artificial lights. Unfortunately, this really sucks for software developers.</p>
<p>I used to write software for manufacturing facilities that would run during a time change. If you have software that records and time-sensitive data during a time change, your software had better be prepared to handle it the fact that one hour is skipped, and another is repeated. Storing the data in UTC solves part of the problem. Unfortunately, when you try to display the data you’ll have an hour of missing data, and a hour with overlapping data. <strong>You may have to design your user interface to deal with this</strong>.</p>
<p><strong>Fixed-time Appointments</strong></p>
<p>Unfortunately, UTC doesn’t solve all of our time offset problems. Let’s say that you have an appointment that you’re scheduling for a future date that occurs when DST is in effect, but it’s not in effect right now. You choose 5:00am for your appointment time. Your application happily converts the time to UTC, and the reverse process expectedly yields the same result. The problem is, the time offset when the appointment occurs will be different than it is now. Daylight savings for the central time zone for example, switches between and offset of –5 and –6. This diagram attempts to visualize:</p>
<p align="center">&#160;<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="DST DateTime Diagram" border="0" alt="DST DateTime Diagram" src="http://www.ytechie.com/post-images/2009/06/image.png" width="476" height="260" /> </p>
<p>What we want to store is the fact that our appointment occurs at <strong>5:00am local time</strong>. If we simply store the information as UTC, we’re losing this additional information. When we switch to <strong>non-DST</strong> time and use our current time adjustment of <strong>–6 hours</strong>, our appointment now occurs at <strong>4:00am</strong>.</p>
<p>If you’re writing an application that stores fixed-time appointments as well as appointments that are designed to have even intervals (exactly 1 month apart, etc) or occur in a different time zone or DST, you’ll need to store an additional flag with the event so you can make the determination if it needs to be adjusted.</p>
<p><strong>Conclusion</strong></p>
<p>Times can be complicated depending on the requirements of your project. It would be unwise to work these problems out toward the end of a project, because the consistency of usage can’t be guaranteed. Do yourself a favor and plan ahead for these issues, and it will be much easier.</p>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/IABtGo1nfB8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/06/common-pitfalls-when-working-with-datetimes.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tip for Technical Presentations – Detailed Notes</title>
		<link>http://www.ytechie.com/2009/05/tip-for-technical-presentations-detailed-notes.html</link>
		<comments>http://www.ytechie.com/2009/05/tip-for-technical-presentations-detailed-notes.html#comments</comments>
		<pubDate>Mon, 18 May 2009 18:10:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/05/tip-for-technical-presentations-detailed-notes.html</guid>
		<description><![CDATA[Justin Etheredge over at CodeThinked is asking for tips for technical presentations. I can certainly relate to his experiences. Technical presentations, or any type of presentation for that matter, can be intimidating, difficult, and scary. &#160; In my college days, I had to give a presentation in one of my information systems classes. I was [...]]]></description>
			<content:encoded><![CDATA[<p>Justin Etheredge over at CodeThinked is <a href="http://www.codethinked.com/post/2009/05/18/A-Technical-Presenters-Journey-Part-1-Know-Your-Audience.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.codethinked.com/post/2009/05/18/A-Technical-Presenters-Journey-Part-1-Know-Your-Audience.aspx?referer=');">asking for tips for technical presentations</a>. I can certainly relate to his experiences. Technical presentations, or any type of presentation for that matter, can be intimidating, difficult, and scary.</p>
<p>&#160;<img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="Presentation" border="0" alt="Presentation" src="http://www.ytechie.com/post-images/2009/05/presentation.jpg" width="301" height="200" /> </p>
<p>In my college days, I had to give a presentation in one of my information systems classes. I was pretty arrogant back then (ok, I still am), so I thought it would be a piece of cake to just wing it. I could save time and look like a cool speaker all at the time time. The result was me getting in front of the class, having my face turn red, and basically say “uh” and “um” for 10 minutes. It was so bad that people actually began to laugh. It pains me to even write about it.</p>
<p>A semester later, I had to give another presentation to an even bigger class. I was so nervous I can’t even describe it. I spent hours upon hours making creating a “script” that I could simply read. The result was that I actually didn’t even use the script. I actually knew what the hell I was talking about and ended up using the script as a reference. I did a great job speaking!</p>
<p>So how do I prepare for presentations these days? I have detailed notes, formatted specifically for the presentation. On my slides, I always keep the number of bullet points per slide low, usually 4 or less. In my notes, I organize them by bullet point so that I can walk though them while I go over each bullet point. <strong>I try to balance simplify with detail. </strong>The notes have to be <strong>simple</strong> enough to read quickly, but <strong>detailed</strong> enough that I can just read them out loud if I lose focus and forget the purpose. Bolding keywords and phrases can help quickly identify the key concepts while still having a readable version if needed.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Slide with Notes" border="0" alt="Slide with Notes" src="http://www.ytechie.com/post-images/2009/05/image1.png" width="481" height="348" /> </p>
</p>
<p>I’ve seen many presentations where the speaker gets nervous and forgets what a slide or bullet point means. The usual remedy they employ is just reading the slide verbatim. Don’t let this happen to you. <strong>It is almost certain that you’ll forget a critical piece of information during your presentation. The trick is to be ready for it.</strong></p>
<p>In my most recent <a href="http://www.ytechie.com/2009/04/speaking-at-day-of-net-at-fox-valley-tech.html">presentation (on Unit Testing)</a>, I actually wrote a paper on the topic I was presenting on. This allowed me to get all of my thoughts in order, and get feedback from others. Once I actually had to put together the PowerPoint, that was the easy part. I was basically creating an outline from an existing document, and the details became my notes.</p>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/oXGKW8ihmeg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/05/tip-for-technical-presentations-detailed-notes.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Practical .NET Unit Testing – Free paper released</title>
		<link>http://www.ytechie.com/2009/04/practical-net-unit-testing-free-paper-released.html</link>
		<comments>http://www.ytechie.com/2009/04/practical-net-unit-testing-free-paper-released.html#comments</comments>
		<pubDate>Thu, 30 Apr 2009 13:04:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[software development]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/04/practical-net-unit-testing-free-paper-released.html</guid>
		<description><![CDATA[I’ve been working on a unit testing paper that sums up my experience in unit testing, and discusses some of the core information that I feel is important about the subject. It’s very much a work in progress, but I wanted to get it out sooner rather than later. I’ll be continuously updating it as [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been working on a unit testing paper that sums up my experience in unit testing, and discusses some of the core information that I feel is important about the subject. It’s very much a work in progress, but I wanted to get it out sooner rather than later. I’ll be continuously updating it as time goes on.</p>
<p><strong>Update: I updated the <a href="http://downloads.ytechie.com/Practical_.NET_Unit_Testing.pdf" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/downloads.ytechie.com/Practical_.NET_Unit_Testing.pdf?referer=');">PDF location</a> to one that doesn&#8217;t require registration.</strong></p>
<p align="center"><a href="http://downloads.ytechie.com/Practical_.NET_Unit_Testing.pdf" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/downloads.ytechie.com/Practical_.NET_Unit_Testing.pdf?referer=');"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Practical .NET Unit Testing" border="0" alt="Practical .NET Unit Testing" src="http://www.ytechie.com/post-images/2009/05/image.png" width="392" height="203" /></a></p>
<p align="left">There are some really great books out there about unit testing, but I think some of them are trying too hard to be long enough to be considered a “book”. I set out to create a document that fills the gap between the various snippets of information from blog posts, and the comprehensive books on the subject. If you’re interested in something a bit more in-depth, here are some great books on the subject:</p>
<ul>
<li>
<div><a href="http://www.amazon.com/gp/product/1933988274?ie=UTF8&amp;tag=ytechie-20&amp;linkCode=xm2&amp;camp=1789&amp;creativeASIN=1933988274" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.amazon.com/gp/product/1933988274?ie=UTF8_amp_tag=ytechie-20_amp_linkCode=xm2_amp_camp=1789_amp_creativeASIN=1933988274&amp;referer=');">The Art of Unit Testing by Roy Osherove</a></div>
</li>
<li>
<div><a href="http://www.amazon.com/gp/product/0131495054?ie=UTF8&amp;tag=ytechie-20&amp;linkCode=xm2&amp;camp=1789&amp;creativeASIN=0131495054" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.amazon.com/gp/product/0131495054?ie=UTF8_amp_tag=ytechie-20_amp_linkCode=xm2_amp_camp=1789_amp_creativeASIN=0131495054&amp;referer=');">xUnit Test Patterns by Gerard Meszaros</a></div>
</li>
</ul>
<p>The paper currently consists of 5 main sections:</p>
<ul>
<li>Why Write Unit Tests? </li>
<li>Unit Test Mechanics </li>
<li>Common Unit Testing Strategies </li>
<li>Designing for Testability </li>
<li>Advanced Techniques </li>
</ul>
<p>Here is a more complete snapshot of the current outline:</p>
<ul>
<li>Introduction </li>
<li>Unit Testing &amp; Managers </li>
<li>What Unit Tests Really Do </li>
<li>Types of Testing </li>
<li>Testing Framework </li>
<li>Test Runner </li>
<li>Unit Test Structure </li>
<li>Other Test Attributes </li>
<li>What is Refactoring? </li>
<li>Test Driven Development </li>
<li>Evolving Code </li>
<li>When Should You Write Unit Tests? </li>
<li>Test is for Functionality, Not Code! </li>
<li>The Constraints of Reality </li>
<li>Interfaces &#8211; Quick Overview </li>
<li>Using a Mocking Framework </li>
<li>Stubs </li>
<li>The Test Driven Design Paradox </li>
<li>Testing Under Pressure </li>
<li>Extracting Duplicate Logic </li>
<li>Modular Design Benefits </li>
</ul>
<p>So what are you waiting for? <a href="http://www.scribd.com/doc/14713003/Practical-NET-Unit-Testing" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.scribd.com/doc/14713003/Practical-NET-Unit-Testing?referer=');">Go check it out online instantly</a>, you can even <a href="http://downloads.ytechie.com/Practical_.NET_Unit_Testing.pdf" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/downloads.ytechie.com/Practical_.NET_Unit_Testing.pdf?referer=');">download it as a PDF</a> if you like. Is anything missing? Is anything just plain wrong? I’d love to hear your feedback.</p>
<p>Remember, if you want to hear more about unit testing, <a href="http://www.ytechie.com/2009/04/speaking-at-day-of-net-at-fox-valley-tech.html">I’ll be speaking in Northeast Wisconsin Saturday, May 9th</a>.</p>
<img src="http://feeds.feedburner.com/~r/Ytechie/~4/vY_DRzpubKU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/04/practical-net-unit-testing-free-paper-released.html/feed</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic page generated in 2.493 seconds. --><!-- Cached page generated by WP-Super-Cache on 2012-01-10 15:38:04 --><!-- Compression = gzip -->

