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

<channel>
	<title>YTechie.com &#187; c#</title>
	<atom:link href="http://www.ytechie.com/category/c/feed" rel="self" type="application/rss+xml" />
	<link>http://www.ytechie.com</link>
	<description>Productive software development using ASP.NET, C#, Adobe Flex, and other technologies and tools.</description>
	<lastBuildDate>Fri, 06 Nov 2009 21:16:21 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>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>superjason</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></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>
]]></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>4</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>superjason</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></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>
]]></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>superjason</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></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>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html/feed</wfw:commentRss>
		<slash:comments>2</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 algorithm. [...]]]></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>
]]></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>5</slash:comments>
		</item>
		<item>
		<title>Value type comparison pitfall with == vs Equals</title>
		<link>http://www.ytechie.com/2009/02/value-type-comparison-pitfall-with-vs-equals.html</link>
		<comments>http://www.ytechie.com/2009/02/value-type-comparison-pitfall-with-vs-equals.html#comments</comments>
		<pubDate>Wed, 11 Feb 2009 17:56:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/02/value-type-comparison-pitfall-with-vs-equals.html</guid>
		<description><![CDATA[I recently ran into a situation that momentarily confused me, because it was non-intuitive to me at first. I’m working on a class that tracks changes made in UI controls in Silverlight, and I wrote code similar to the following:

private void checkChanges(UIElement control)
{
	object oldValue = getOldValue(control);
	object newValue = getNewValue(control);

	if(oldValue == newValue)
		return;

	Debug.WriteLine("The value has changed");
}

The data [...]]]></description>
			<content:encoded><![CDATA[<p>I recently ran into a situation that momentarily confused me, because it was non-intuitive to me at first. I’m working on a class that tracks changes made in UI controls in Silverlight, and I wrote code similar to the following:</p>
<div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a30093d7-b6e9-433f-8316-eda2e6dc808c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#">private void checkChanges(UIElement control)
{
	object oldValue = getOldValue(control);
	object newValue = getNewValue(control);

	if(oldValue == newValue)
		return;

	Debug.WriteLine("The value has changed");
}</pre>
</div>
<p>The data type I was working with in this case was a <em>DateTime</em>, which happens to be Struct, which is a <a href="http://msdn.microsoft.com/en-us/library/34yytbws.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/34yytbws.aspx?referer=');">value type</a>. I know that this code works as expected:</p>
<div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:707b5029-5f63-4a95-842d-e569e19a2cd6" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#">DateTime time1 = DateTime.Parse("1-1-09");
DateTime time2 = DateTime.Parse("1-1-09");

//This is true
Assert.IsTrue(time1 == time2);</pre>
</div>
<p>The code above works because I’m comparing 2 <em>DateTime</em> structures. The original code does not work because <strong>the structures are being boxed</strong>, in other words, they’re wrapped in objects. When you use “==” on two objects, it’s comparing the memory references, determining if they’re the same instance. In this case, the <em>DateTime</em> objects are each boxed into separate boxes.</p>
<p>The workaround is to use the “Equals” method which exists on all objects, and is overridden for the most common framework elements you’ll use. For example, <em>DateTime</em> overrides .<em>Equals</em> to determine if the date/times are equivalent.</p>
<p>So if I wanted to fix my original code, it would look like this:</p>
<div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:b5218056-45a4-44bc-8ee3-d61a990fb0cc" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#">private void checkChanges(UIElement control)
{
	object oldValue = getOldValue(control);
	object newValue = getNewValue(control);

	if(oldValue.Equals(newValue))
		return;

	Debug.WriteLine("The value has changed");
}</pre>
</div>
<p>Of course this problem applies to all values types such as int, double, and any custom structs you may have created.</p>
<p>It goes without saying that this pitfall is not an issue when you’re working with reference types, because they have no need to be boxed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/02/value-type-comparison-pitfall-with-vs-equals.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using C# Yield for Readability and Performance</title>
		<link>http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html</link>
		<comments>http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html#comments</comments>
		<pubDate>Wed, 04 Feb 2009 03:37:33 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html</guid>
		<description><![CDATA[I must have read about &#34;yield&#34; a dozen times. Only recently have I began to understand what it does, and the real power that comes along with it. I&#8217;m going to show you some examples of where it can make your code more readable, and potentially more efficient.
To give you a very quick overview of [...]]]></description>
			<content:encoded><![CDATA[<p>I must have read about &quot;yield&quot; a dozen times. Only recently have I began to understand what it does, and the real power that comes along with it. I&#8217;m going to show you some examples of where it can make your code more readable, and potentially more efficient.</p>
<p>To give you a <strong>very</strong> quick overview of how the yield functionality works, I first want to show you an example without it. The following code is simple, yet it&#8217;s a common pattern in the latest project I&#8217;m working on.</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:ae5f77da-9134-4a5a-90b8-136ccbf440b4" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c#" name="code">IList&lt;string&gt; FindBobs(IEnumerable&lt;string&gt; names)
{
	var bobs = new List&lt;string&gt;();

	foreach(var currName in names)
	{
		if(currName == &quot;Bob&quot;)
			bobs.Add(currName);
	}

	return bobs;
}</pre>
</div>
<p>Notice that I take in an IEnumerable&lt;string&gt;, and return an IList&lt;string&gt;. My general rule of thumb has been to be as lenient as possible with my input, and as strict as possible with my output. For the input, it clearly makes sense to use IEnumerable if you&#8217;re just going to be looping through it with a <em>foreach</em>. For the output, I try to use an interface so that the implementation can be changed. However, I chose to return the list because the caller may be able to take advantage of the fact that I already went through the work of making it a list.</p>
<p>The problem is, my design isn&#8217;t chainable, and it&#8217;s creating lists all over the place. In reality, this probably doesn&#8217;t add up to much, but it&#8217;s there nonetheless.</p>
<p>Now, let&#8217;s take a look at the &quot;yield&quot; way of doing it, and then I&#8217;ll explain how and why it works:</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a25345cb-149d-46f3-be0e-9061a7092d62" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c#" name="code">IEnumerable&lt;string&gt; FindBobs(IEnumerable&lt;string&gt; names)
{
	foreach(var currName in names)
	{
		if(currName == &quot;Bob&quot;)
			yield return currName;
	}
}</pre>
</div>
<p>In this version, we have changed the return type to IEnumerable&lt;string&gt;, and we&#8217;re using &quot;yield return&quot;. Notice that I&#8217;m no longer creating a list. What&#8217;s happening is a little confusing, but I promise it&#8217;s actually incredibly simple once you understand it.</p>
<p>When you use the &quot;yield return&quot; keyphrase, .NET is wiring up a whole bunch of plumbing code for you, but for now you can pretend it&#8217;s magic. When you start to loop in the calling code (not listed here), this function actually gets called over and over again, but each time it resumes execution where it left off.</p>
<table cellspacing="0" cellpadding="2" width="400" border="0">
<tbody>
<tr>
<td>
<p><strong>Typical Implementation</strong></p>
</td>
<td><strong>Yield Implementation</strong></td>
</tr>
<tr>
<td>
<ol>
<li>Caller calls function<br />
            </li>
<li>Function executes and returns list<br />
            </li>
<li>Caller uses list </li>
</ol>
</td>
<td>
<ol>
<li>Caller calls function<br />
            </li>
<li>Caller requests item<br />
            </li>
<li>Next item returned<br />
            </li>
<li>Goto step #2 </li>
</ol>
</td>
</tr>
</tbody>
</table>
<p>Although the execution of the yield implementation is a little more complicated, what we end up with is an implementation that <strong>&quot;pulls&quot;</strong> items one at a time instead of having to build an entire list before returning to the client.</p>
<p>In regards to the syntax, I personally think the yield syntax is simpler, and does a better job conveying what the method is actually doing. Even the fact that I&#8217;m returning IEnumerable tells the caller that its only concern should be that it can &quot;foreach&quot; over the return data. <strong>The caller can now make their own decision</strong> if they want to put it in a list, possibly at the expense of performance.</p>
<p>In the simple example I provided, you might not see much of an advantage. However, you&#8217;ll avoid unnecessary work when the caller can &quot;short-circuit&quot; or cancel looping through all of the items that the function will provide. When you start chaining methods using this technique together, this becomes more likely, and the amount of work saved can possibly multiply.</p>
<p>Ayende has a great example of <a href="http://ayende.com/Blog/archive/2008/01/05/Pipes-and-filters-The-IEnumerable-appraoch.aspx" target="_blank" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/ayende.com/Blog/archive/2008/01/05/Pipes-and-filters-The-IEnumerable-appraoch.aspx?referer=');">using yield for a slick pipes &amp; filters implementation</a>. He even has a <a href="http://ayende.com/Blog/archive/2008/01/06/Pipes-and-filters-The-multi-threaded-version.aspx" target="_blank" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/ayende.com/Blog/archive/2008/01/06/Pipes-and-filters-The-multi-threaded-version.aspx?referer=');">version that is multi-threaded</a> which I find very intriguing.</p>
<p>One of my first reservations with using yield was that there is a potential performance implication. Since c# is keeping track of what is going on in what is essentially a state machine, there is a bit of overhead. Unfortunately, I can&#8217;t find any information that demonstrates the performance impact. I do think that the potential advantages I mentioned should outweigh the overhead concerns.</p>
<p><strong>Conclusion</strong></p>
<p>Yield can make your code more efficient and more readable. It&#8217;s been around since .NET 2.0, so there&#8217;s not much reason to avoid understanding and using it.</p>
<p>You can find detailed information about <a href="http://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/" target="_blank" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/?referer=');">how the yield keyword works under the hood here</a>.</p>
<p>Have you been using yield in interesting ways? Have you ever been bitten by using it? Leave a comment and let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html/feed</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Locking sessions for multi-threaded access</title>
		<link>http://www.ytechie.com/2008/07/locking-sessions-for-multi-threaded-access.html</link>
		<comments>http://www.ytechie.com/2008/07/locking-sessions-for-multi-threaded-access.html#comments</comments>
		<pubDate>Thu, 10 Jul 2008 16:49:48 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2008/07/locking-sessions-for-multi-threaded-access.html</guid>
		<description><![CDATA[I recently ran into a situation where I needed to upload some small files from a Flex client application to an ASP.NET web server. I decided to store the uploaded files in the users session while they were in the checkout process. Once the user confirms their order, the images are read from the session [...]]]></description>
			<content:encoded><![CDATA[<p>I recently ran into a situation where I needed to upload some small files from a Flex client application to an ASP.NET web server. I decided to store the uploaded files in the users session while they were in the checkout process. Once the user confirms their order, the images are read from the session and stored to the database.</p>
<p>Here is the original code from the page that accepts each uploaded file, and adds it to a Dictionary in the collection:</p>
<pre class="c#" name="code">if (Session[SESSION_ORDER_FILES] == null)
{
	//Our dictionary hasn't been created, so we do it now
	files = new Dictionary&lt;string, byte[]&gt;();
	Session[SESSION_ORDER_FILES] = files;
}
else
{
	//The dictionary has already been created, just load it
	files = (Dictionary&lt;string , byte[]&gt;) Session[SESSION_ORDER_FILES];
}

//If we have the &quot;_clearPrevious&quot; flag, that means all
//of the files should be removed from this users session
if (_clearPrevious)
	files.Clear();

//If the file name is the same, replace it
if (files.ContainsKey(_fileName))
	files.Remove(_fileName);

files.Add(_fileName, bytes);</pre>
<p>The problem is that we ended up with missing images. The client was sending them, but when the user confirmed their order they were missing images in the session. Since ASP.NET will process page requests in multiple threads, <strong>the session can be accessed in multiple threads</strong>!</p>
<p>Now, we need to find a way to lock them. I questioned whether ASP.NET would give me the same session object each time, or a new instance representing the same session. I whipped up this code in a test page. It saves the previous session reference to the session. I know it&#8217;s a little strange, but since no serialization happens with the session, it gave me a good way to know if the previous session object and the current session object were <strong>the same instance</strong>.</p>
<pre class="c#" name="code">const string SESS_SESS = &quot;test&quot;;
var currSessionObj = Session[SESS_SESS];

if(currSessionObj == null)
	//First page load
	Session[SESS_SESS] = Session;
else
	lblText.Text = (Session[SESS_SESS] == Session).ToString();</pre>
<p>The result of this page was <strong>false</strong>. That means you most certainly do <strong>get a new session instance each time</strong>. Keep in mind that I&#8217;m not saying it&#8217;s a different session, the object you&#8217;re accessing the session with simply changes.</p>
<p><strong>What does this mean?</strong></p>
<p>This means that you have to be careful when there is a chance that you&#8217;re working with session objects in multiple pages, or in a page that could be accessed multiple times simultaneously. Thankfully, there are only a few real-world scenarios where this would be a large concern.</p>
<p>As with any other kind of multi-threaded code, be careful if you&#8217;re checking the session, and then performing an action based on the result. In that case, you&#8217;ll need to lock a global object that is available to all threads that could access that code. Here is an example:</p>
<pre class="c#" name="code">lock(Global.SessionLock)
{
	if(Session[&quot;foo&quot;] == null)
		Session[&quot;foo&quot;] = new Bar();
}</pre>
<p>In your Global class, you&#8217;ll need this field: </p>
<pre class="c#" name="code">static object SessionLock = new object();</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2008/07/locking-sessions-for-multi-threaded-access.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using objects or repository interface in constructor</title>
		<link>http://www.ytechie.com/2008/07/using-objects-or-repository-interface-in-constructor.html</link>
		<comments>http://www.ytechie.com/2008/07/using-objects-or-repository-interface-in-constructor.html#comments</comments>
		<pubDate>Tue, 08 Jul 2008 18:48:33 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[productivity]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2008/07/using-objects-or-repository-interface-in-constructor.html</guid>
		<description><![CDATA[I&#8217;ve been really trying to use the Single Responsibility Pattern in all of the classes I design. Recently, I needed to create code to query a list of holidays from the database, and then create a method that allows you to get the number of holidays between two given dates.
Here was my first stab at [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been really trying to use the <a href="http://www.ytechie.com/2008/06/agile-patterns-practices-and-the-developer-divide.html">Single Responsibility Pattern</a> in all of the classes I design. Recently, I needed to create code to query a list of holidays from the database, and then create a method that allows you to get the number of holidays between two given dates.</p>
<p>Here was my first stab at the constructor:</p>
<pre class="c#" name="code">public HolidayCalculator(IEnumerable&lt;DateTime&gt; holidays)</pre>
<p>It&#8217;s simple and easy to understand. Then I started thinking about some of the dependency injected examples I&#8217;ve seen. For example, <a href="http://www.springframework.net/doc-latest/reference/html/quickstarts.html" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.springframework.net/doc-latest/reference/html/quickstarts.html?referer=');">one of the Spring.NET IoC quickstarts</a> has a similar example, except that they&#8217;re trying to list movies. In their example, they use an IMovieFinder interface. That interface has a single method that retrieves a list of movies. Using this concept, my constructor would look like (and what I ultimately changed it to):</p>
<pre class="c#" name="code">public HolidayCalculator(IHolidayRepository holidayRepository)</pre>
<p>That example originally seemed unnecessarily complex to me. Why separate something so simple and disconnected into an interface? Well, it turns out there are a couple of good reasons that you might want to do this.</p>
<p><strong>Delay loading</strong></p>
<p>With my original constructor, I had to load all of the holidays from the repository (ultimately a database in the production environment) to even create an instance of this class. This is certainly less than ideal when I want to use this class as a singleton that may get created early in the application.</p>
<p><strong>Single Responsibility</strong></p>
<p>In my original design, I was accepting in a list that would get cached in my holiday calculator. My class now has two responsibilities. It has to calculate holidays, and it has to cache the holiday list. What if I wanted to change how the list was cached? I would have to change the class, which is not ideal.</p>
<p><a href="http://www.ytechie.com/post-images/2008/07/holiday-calculator-design.gif"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="97" alt="Holiday-Calculator-Design" src="http://www.ytechie.com/post-images/2008/07/holiday-calculator-design-thumb.gif" width="361" border="0" /></a></p>
<p>Ideally, this class would load the holiday list each time it needs to perform a calculation. The implementation passed into the constructor would be responsible for caching. In fact, we can now easily separate out the caching feature, and the holiday loading feature. Both classes would implement the IHolidayRepository interface and would be chained together. The caching class would take an IHolidayRepository.</p>
<p><strong>Incremental Coding</strong></p>
<p>Following the Agile philosophy, I can now deliver code faster. I don&#8217;t <em>need</em> to add a caching layer. I can have a working application in less time, and then later evaluate if I need to cache the holiday data.</p>
<p><strong>Conclusion</strong></p>
<p>Overall, this design is a little more work, but I think the benefits outweigh the extra classes and interface I needed to create. This design makes it easy to test, and each class has almost no code in it. Reading it and understanding it is extremely simple.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2008/07/using-objects-or-repository-interface-in-constructor.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using &quot;var&quot; to simplify code and avoid redundancy</title>
		<link>http://www.ytechie.com/2008/06/using-var-to-simplify-code-and-avoid-redundancy.html</link>
		<comments>http://www.ytechie.com/2008/06/using-var-to-simplify-code-and-avoid-redundancy.html#comments</comments>
		<pubDate>Wed, 25 Jun 2008 15:01:51 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[productivity]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2008/06/using-var-to-simplify-code-and-avoid-redundancy.html</guid>
		<description><![CDATA[You&#8217;ve probably already heard of the new &#34;var&#34; keyword that you can use to declare variables in your .NET code. I wanted to clear up some quick myths and give a quick overview of when it&#8217;s most valuable.
If you haven&#8217;t heard of it, you can now use this syntax:
var c = new Cat();
Instead of this:
Cat [...]]]></description>
			<content:encoded><![CDATA[<p>You&#8217;ve probably already heard of the new &quot;var&quot; keyword that you can use to declare variables in your .NET code. I wanted to clear up some quick myths and give a quick overview of when it&#8217;s most valuable.</p>
<p>If you haven&#8217;t heard of it, you can now use this syntax:</p>
<pre class="c-sharp" name="code">var c = new Cat();</pre>
<p>Instead of this:</p>
<pre class="c-sharp" name="code">Cat c = new Cat();</pre>
<p>As Jeff Atwood mentioned, it&#8217;s a <a href="http://www.codinghorror.com/blog/archives/001136.html" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.codinghorror.com/blog/archives/001136.html?referer=');">great way to avoid redundancy</a>. It&#8217;s obvious that you&#8217;re creating a &quot;Cat&quot; object, why do you have to say it twice?</p>
<p>The most important thing to realize, is that it&#8217;s NOT a var like in JavaScript or other languages (<a href="http://www.hanselman.com/blog/BackToBasicsVarDim.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.hanselman.com/blog/BackToBasicsVarDim.aspx?referer=');">DIM in VB</a>). It really is 100% a &quot;Cat&quot; object, complete with intellisense. The generated IL would be no different than specifying the type when you declare it. <strong>It&#8217;s simply a compiler trick</strong>.</p>
<p>Another important thing to remember is that you the assignment must be combined with the declaration. If that wasn&#8217;t the case, readability would be very poor.</p>
<pre class="c-sharp" name="code">var myName = &quot;Jason&quot;; //Allowed
var yourName; //Not allowed
yourName = &quot;Bob&quot;; //Glad you can't do this</pre>
<p>What are some really good examples of when it ideally should be used:</p>
<pre class="c-sharp" name="code">List&lt;Dictionary&lt;int, string&gt;&gt; customers = new List&lt;Dictionary&lt;int, string&gt;&gt;(); //Yuck!
var customers = new List&lt;Dictionary&lt;int, string&gt;&gt;(); //Yay!

OrderRepository orderRepo = (OrderRepository)ctx.GetObject(&quot;orderRepository&quot;); //Yuck!
var orderRepo = (OrderRepository)ctx.GetObject(&quot;orderRepository&quot;); //Yay!

string name = &quot;Jason Young&quot;; //Kinda yucky
var name = &quot;Jason Young&quot;; //Kinda better</pre>
<p>As you can see, those examples have obvious redundancy. Using the &quot;var&quot; keyword increases readability, and makes it easier to change if needed.</p>
<p>There are certainly times when its use is questionable. In the following example, I&#8217;m calling a function that returns some data. Since I&#8217;m not explicitly defining the type that is being returned from that function, I have to do some digging to figure out the type being returned. In this case, you&#8217;ll have to define the correct way to handle it in your coding standards.</p>
<pre class="c-sharp" name="code">var data = GetData();</pre>
<p>Another potential readability issue comes up in the following case. You might not want to use the &quot;Circle&quot; specific methods (Circle inherits from Shape).</p>
<pre class="c-sharp" name="code">Shape s = GetCircle(); //I see what you're doing
var s = GetCircle(); //Do you want a shape, or a circle?</pre>
<p>Aside from a couple of decisions that need to be made in your organization, I think this is a great addition, and should make our lives as developers a little bit easier. It&#8217;s just another tool for our toolbelt. With great power comes great responsibility</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2008/06/using-var-to-simplify-code-and-avoid-redundancy.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A Dependency Injection example with Spring.NET</title>
		<link>http://www.ytechie.com/2008/06/a-dependency-injection-example-with-springnet.html</link>
		<comments>http://www.ytechie.com/2008/06/a-dependency-injection-example-with-springnet.html#comments</comments>
		<pubDate>Fri, 13 Jun 2008 13:32:51 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2008/06/a-dependency-injection-example-with-springnet.html</guid>
		<description><![CDATA[As requested, here is a real world example of how I used dependency injection to simplify a project, increase modularity, and subsequently increase testability.
Here&#8217;s the project. I have a successful website called SimpleTracking.com which allows you to track packages using a simple, common user interface. It also allows you to track pages using RSS.
Here is [...]]]></description>
			<content:encoded><![CDATA[<p>As requested, here is a real world example of how I used <a href="http://www.ytechie.com/2008/06/i-finally-get-the-point-of-inversion-of-control.html">dependency injection</a> to simplify a project, increase modularity, and subsequently increase testability.</p>
<p>Here&#8217;s the project. I have a successful website called <a href="http://www.SimpleTracking.com" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.SimpleTracking.com?referer=');">SimpleTracking.com</a> which allows you to <a href="http://www.SimpleTracking.com" onclick="pageTracker._trackPageview('/outgoing/www.SimpleTracking.com?referer=');">track packages</a> using a simple, common user interface. It also allows you to track pages using RSS.</p>
<p>Here is a list of features:</p>
<ul>
<li>Supports multiple shippers, including FedEx, DHL, and USPS. The tracking number is resolved to one of them, and if a tracking number could belong to more than one, they are called simultaneously, and the one that returns the results is used. </li>
<li>Results are cached to avoid overusing the shippers servers </li>
<li>Errors are handled appropriately </li>
</ul>
<p>I boiled the design into a tree of classes:</p>
<p align="center">&#160;<img height="361" alt="image" src="http://www.ytechie.com/post-images/2008/06/image1.png" width="293" border="0" /> </p>
<p>To greatly simply the design, I decided that each module would implement a common interface. After all, they all take in a tracking number, and return tracking data. Here is the ITracker interface:</p>
<pre class="c-sharp" name="code">public interface ITracker
{
	TrackingData GetTrackingData(string trackingNumber);
}</pre>
<p>Simple enough? <strong>Every </strong>class in the diagram above implements the same interface. If I want to add additional functionality, such as logging for example, I can simply add a class to the chain, and implement the same interface.</p>
<p>Now I can wire it up with Spring.NET:</p>
<pre class="xml" name="code">&lt;object name=&quot;postUtility&quot; type=&quot;YTech.ShipperInterface.Tracking.Http.PostUtility, YTech.ShipperInterface&quot; /&gt;

&lt;!-- The trackers that actually do the work --&gt;
&lt;object name=&quot;uspsTracker&quot; type=&quot;YTech.ShipperInterface.Usps.Tracking.UspsTracker, YTech.ShipperInterface&quot;&gt;
	&lt;constructor-arg ref=&quot;postUtility&quot; /&gt;
	&lt;!-- Code removed for readability... --&gt;
&lt;/object&gt;
&lt;object name=&quot;fedexTracker&quot; type=&quot;YTech.ShipperInterface.FedEx.Tracking.FedexTracker, YTech.ShipperInterface&quot;&gt;
	&lt;constructor-arg ref=&quot;postUtility&quot; /&gt;
	&lt;!-- Code removed for readability... --&gt;
&lt;/object&gt;
&lt;object name=&quot;dhlTracker&quot; type=&quot;YTech.ShipperInterface.Dhl.Tracking.DhlScreenScrapeTracker, YTech.ShipperInterface&quot;&gt;
	&lt;constructor-arg ref=&quot;postUtility&quot; /&gt;
&lt;/object&gt;
&lt;object name=&quot;simulationTracker&quot; type=&quot;YTech.ShipperInterface.Tracking.Simulation.SimulationTracker, YTech.ShipperInterface&quot; /&gt;

&lt;!-- Combine all of the other trackers into one stream --&gt;
&lt;object name=&quot;multiTracker&quot; type=&quot;YTech.ShipperInterface.Tracking.MultiTracker, YTech.ShipperInterface&quot;&gt;
	&lt;constructor-arg&gt;
		&lt;list element-type=&quot;YTech.ShipperInterface.Tracking.ITracker, YTech.ShipperInterface&quot;&gt;
			&lt;ref object=&quot;simulationTracker&quot; /&gt;
			&lt;!-- Order these by popularity --&gt;
			&lt;ref object=&quot;fedexTracker&quot; /&gt;
			&lt;ref object=&quot;uspsTracker&quot; /&gt;
			&lt;ref object=&quot;dhlTracker&quot; /&gt;
		&lt;/list&gt;
	&lt;/constructor-arg&gt;
&lt;/object&gt;

&lt;!-- Cache the upstream tracking data --&gt;
&lt;object name=&quot;cacheTracker&quot; type=&quot;YTech.ShipperInterface.Tracking.CacheTracker, YTech.ShipperInterface&quot;&gt;
	&lt;constructor-arg ref=&quot;multiTracker&quot; /&gt;
&lt;/object&gt;

&lt;!-- Handle errors by logging them, and returning a special ErrorTrackingData object --&gt;
&lt;object name=&quot;MainTracker&quot; type=&quot;YTech.ShipperInterface.Tracking.ErrorHandlerTracker, YTech.ShipperInterface&quot;&gt;
	&lt;constructor-arg ref=&quot;cacheTracker&quot; /&gt;
&lt;/object&gt;</pre>
<p>Now in my code, this is all I have to do:</p>
<pre class="c-sharp" name="code">var ctx = ContextRegistry.GetContext();
var tracker = (ITracker)ctx.GetObject(&quot;MainTracker&quot;);
var td = tracker.GetTrackingData(&quot;my tracking number&quot;);</pre>
<p>Every piece I&#8217;ve written is fully testable. I even created a class that posts data to a remote web server, and returns the response. This allows me to completely test the tracker classes. They don&#8217;t care if they&#8217;re hitting against a real server, or an in memory request/response mock class.</p>
<p>I have nearly 100% test coverage, and making changes to the site is a breeze.</p>
<p>The next step is to convert the actual web project to an MVC project so that I can unit test the actual page functionality.</p>
<p>Hopefully I&#8217;ve given a good example of how inversion of control can be a really good thing. Have any more questions about the architecture? Feel free to leave a comment.</p>
<p>Note: I haven&#8217;t replaced the code on the live SimpleTracking.com site yet, but I plan on upgrading in the next couple of weeks.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2008/06/a-dependency-injection-example-with-springnet.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
