<?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>i-think Twenty-Two</title>
	
	<link>http://www.i-think22.net</link>
	<description>Now with more rambling</description>
	<lastBuildDate>Sat, 04 Jul 2009 08:35:19 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/i-thinkTwenty-two" type="application/rss+xml" /><item>
		<title>Workplace Instant Messaging Etiquette</title>
		<link>http://www.i-think22.net/archives/2009/07/04/workplace-instant-messaging-etiquette/</link>
		<comments>http://www.i-think22.net/archives/2009/07/04/workplace-instant-messaging-etiquette/#comments</comments>
		<pubDate>Sat, 04 Jul 2009 08:35:19 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[The Mill]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[soapbox]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/07/04/workplace-instant-messaging-etiquette/</guid>
		<description><![CDATA[I’ve been getting progressively more and more annoyed at the use of Instant Messaging in the workplace. Don’t get me wrong, I think it is a fantastic way to get quick messages across to people and for communicating across boundaries (such as across the other side of the building), but I feel that there are [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been getting progressively more and more annoyed at the use of Instant Messaging in the workplace. Don’t get me wrong, I think it is a fantastic way to get quick messages across to people and for communicating across boundaries (such as across the other side of the building), but I feel that there are a few rules that should be followed if Instant Messaging is going to be an effective form of communication.</p>
<p><strong>1. If you want something or are asking a question put it in your first message.</strong></p>
<p>Every time I am interrupted by an instant message that just says “Hi” or “Rhys” I scream a little inside. This “handshaking protocol” has broken my concentration and I am now trying to work out what the person wants. I can even see that they are feverously trying to type their actual message. Why waste my previous cycles by forcing me to process a single useless “header” and wait for the actual body. Send the header and the body at the same time!! As an example:</p>
<blockquote><p>Hi Rhys, do you have time for a quick test review?</p>
</blockquote>
<p>This message is concise, expresses the point and can easily be responded to, like so:</p>
<blockquote><p>I’m busy. Go away.</p>
</blockquote>
<p>Ok, in reality it would probably be more like this:</p>
<blockquote><p>Sure</p>
</blockquote>
<p>Or if I really am busy:</p>
<blockquote><p>Can it wait? I am in the middle of something and should be ready in about 20 minutes.</p>
</blockquote>
<p><strong>2. Send complete messages</strong></p>
<p>The last example leads us into the next rule, send complete messages. Don’t leave the recipient of your message guessing. Sure, you can’t answer all possible questions at once, but at least answer the most obvious ones. Empower the person you are communicating with&#160; by giving them the information they need to make a decision so that the conversation can end quickly.</p>
<p><strong>3. Don’t let conversations drag on</strong></p>
<p>If an Instant Messaging conversation is going on too long it is a good indication that the process has broken down. If possible it may be time to get up and speak to the person the old fashioned way. You’ll be able to get more information processed more quickly. If you can’t speak in person, use a telephone or if there is just a lot of information that you need to pass, write an email.</p>
<p><strong>Final words</strong></p>
<p>I’m sure there are more rules that could be applied, but I know that if everyone could follow the first rule I’d be much much happier.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=6O3rYWmhnFs:-0taTpLJK0g:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=6O3rYWmhnFs:-0taTpLJK0g:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=6O3rYWmhnFs:-0taTpLJK0g:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=6O3rYWmhnFs:-0taTpLJK0g:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=6O3rYWmhnFs:-0taTpLJK0g:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/6O3rYWmhnFs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/07/04/workplace-instant-messaging-etiquette/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>LINQ Talk from Queensland MSDN User Group</title>
		<link>http://www.i-think22.net/archives/2009/05/07/linq-talk-from-queensland-msdn-user-group/</link>
		<comments>http://www.i-think22.net/archives/2009/05/07/linq-talk-from-queensland-msdn-user-group/#comments</comments>
		<pubDate>Wed, 06 May 2009 20:23:52 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/?p=261</guid>
		<description><![CDATA[Last month I did a talk on LINQ at the Queensland MSDN User Group. For your viewing pleasure the talk is available on Live Meeting. Check it out here:
LINQ: Powerful Stuff (QMSDNUG)
You may need to skip the first 5 minutes.
Slides are available here: http://linq.i-think22.net/LinqApril2009.pdf
Demos will be available soon.
]]></description>
			<content:encoded><![CDATA[<p>Last month I did a talk on LINQ at the Queensland MSDN User Group. For your viewing pleasure the talk is available on Live Meeting. Check it out here:</p>
<p><a href="https://www112.livemeeting.com/cc/microsoft/view?cn=&#038;id=59CJFS&#038;pw=">LINQ: Powerful Stuff (QMSDNUG)</a></p>
<p>You may need to skip the first 5 minutes.</p>
<p>Slides are available here: <a href="http://linq.i-think22.net/LinqApril2009.pdf">http://linq.i-think22.net/LinqApril2009.pdf</a></p>
<p>Demos will be available soon.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=GOrrD6OqHX4:TcZGlJ5BIgM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=GOrrD6OqHX4:TcZGlJ5BIgM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=GOrrD6OqHX4:TcZGlJ5BIgM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=GOrrD6OqHX4:TcZGlJ5BIgM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=GOrrD6OqHX4:TcZGlJ5BIgM:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/GOrrD6OqHX4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/05/07/linq-talk-from-queensland-msdn-user-group/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing XML with XElement</title>
		<link>http://www.i-think22.net/archives/2009/02/27/writing-xml-with-xelement/</link>
		<comments>http://www.i-think22.net/archives/2009/02/27/writing-xml-with-xelement/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 22:39:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/27/writing-xml-with-xelement/</guid>
		<description><![CDATA[In my last post we looked at how you can use LINQ to XML and XElement to parse XML. But what if you want to create XML files programmatically? Or modify an existing XML document?
Let&#8217;s start by looking at how we might add a new entry to our blog. Here is the XML file again:
&#60;?xml [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post we looked at <a href="http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/">how you can use LINQ to XML and XElement to parse XML</a>. But what if you want to create XML files programmatically? Or modify an existing XML document?</p>
<p>Let&#8217;s start by looking at how we might add a new entry to our blog. Here is the XML file again:</p>
<pre class="prettyprint">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;Blog&gt;
   &lt;Entries&gt;
      &lt;Entry Archived="false"&gt;
         &lt;Title&gt;My First Post&lt;/Title&gt;
         &lt;Body&gt;I love LINQ. It's the best&lt;/Body&gt;
         &lt;Comments&gt;
            &lt;!-- TODO: Shouldn't comments have authors? --&gt;
            &lt;Comment&gt;I love LINQ more&lt;/Comment&gt;
            &lt;Comment&gt;LINQ is the way of the future.&lt;/Comment&gt;
         &lt;/Comments&gt;
      &lt;/Entry&gt;
   &lt;/Entries&gt;
&lt;/Blog&gt;</pre>
<p>So we want to add a new Entry under the Entries element. We&#8217;ll also assume that our XML file has been parsed into an <code class="prettyprint">XElement</code> variable <code class="prettyprint">blog</code>.</p>
<p>We&#8217;ll start by creating our entry first:</p>
<pre class="prettyprint">var entry = new XElement("Entry");
entry.SetAttributeValue("Archived", false);
entry.Add(new XElement("Title", "My Second Post"));
entry.Add(new XElement("Body", "Just a quick post."));
entry.Add(new XElement("Comments"));</pre>
<p>We started by creating the element, set the &#8220;Archived&#8221; attribute, then added the other necessary elements. I&#8217;ve still added the Comments element even though it will be empty. Depending on the rules that have been set about how I should layout the XML it might be optional.</p>
<p>To check that my code worked I plugged it into <a href="http://www.linqpad.net/">LINQPad</a> and dumped the value of entry like so:</p>
<pre class="prettyprint">entry.ToString().Dump();</pre>
<p>The results showed me the following:</p>
<pre class="prettyprint">&lt;Entry Archived="false"&gt;
   &lt;Title&gt;My Second Post&lt;/Title&gt;
   &lt;Body&gt;Just a quick post.&lt;/Body&gt;
   &lt;Comments /&gt;
&lt;/Entry&gt;
</pre>
<p>Wow, that&#8217;s exactly what we want. Even though we used a <code class="prettyprint">Boolean</code> value instead of a <code class="prettyprint">String</code> for the attribute, <code class="prettyprint">XElement</code> was smart enough to display its value as a human readable string. The XML is also nicely formatted and readable. I added the call to <code class="prettyprint">ToString()</code> to emphasise that it wasn&#8217;t LINQPad that was responsible for the improved formatting.</p>
<p>What we have done here is generate an XML fragment. Sometimes it is easier to think of large XML files as smaller fragments that can be handled independently.</p>
<p>So now all we have to do is find the Entries element and add our <code class="prettyprint">entry</code> <code class="prettyprint">XElement</code> to it like so.</p>
<pre class="prettyprint">blog.Element("Entries").Add(entry);</pre>
<p>This will leave us with the final XML looking like this:</p>
<pre class="prettyprint">&lt;Blog&gt;
   &lt;Entries&gt;
     &lt;Entry Archived="false"&gt;
       &lt;Title&gt;My First Post&lt;/Title&gt;
       &lt;Body&gt;I love LINQ. It's the best&lt;/Body&gt;
       &lt;Comments&gt;
         &lt;!-- TODO: Shouldn't comments have authors? --&gt;
         &lt;Comment&gt;I love LINQ more&lt;/Comment&gt;
         &lt;Comment&gt;LINQ is the way of the future.&lt;/Comment&gt;
       &lt;/Comments&gt;
     &lt;/Entry&gt;
     &lt;Entry Archived="false"&gt;
       &lt;Title&gt;My Second Post&lt;/Title&gt;
       &lt;Body&gt;Just a quick post.&lt;/Body&gt;
       &lt;Comments /&gt;
     &lt;/Entry&gt;
   &lt;/Entries&gt;
&lt;/Blog&gt;</pre>
<h3>What about our XML declaration?</h3>
<p>You might be wondering why the <code class="prettyprint">ToString()</code> method of <code class="prettyprint">XElement</code> doesn&#8217;t include the XML declaration. Because XElement represents a fragment of XML which could appear anywhere in an XML document. If it included the XML declaration it would lose this flexibility. However there is a workaround if you are outputting to a final file.</p>
<pre class="prettyprint">var blogDump = new StringBuilder();
blog.Save(new StringWriter(blogDump));</pre>
</p>
<p>The <code class="prettyprint">Save()</code> method on <code class="prettyprint">XElement</code> automatically adds an appropriate XML declaration, which is probably a good idea as it sorts out the complicated things like the encoding and XML version (which I&#8217;ve never seen as anything other than 1.0 to date). The <code class="prettyprint">Save()</code> method can take either the name of a file (as a <code class="prettyprint">String</code>), an <code class="prettyprint">XmlWriter</code> or <code class="prettyprint">TextWriter</code>. In the example above I&#8217;ve used a <code class="prettyprint">StringWriter</code> (which is a subclass of <code class="prettyprint">TextWriter</code>) to save XML to a <code class="prettyprint">StringBuilder</code> object which I could then use to build a string containing the XML. <code class="prettyprint">Save()</code> also takes a second parameter, <code class="prettyprint">SaveOptions</code> which allows you to save your XML file without the extra whitespace that I&#8217;ve shown above. If you want to save those bytes it might be worth looking at this option.</p>
<h3>Where do we go from here?</h3>
<p>I haven&#8217;t yet decided what my next LINQ post will cover (although LINQ to Entities is high on the agenda), so I won&#8217;t promise anything here now. I have much more to say still about LINQ, so feel free to post in the comments suggestions for areas to cover in future posts and the areas you would like to see covered in more detail. So far this has been fairly introductory and we&#8217;ll be building towards more advanced topics over the coming weeks.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=1JvUQTZ75T0:6zJYpDdG9fk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=1JvUQTZ75T0:6zJYpDdG9fk:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=1JvUQTZ75T0:6zJYpDdG9fk:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=1JvUQTZ75T0:6zJYpDdG9fk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=1JvUQTZ75T0:6zJYpDdG9fk:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/1JvUQTZ75T0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/27/writing-xml-with-xelement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML Made Easy with LINQ to XML</title>
		<link>http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/</link>
		<comments>http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 22:58:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/</guid>
		<description><![CDATA[XML is a fantastic way to structure information. Here are the two things I like most about XML.

It&#8217;s fundamental concepts are simple, making many XML files readable by regular humans.  
The formalised structure enables re-use of a more generalised XML parser.

Projects can certainly suffer from too much XML or XML is used when a [...]]]></description>
			<content:encoded><![CDATA[<p>XML is a fantastic way to structure information. Here are the two things I like most about XML.</p>
<ol>
<li>It&#8217;s fundamental concepts are simple, making many XML files readable by regular humans.  </li>
<li>The formalised structure enables re-use of a more generalised XML parser.</li>
</ol>
<p>Projects can certainly suffer from too much XML or XML is used when a better option exists. Once your XML files become too difficult to read in a text editor it may be better to look at another option (or better design your XML schema).</p>
<h3>A lightning fast introduction to XML</h3>
<p>Skip this section if you already know XML, but take time to look at this XML sample as it will be used throughout the article.</p>
<pre class="prettyprint">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;Blog&gt;
   &lt;Entries&gt;
      &lt;Entry Archived="false"&gt;
         &lt;Title&gt;My First Post&lt;/Title&gt;
         &lt;Body&gt;I love LINQ. It's the best&lt;/Body&gt;
         &lt;Comments&gt;
            &lt;!-- TODO: Shouldn't comments have authors? --&gt;
            &lt;Comment&gt;I love LINQ more&lt;/Comment&gt;
            &lt;Comment&gt;LINQ is the way of the future.&lt;/Comment&gt;
         &lt;/Comments&gt;
      &lt;/Entry&gt;
   &lt;/Entries&gt;
&lt;/Blog&gt;</pre>
<p>Above is an example of a simple XML file. XML files follow a structured pattern called a <strong>schema</strong>. The schema defines the rules for what is allowed where and generally defines the structure of your file. Fortunately you don&#8217;t need to write a formal schema to get started with XML. Instead you can just start laying out your data. That&#8217;s where the &#8220;X&#8221; in XML comes from, because it is <strong>eXtensible</strong>.</p>
<p>So the sample XML above is being used to store the contents of a simple blog. XML isn&#8217;t the best way to do this, but a blog is a simple well understood concept. If you read my article on <a href="http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/">LINQ to SQL</a> you might notice that this is very similar to the database example I used there.</p>
<p>Every XML document <em>should</em> start with what is known as an <strong>XML declaration</strong>. It&#8217;s in the first line of the XML and defines the version of the XML as well as the encoding of the file. If you are using notepad you can select the encoding when you save the file. The topic of encodings is out of the scope of this article.</p>
<p>The next important element that all XML files need is a <strong>root node</strong>. In this example our root node is called &#8220;Blog&#8221; and it holds all of our other elements. There can only be one root node in an XML document so if we wanted another blog we would have to put it in another XML file or redesign our XML to have a new root node (such as BlogCollection).</p>
<p>From there we can see that our XML document is made up of two key parts, elements and attributes. <strong>Elements</strong> are the things in angle brackets (called <strong>tags</strong>) and an element continues until it is closed with a matching closing tag. <strong>Closing tags</strong> are different from regular tags as they have a forward slash (/) before the name of the tag. We will use the term element to describe everything from the opening tag (a regular tag) to the closing tag, and a tag as the bit with the angle brackets.</p>
<p>There is also a special kind of tag called a <strong>self-closing tag</strong> that is both an opening tag and a closing tag. These tags have a forward slash before the closing angle bracket. For example:</p>
<pre class="prettyprint">&lt;SelfClosingTag /&gt;</pre>
</p>
<p>The space before the forward slash is optional (and stems back to compatibility with HTML). Personally I like keeping the space there, but your project may have different rules.</p>
<p>The other important concept is attributes. <strong>Attributes</strong> go inside the tag to provide more information about a tag. Attributes can only be used once per element (but one element can have multiple attributes). In the example above, we have given the entry tag the Archived attribute.</p>
<p>Sometimes it can be difficult to determine whether data should be expressed as an attribute or as a <strong>child element</strong> (an element inside another element). Typically the rule of thumb is that an attribute should be describing metadata, that is extra information about the element itself and how it might be interpreted. Occasionally this doesn&#8217;t clear things up at all. If you are still confused, consider the complexity of the data and whether multiple instances of the data will be required. Complex and repeating data is a sure sign that you want to use an element.</p>
<p>Importantly elements can contain other elements which can in turn contain more elements (and so on). XML follows a very strict hierarchy (which makes it easy to navigate) so an element must be closed inside the element that it was opened in. This means that any element (except the root node of course) has one and only one <strong>parent element</strong>. If you are modelling structured data it is unlikely you&#8217;ll run into troubles.</p>
<p>Finally I&#8217;ve also added a comment to remind me to add authors to the comments. We won&#8217;t actually be doing this, it was merely there to demonstrate how you can include <strong>comments</strong> in your XML documents. Comments should be ignored when parsing an XML file as they are unrelated to the data. Comments begin with <code class="prettyprint">&lt;!--</code> and end with <code class="prettyprint">--&gt;</code>.</p>
<p>Ok, so by now you should know enough about XML to understand how we can parse this XML file and pull the necessary elements.</p>
<h3>Now for the exciting stuff</h3>
<p>LINQ to XML is a set of classes designed to work well with LINQ. It provides a very simple API that allows XML to be read and written with ease.</p>
<p>The centre of your LINQ to XML world is <code class="prettyprint">XElement</code>. Through <code class="prettyprint">XElement</code> we can access all of the important information in the sample above. Let&#8217;s start by writing a query that can help us get the Blog entries to display on the front page. We&#8217;ll assume I&#8217;ve loaded the XML as a string into a variable called <code class="prettyprint">blogXml</code>.</p>
<pre class="prettyprint">var blog = XElement.Parse(blogXml);

var frontPage = from e in blog.Descendants("Entry")
                where e.Attribute("Archived").Value == "false"
                select e;

foreach (var entry in frontPage)
{
   WriteBlogTitle(entry.Element("Title").Value);
   WriteBlogBody(entry.Element("Body").Value);
   WriteBlogCommentCount(entry.Descendants("Comment").Count());
}</pre>
</p>
<p>This example does absolutely no error checking (something you&#8217;ll definitely want to do if you are working with real XML) but demonstrates how simple it is to find particular elements inside XML. Additionally you can use <code class="prettyprint">XElement</code> objects to pass XML fragments around your application. We could have made our LINQ query return an anonymous type that pulled out the Title, Body and Comment count for each entry, but instead we just pulled out the <code class="prettyprint">XElement</code> itself. From there we were able count the comments inside our loop. </p>
<p>There is nothing preventing you from using these fantastic classes without having to use LINQ queries as well. In fact, most of the XML parsing code I&#8217;ve written lately doesn&#8217;t use LINQ queries at all to find elements, just the methods of the XElement class. Let&#8217;s look at the ones you&#8217;ll likely use most. Don&#8217;t worry that these parameters take an XName as their parameter, strings are automatically cast to a XName. You&#8217;ll need to use XName if you are dealing with namespaces (which I&#8217;ll discuss in a future post).</p>
<ul>
<li><code class="prettyprint"><strong>Element(XName name)</strong></code> returns the first <strong>immediate</strong> child element with the given name. If the element does not exist it returns <code class="prettyprint">null</code>.
</li>
<li><code class="prettyprint"><strong>Elements()</strong></code> returns an <code class="prettyprint">IEnumerable&lt;XElement&gt;</code> of all the <strong>immediate</strong> child elements. So against Blog the enumeration would yield a single &#8220;Entries&#8221; <code class="prettyprint">XElement</code>. If there are no child elements the enumeration will be empty.
</li>
<li><code class="prettyprint"><strong>Elements(XName name)</strong></code> returns an <code class="prettyprint">IEnumerable&lt;XElement&gt;</code> of all the <strong>immediate</strong> child elements with the given name. If no elements with the name exist it will return an empty enumeration.
</li>
<li><code class="prettyprint"><strong>Attribute(XName name)</strong></code> returns an <code class="prettyprint">XAttribute</code> that is the attribute with the specified name. If the attribute does not exist it returns <code class="prettyprint">null</code>.</li>
</ul>
<p>To match the <code class="prettyprint">Element()</code> and <code class="prettyprint">Elements()</code> methods there are also a set of <code class="prettyprint">Descendant()</code> and <code class="prettyprint">Descendants()</code> methods. These work in the same way except that they return all elements under the node. We used this method when we were finding the Entry element as we didn&#8217;t care about the rest of the document&#8217;s hierarchy.</p>
<p>Because these methods return null if the element (or attribute) is not found it is important to check that the value is not null unless you are using a method which returns an <code class="prettyprint">IEnumerable&lt;T&gt;</code> object.</p>
<h3>Where to from here?</h3>
<p>You now know all the important classes needed to parse XML files (perhaps to load up some strongly typed objects). In my next post I&#8217;ll be discussing how you can use this same class to build complex XML structures. In the meantime, check out the <a href="http://msdn.microsoft.com/">MSDN</a> documentation for <code class="prettyprint">XElement</code>.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=Ip75GG55lW4:udR7PigUWGw:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=Ip75GG55lW4:udR7PigUWGw:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=Ip75GG55lW4:udR7PigUWGw:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=Ip75GG55lW4:udR7PigUWGw:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=Ip75GG55lW4:udR7PigUWGw:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/Ip75GG55lW4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Introduction to LINQ to SQL</title>
		<link>http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/</link>
		<comments>http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 23:23:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/</guid>
		<description><![CDATA[So we already know that LINQ gives us a way to compose queries against IEnumerable&#60;T&#62; objects. LINQ to SQL gives us a way to describe our database so that we can use LINQ queries against the data and have LINQ to SQL generate the necessary SQL statements to get the results. With LINQ to SQL [...]]]></description>
			<content:encoded><![CDATA[<p>So we already know that LINQ gives us a way to compose queries against <code class="prettyprint">IEnumerable&lt;T&gt;</code> objects. LINQ to SQL gives us a way to describe our database so that we can use LINQ queries against the data and have LINQ to SQL generate the necessary SQL statements to get the results. With LINQ to SQL you can query, insert and delete data all with fully compiled LINQ queries. Although LINQ to SQL will take a back seat to the Entity Framework (I&#8217;ll cover that in a future post) according to the ADO.Net team blog&#8217;s &#8220;<a href="http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx">Update on LINQ to SQL and LINQ to Entities Roadmap</a>&#8220;, LINQ to SQL remains a good simple way to set up a database.</p>
<p>I&#8217;ll just be covering the core concepts here. Each of these core concepts will still apply to LINQ to Entities although there are sure to be small differences.</p>
<h3></h3>
<h3>Basic structure</h3>
<p>In Visual Studio LINQ to SQL comes with a full designer experience. You&#8217;ll find &#8220;LINQ to SQL Classes&#8221; as an item under &#8220;Data&#8221; in the Add New Item dialog. Keep in mind that &#8220;DataContext&#8221; will be added to the end of the name you give. I&#8217;ve created many TestDataDataContext classes!</p>
<p>Once this item has been added you will be presented with a designer window. Assuming you are using a SQL Server or SQL Express database you can simply drag tables from the Server Explorer to the designer window (I&#8217;ll be discussing the tool <code>sqlmetal.exe</code> in a future post which can be used to get LINQ to SQL working with SQL Server Compact Edition). As you add more tables, the relationships will begin to appear. Dragging all these tables simply generates extra classes under the scenes. There are four important files that are part of the LINQ to SQL classes:</p>
<ul>
<li><strong>TestDataContext.dbml</strong> is the core file. It is an XML formatted file that describes the tables and relationships in your Data Context.  </li>
<li><strong>TestDataContext.dbml.layout</strong> is purely for the designer experience so that you can lay out your tables in a way that makes sense to you.  </li>
<li><strong>TestDataContext.designer.cs</strong> is where things get interesting. This is the file that contains all the classes that are generated from your .dbml file. These are partial classes so you can add extra methods and properties in a separate file.  </li>
<li><strong>TestDataContext.cs</strong> is the file where you put your extra methods and properties.</li>
</ul>
<p>Each of the tables is represented as a class in your object model. The fields of the tables become the properties and relationships are also represented as properties. It is important to remember that the classes represent a single row from the database.</p>
<p>In addition to the classes representing your data model you also get a DataContext class (in this example TestDataContext) which you use to interact with your database. It has a property for each of your tables which are of type <code class="prettyprint">System.Data.Linq.Table&lt;T&gt;</code> where <code class="prettyprint">T</code> is the name of your class. So if you have a table of Users, you might call the class User (as it represents one user) and your DataContext would have a property Users of type <code class="prettyprint">System.Data.Linq.Table&lt;User&gt;</code>.</p>
<h3>Initialize your DataContext</h3>
<p>All access to your data is done through the DataContext object. Before you can begin you&#8217;ll need to create an instance of the class. If you&#8217;ve used Visual Studio to connect to SQL Server or SQL Express database you probably have access to the default constructor which will use the connection string from your app.config file. If you&#8217;ve used <code>sqlmetal.exe</code> or if you want to manually specify a connection string you can use a simple constructor that just takes the connection string.</p>
<p>In the next examples, we&#8217;ll assume we have already initialized the data context using the connection string from app.config like so:</p>
<pre class="prettyprint">var db = new TestDataContext();</pre>
<h3>Query the database (<code class="prettyprint">SELECT</code>)</h3>
<p>Let&#8217;s start with a simple query to pull data from the database. Let&#8217;s say that we have a really simple blog with the following tables: Entries, Comments and Users. We&#8217;ll be using this same basic database through all of the following examples.</p>
<p>Let&#8217;s start with the front page. Because this is a simple blog all the posts will stay on the front page until we archive them. So we want to start by finding all the blog posts that haven&#8217;t been archived. Let&#8217;s start by looking at the raw SQL.</p>
<pre class="prettyprint">SELECT *
FROM Entries
WHERE e.Archived = 0</pre>
<p>That&#8217;s a pretty simple query and in LINQ it is also simple:</p>
<pre class="prettyprint">var frontPage = from e in db.Entries
                where !e.Archived
                select e;</pre>
<p>Again, this is just our query definition, this line of code will not execute the query against the database. To actually execute the query we need to do something like this:</p>
<pre class="prettyprint">foreach (var entry in frontPage)
{
   WriteBlogTitle(entry.Title);
   WriteBlogBody(entry.Body);
   // TODO: Show number of comments
}</pre>
<p>Here <code class="prettyprint">WriteBlogTitle()</code> and <code class="prettyprint">WriteBlogBody()</code> methods are responsible for sending the output to the web browser. Both methods just take a <code class="prettyprint">string</code> and are completely unaware of where the data is coming from.</p>
<p>I&#8217;ve included a TODO comment suggesting it might be good to show the number of comments for each entry. First I&#8217;ll show you how to do this by running an extra query for each entry:</p>
<pre class="prettyprint">foreach (var entry in frontPage)
{
   WriteBlogTitle(entry.Title);
   WriteBlogBody(entry.Body);
   WriteBlogCommentCount(entry.Comments.Count);
}</pre>
</p>
<p>Because comments are associated with the entry we can directly access its count. This line will cause another database query so has obvious performance implications (as it needs to hit the database server for every single post). Instead we&#8217;ll rewrite the query so we pull everything we need from the database in one query.</p>
<pre class="prettyprint">var frontPage = from e in db.Entries
                where !e.Archived
                select new {
                              Entry = e,
                              CommentCount = e.Comments.Count
                           };

foreach (var post in frontPage)
{
   WriteBlogTitle(post.Entry.Title);
   WriteBlogBody(post.Entry.Body);
   WriteBlogCommentCount(post.CommentCount)
}</pre>
<p>By creating a new anonymous type in the query we send one complex query to the database instead of lots of simple queries.</p>
<p>So what if a user actually wants to view those comments. This time we&#8217;ll accept that two database queries is acceptable (it&#8217;s a constant). So, let&#8217;s see how that might work for a page that displays a specific post.</p>
<pre class="prettyprint">var post = (from e in db.Entries
            where e.Id == id
            select e).FirstOrDefault();

if (post == null)
{
   // Post could not be found
   throw new ArgumentException();
}

WriteBlogTitle(post.Title);
WriteBlogBody(post.Body);

foreach (var comment in post.Comments)
{
   WriteBlogComment(comment.Comment);
}</pre>
<p>It almost seems to easy to believe. Because the relationships are already defined LINQ to SQL is able to generate the second SQL statement to get each of the comments for that post. Most importantly we did all this without any strings!</p>
<h3>Inserting data (<code class="prettyprint">INSERT</code>)</h3>
<p>Right now the blog is pretty boring, it can display posts and comments, but how do the posts and comments get there?&nbsp; Let&#8217;s start with the simple example of creating a post.</p>
<pre class="prettyprint">var post = new Entry();

post.Title = "My first post";
post.Body = "I love LINQ. It's the best.";

db.Entries.InsertOnSubmit(post);
db.SubmitChanges();</pre>
</p>
<p>That&#8217;s it. The post is now in the database. What about a comment?</p>
<pre class="prettyprint">var comment = new Comment();

comment.Comment = "I love LINQ more";
comment.Entry = post;

db.Comments.InsertOnSubmit(comment);
db.SubmitChanges();</pre>
</p>
<p>We&#8217;ve been able to link the comment to the post by using the Entry property directly. We haven&#8217;t had to worry about how our tables are related in our code.</p>
<h3>Deleting data (<code class="prettyprint">DELETE</code>)</h3>
<p>Did you get a spam comment on your blog? Don&#8217;t worry, LINQ to SQL can help you delete it. It follows a similar model to that of inserting data.</p>
<pre class="prettyprint">db.Comments.DeleteOnSubmit(comment);
db.SubmitChanges();</pre>
<h3>Updating data (<code class="prettyprint">UPDATE</code>)</h3>
<p>Maybe you want to start cleaning up the front page because it is starting to get cluttered. We need to update the Archived field on each of the entries we want to archive. To keep things really simple, we&#8217;ll archive all the posts that aren&#8217;t already archived.</p>
<pre class="prettyprint">var toArchive = from e in db.Entries
                where !e.Archived
                select e;

foreach (var entry in toArchive)
{
   entry.Archived = true;
}

db.SubmitChanges();</pre>
<h3>Remember to submit your changes</h3>
<p>The key thing to remember when manipulating data with LINQ to SQL is to call <code class="prettyprint">SubmitChanges()</code> on your DataContext object. Only then will the SQL statements be generated and executed on the server.</p>
<h3>What&#8217;s next?</h3>
<p>In my next LINQ post I&#8217;ll be exploring LINQ to XML.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=hCYPJV8kJa8:uXVhUp1sO_A:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=hCYPJV8kJa8:uXVhUp1sO_A:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=hCYPJV8kJa8:uXVhUp1sO_A:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=hCYPJV8kJa8:uXVhUp1sO_A:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=hCYPJV8kJa8:uXVhUp1sO_A:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/hCYPJV8kJa8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Turning off UAC</title>
		<link>http://www.i-think22.net/archives/2009/02/23/turning-off-uac/</link>
		<comments>http://www.i-think22.net/archives/2009/02/23/turning-off-uac/#comments</comments>
		<pubDate>Sun, 22 Feb 2009 23:06:15 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[i-think IT]]></category>
		<category><![CDATA[vista]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/23/turning-off-uac/</guid>
		<description><![CDATA[Recently I was setting up a workstation and decided to turn off UAC while finalizing things. Having always worked with UAC on, the absence of confirmation dialogs was brilliant. So whilst I still think UAC is generally a good idea, there are definitely circumstances where it not only can be turned off, but should. If [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was setting up a workstation and decided to turn off UAC while finalizing things. Having always worked with UAC on, the absence of confirmation dialogs was brilliant. So whilst I still think UAC is generally a good idea, there are definitely circumstances where it not only can be turned off, but should. If setting up applications and tweaking system settings is something you need to do regularly and you know what you are doing turning UAC off is a great way to save your sanity.</p>
<p>When I turned UAC off for the first time I thought the possible conversation between Maxwell Smart and the Chief on the topic:</p>
<p>The Chief: Max, turning off UAC will mean your processes will execute with your full privileges. You&#8217;ll be in constant danger of malware, viruses and trojans.</p>
<p>Max: And loving it.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=pSjP9ZYX8Jk:SqkxwHYTZuI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=pSjP9ZYX8Jk:SqkxwHYTZuI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=pSjP9ZYX8Jk:SqkxwHYTZuI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=pSjP9ZYX8Jk:SqkxwHYTZuI:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=pSjP9ZYX8Jk:SqkxwHYTZuI:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/pSjP9ZYX8Jk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/23/turning-off-uac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visual Studio, .NET and Developer Productivity</title>
		<link>http://www.i-think22.net/archives/2009/02/22/visual-studio-net-and-developer-productivity/</link>
		<comments>http://www.i-think22.net/archives/2009/02/22/visual-studio-net-and-developer-productivity/#comments</comments>
		<pubDate>Sun, 22 Feb 2009 00:24:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[i-think IT]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[vstudio]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/22/visual-studio-net-and-developer-productivity/</guid>
		<description><![CDATA[Recently I&#8217;ve had to work on porting a .NET app to Ruby. The .NET version consumed WCF web services, exposed WCF web services, parsed XML and relied on multiple threads. The experience reminded me of one thing: the awesomeness of .NET and Visual Studio.
.NET&#8217;s documentation is pervasive
.NET seems to have been designed from the start [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I&#8217;ve had to work on porting a .NET app to Ruby. The .NET version consumed WCF web services, exposed WCF web services, parsed XML and relied on multiple threads. The experience reminded me of one thing: the awesomeness of .NET and Visual Studio.</p>
<h3>.NET&#8217;s documentation is pervasive</h3>
<p>.NET seems to have been designed from the start to encourage excellent documentation. With XML documentation all the important parts of a method and a class are able to be encapsulated. Using a tool like <a href="http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/">GhostDoc</a> (which is free) a skeleton for the documentation can be written for you.</p>
<p>In Visual Studio as you code you are constantly presented with relevant documentation as you code. If you need more help you can press F1 to be taken to the relevant page from the <a href="http://msdn.microsoft.com/">MSDN</a> library.</p>
<h3>The .NET Framework is generally well laid out</h3>
<p>I&#8217;m sure someone can come up with an exception, but generally the .NET framework is well laid out. IO functions can be found in System.IO, Windows form controls sit in System.Windows.Forms. Knowing where to look for things goes a long way to improving the discovery of methods and types leading to a less steep learning curve.</p>
<p>It also serves well for discussions. If you want to working with XML you can be told to check the classes in System.Xml. Want to check out the new LINQ to XML classes, they are sitting in System.Xml.Linq, right under the System.Xml namespace.</p>
<h3>The .NET Framework has consistent naming</h3>
<p>Classes and method names have consistent case rules that make it easy to work in a case-sensitive environment. Consistent use of prefixes (like &#8216;I&#8217; for Interface) and suffixes (like &#8216;Exception&#8217; for exceptions) helps developers identify the purpose of a class without looking deeper. Fortunately Visual Studio makes looking deeper easy. <a href="http://msdn.microsoft.com/en-us/library/ms229042.aspx">Design guidelines for developing class libraries</a> encourage developers to stick with this consistent approach. Furthermore, tools like <a href="http://code.msdn.microsoft.com/sourceanalysis">StyleCop</a> and <a href="http://go.microsoft.com/fwlink/?LinkId=70294">FxCop</a> can help make sure your code is consistent.</p>
<h3>Even the basic documentation is good</h3>
<p>The class documentation on MSDN is generally excellent, but even at its core, just listing the members, constructor overloads and object hierarchy goes a long way to understanding a complex framework. It is well organised (using the namespaces we&#8217;ve already discussed) and easy to navigate.</p>
<p>Working with Ruby&#8217;s documentation really made this apparent. Whilst the ruby docs can have this information I have seen members not listed in documentation, and the three top panes are almost impossible to navigate (from left to right, a list of source files, a list of all classes and modules, and then a list of all members). These lists get so long that it is difficult to scroll to the right spot and even then it can be hard to pick the item you want.</p>
<h3></h3>
<h3>Visual Studio makes it easy to navigate your code</h3>
<p>Enterprise applications are large, so being able to navigate through your own code needs to be as quick and easy as possible. In Visual Studio it is easy to navigate to the declaration of a type or a method. In addition to Visual Studio&#8217;s navigation features I also make use of <a href="http://www.jetbrains.com/resharper/index.html">ReSharper</a> (not free, but so worth it) to navigate to a member, a particular file, references, etc. This ease of navigation improves my productivity greatly.</p>
<h3>Did I mention how much I love IntelliSense?</h3>
<p>Seriously, IntelliSense is the greatest IDE feature ever. It improves the discoverability of classes and methods and reduces errors in code. ReSharper has a handy feature which let&#8217;s me take advantage of camel casing too. I can type &#8216;ArgN&#8217; and still be presented with the option of an <code class="prettyprint">ArgumentNullException</code>. This has saved me a lot of time I would normally spend using the dreaded cursor keys to select the type I want.</p>
<h3>Simple refactoring made easy</h3>
<p>Changing the name of a method or type in Visual Studio is simple. References can be updated to reflect the change. Making a change like this by hand is time consuming and prone to error. Again, tools like ReSharper can take this further.</p>
<h3>The joy of compilation</h3>
<p>Compilers are awesome. Not only do they now do a lot of type inference magic, but they can help identify many of the common little problems that arise in code such as minor typos, invalid syntax and undeclared variables. The C# compiler generally returns good error messages that help identify problems quickly. Some of the errors I saw while running my Ruby port were reasonable and certainly allowed me to solve the problem, but often I would need to go deep into the code before these problems become evident. I needed to make thorough use of unit tests just to be confident that the code was syntactically valid.</p>
<h3>Too much hand holding?</h3>
<p>My experience with Ruby has certainly highlighted my reliance on tools like Visual Studio to help me write my code. At the same time I recognised that I was making fewer errors over time writing all my code in a text editor. Perhaps it is beneficial to code in a text editor from time to time, but for anything with more than a few methods or classes you won&#8217;t see me giving up Visual Studio (and ReSharper) any time soon.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=bXNah9ctXSE:K5Y9MHh1nFY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=bXNah9ctXSE:K5Y9MHh1nFY:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=bXNah9ctXSE:K5Y9MHh1nFY:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=bXNah9ctXSE:K5Y9MHh1nFY:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=bXNah9ctXSE:K5Y9MHh1nFY:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/bXNah9ctXSE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/22/visual-studio-net-and-developer-productivity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Introduction to Lambda Expressions in LINQ</title>
		<link>http://www.i-think22.net/archives/2009/02/21/an-introduction-to-lambda-expressions-in-linq/</link>
		<comments>http://www.i-think22.net/archives/2009/02/21/an-introduction-to-lambda-expressions-in-linq/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 22:33:09 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[lambda]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/21/an-introduction-to-lambda-expressions-in-linq/</guid>
		<description><![CDATA[Lambda expressions are a great way to write simple anonymous delegates in a concise way. Of course you aren&#8217;t limited to simple functions, you can write a full blown method in lambda syntax.
I&#8217;ve already shown some lambda expressions in use when I discussed extensions methods. Here&#8217;s the example:

items.Where(item =&#62; item.Price &#60; 1).Select(item =&#62; item.Name)

There are [...]]]></description>
			<content:encoded><![CDATA[<p>Lambda expressions are a great way to write simple <strong>anonymous delegates</strong> in a concise way. Of course you aren&#8217;t limited to simple functions, you can write a full blown method in lambda syntax.</p>
<p>I&#8217;ve already shown some lambda expressions in use when I discussed <a href="http://www.i-think22.net/archives/2009/02/16/linq-and-extension-methods/">extensions methods</a>. Here&#8217;s the example:</p>
</p>
<pre class="prettyprint">items.Where(item =&gt; item.Price &lt; 1).Select(item =&gt; item.Name)</pre>
</p>
<p>There are two lambda expressions in the above example. They are:</p>
<ol>
<li><code class="prettyprint">item =&gt; item.Price &lt; 1</code>
</li>
<li><code class="prettyprint">item =&gt; item.Name</code></li>
</ol>
<p>These are very simple lambda expressions that take one parameter (<code class="prettyprint">item</code>) and return a result. The type of the parameter and the the type of the result are <strong>inferred</strong> by the compiler allowing us to express what clearly without having to decorate it with types. So each of the expressions really means the following:</p>
<ol>
<li>Take an item and return whether the item&#8217;s price is less than one.
</li>
<li>Take and item and return the item&#8217;s name.</li>
</ol>
<p>Hopefully you can see the basic pattern here. Take what&#8217;s on the left of the lambda operator (<code class="prettyprint">=&gt;</code>), use it in the expression on the right and return the result of the expression.</p>
<p>The important thing to remember with lambdas is that they only declare the function. In the example above the lambda expression is executed within the <code class="prettyprint">Where</code> and <code class="prettyprint">Select</code> methods and is executed once for each item in the enumeration. The <code class="prettyprint">Where</code> method uses the result of the lambda expression to determine if the item should be in the resultant enumeration and the <code class="prettyprint">Select</code> method returns the result on the lambda expression as the member of the enumeration.</p>
<h3><code class="prettyprint">Invoke()</code> made easy</h3>
<p>Lambdas aren&#8217;t restricted to being used just with LINQ, they can be used anywhere that anonymous delegates can be found. One area I&#8217;ve found lambdas increasingly useful is in multi-threaded applications. For example, my <a href="http://www.i-think22.net/archives/2009/01/06/tweet-demo/">Tweet demo</a> uses multiple threads to perform the animation. Consequently I often needed to update the UI from the background thread. Because this isn&#8217;t directly allowed I needed to send the code to the UI thread. Before anonymous delegates I would need to create a full blown method to perform a single task. That&#8217;s a lot of extra work for something that is unlikely to be re-used elsewhere. With anonymous delegates I can define the method inline, which is great, but still uses a lot of extra decoration. Now with lambdas I can finally get to the work of just having my code. Here&#8217;s an example straight from that demo.</p>
<pre class="prettyprint">Dispatcher.BeginInvoke(() =&gt;
                           {
                              info.Text = title;
                              infoContainer.Visibility =
                                 Visibility.Visible;
                              _mutex.Unlock();
                           });</pre>
<p>Perhaps the most interesting part of the code is the use of the <code class="prettyprint">title</code> variable within the lambda expression. In this instance, <code class="prettyprint">title</code> is a local variable within the method that is calling <code class="prettyprint">BeginInvoke()</code>. The anonymous delegate will use this local reference when it is called. You can&#8217;t always get away with this.&nbsp; Fortunately strings are immutable in .NET, so we can be confident that the value will not change. If title was mutable (can be changed) its value could be modified after <code class="prettyprint">BeginInvoke()</code> is called, but before it is used in the lambda expression. This may lead to unexpected results.</p>
<p>This problem isn&#8217;t just isolated to multi-threaded applications (although multi-threaded applications are inherently more unpredictable). Because LINQ queries are not executed until they are enumerated (<a href="http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/">LINQ and Deferred Execution</a>) they are susceptible to the same problems, but fortunately in a more consistent way. So remember to always be wary when using a local variable in a LINQ query.</p>
<h3>Generic Delegates in .NET 3.5</h3>
<p>Version 3.5 of the .NET Framework introduced some new generic delegates designed to cover most cases. In fact, it is unlikely that you will need to define your own delegates unless you need more than four parameters.</p>
<p><strong>The <code class="prettyprint">Action</code> delegates</strong></p>
<p><code class="prettyprint">Action</code> delegates refer to a method that does not return a value (a <code class="prettyprint">void</code> method).</p>
<ul>
<li><code class="prettyprint">Action</code> is non-generic delegate that takes no parameters and does not return a value.
</li>
<li><code class="prettyprint">Action&lt;T&gt;</code> was originally introduced in .NET 2.0. This delegate takes one parameter of type <code class="prettyprint">T</code>.
</li>
<li><code class="prettyprint">Action&lt;T1, T2&gt;</code>, <code class="prettyprint">Action&lt;T1, T2, T3&gt;</code> and <code class="prettyprint">Action&lt;T1, T2, T3, T4&gt;</code> are generic delegates that take two, three and four parameters respectively and do not return a value.</li>
</ul>
<p><strong>The <code class="prettyprint">Func</code> delegates</strong></p>
<p><code class="prettyprint">Func</code> delegates are similar to the Action delegates except that they also return a value. The type of the value is always the last type parameter of the generic delegate.</p>
<ul>
<li><code class="prettyprint">Func&lt;TResult&gt;</code> is a generic delegate that takes no parameters and returns a value of type <code class="prettyprint">TResult</code>.
</li>
<li><code class="prettyprint">Func&lt;T, TResult&gt;</code>, <code class="prettyprint">Func&lt;T1, T2, TResult&gt;</code>, <code class="prettyprint">Func&lt;T1, T2, T3, TResult&gt;</code> and <code class="prettyprint">Func&lt;T1, T2, T3, T4, TResult&gt;</code> are generic delegates that take one, two, three and four parameters respectively and return a value of type <code class="prettyprint">TResult</code>.</li>
</ul>
<h3>What&#8217;s next?</h3>
<p>Next up we&#8217;ll be looking at LINQ to SQL and how it can make accessing and using a database a joy.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=r_nScJyIeGk:9o9zXnd0vok:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=r_nScJyIeGk:9o9zXnd0vok:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=r_nScJyIeGk:9o9zXnd0vok:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=r_nScJyIeGk:9o9zXnd0vok:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=r_nScJyIeGk:9o9zXnd0vok:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/r_nScJyIeGk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/21/an-introduction-to-lambda-expressions-in-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Telstra’s Complaint Process (Part 3)</title>
		<link>http://www.i-think22.net/archives/2009/02/20/telstras-complaint-process-part-3/</link>
		<comments>http://www.i-think22.net/archives/2009/02/20/telstras-complaint-process-part-3/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 21:13:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[The Mill]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[telstra]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/17/telstras-complaint-process-part-3/</guid>
		<description><![CDATA[Finally the email that provoked a more acceptable response.
Thank you for your reply, although &#8220;Our procedure in this type of request is only done through a phone conversation with a consultant&#8221; is not actually an explanation.
Referencing your Complaints Policy on your website (http://www.telstra.com.au/contact/complaints.htm) it appears as though email and even post are perfectly acceptable ways [...]]]></description>
			<content:encoded><![CDATA[<p>Finally the email that provoked a more acceptable response.</p>
<blockquote><p>Thank you for your reply, although &#8220;Our procedure in this type of request is only done through a phone conversation with a consultant&#8221; is not actually an explanation.</p>
<p>Referencing your Complaints Policy on your website (<a href="http://www.telstra.com.au/contact/complaints.htm">http://www.telstra.com.au/contact/complaints.htm</a>) it appears as though email and even post are perfectly acceptable ways to place a complaint. In fact, it even listed a mailing address: Telstra Locked Bag 20026 Melbourne VIC 3001.</p>
<p>I assume that I can send my complaint to this address.<br />If you insist on asking me to call the customer service hotline again I would like to take the option described under the &#8220;If you would like further investigation from Telstra&#8221; section of your complaints policy: &#8220;If you are not satisfied with the resolution or the investigation of your complaint it will be escalated to the next level of management, or a Case Manager in a specialised customer relations area.&#8221; </p>
<p>So yes, I would like this escalated to whatever specialised area is necessary. Being in electronic form it should be straightforward to pass this information on to whatever area necessary (as requested in my original email). I have again attached both of my previous complaint letters to allow you to easily forward my issues on to the relevant areas.  </p>
<p>If I receive another canned response (excluding the initial auto responder email) I will be mailing these complaints as well as another covering letter to the address listed on your complaints policy. I will also be contacting the Telecommunications Industry Ombudsman.  </p>
<p>So please take the actions that I have asked and if you personally can not handle it speak to someone who can. Forwarding a complaint to the necessary area should not be a complicated task and should your procedures prevent that may I say that your procedures are in severe need of re-evaluation.  </p>
<p>Regards,  </p>
<p>Rhys Parry</p>
</blockquote>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=E-iJEUJMPyI:FrMY2B0kVUE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=E-iJEUJMPyI:FrMY2B0kVUE:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=E-iJEUJMPyI:FrMY2B0kVUE:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=E-iJEUJMPyI:FrMY2B0kVUE:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=E-iJEUJMPyI:FrMY2B0kVUE:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/E-iJEUJMPyI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/20/telstras-complaint-process-part-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>LINQ and Deferred Execution</title>
		<link>http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/</link>
		<comments>http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 00:25:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/</guid>
		<description><![CDATA[One of the stumbling blocks on the road to understanding LINQ is deferred execution. The key to getting past this is being able to identify that a query is a definition of what you want, rather than the results themselves.
Here&#8217;s an example of how this works:
var itemsInStock = from item in warehouse.Items
    [...]]]></description>
			<content:encoded><![CDATA[<p>One of the stumbling blocks on the road to understanding LINQ is deferred execution. The key to getting past this is being able to identify that a query is a <strong>definition</strong> of what you want, rather than the <strong>results</strong> themselves.</p>
<p>Here&#8217;s an example of how this works:</p>
<pre class="prettyprint">var itemsInStock = from item in warehouse.Items
                   where item.Quantity &gt; 0;
                   select item;

// Display how many items are in stock
Console.WriteLine("Items in stock: {0}", itemsInStock.Count());

// Add a new item to the warehouse
warehouse.Items.Add(new Item("A new item", 50);

// Display how many items are in stock
Console.WriteLine("Items in stock: {0}", itemsInStock.Count());
</pre>
<p>The second time <code class="prettyprint">itemsInStock.Count()</code> is called it returns the updated count that includes our new item. Instead of executing the query when it is defined, execution is <strong>deferred</strong> until a result is needed (such as iterating over the collection with a <code class="prettyprint">foreach</code> loop, using <code class="prettyprint">ToList()</code> to store the results in a <code class="prettyprint">List&lt;T&gt;</code> or one of the many LINQ extension methods that force an actual result (such as <code class="prettyprint">Count()</code> in this example). This has the added benefit of allowing a query to be extended like so:</p>
<pre class="prettyprint">var lowStock = from item in itemsInStock
               where item.Quantity &lt; 5;
               select item;</pre>
<p>This query can now be used to return items that are in stock, but have less than 5 available units.</p>
<p>Quite often you&#8217;ll want to work with a snapshot of the results from a query. Maybe you are writing a method that returns a particular set of items. In this scenario it may be better to return a list rather than the query itself. By returning a list, the calling code is able to iterate over the result multiple times without the result changing. For example you might implement your method like this:</p>
<pre class="prettyprint">private IEnumerable&lt;Item&gt; GetItemsInStockQuery()
{
   return from item in warehouse.Items
          where item.Quantity &gt; 0
          select item;
}

public List&lt;Item&gt; GetItemsInStock()
{
   return GetItemsInStockQuery().ToList();
}</pre>
<p>Calling code is able to get the information it needs and internally you can directly get access to the query.</p>
<p>Another important thing to remember is that because a query is executed every time you iterate it with a <code class="prettyprint">foreach</code> loop you should use <code class="prettyprint">ToList()</code> if you are repeatedly calling the query and don&#8217;t need the results to be recalculated each time.</p>
<h3>More LINQ to come</h3>
<p>In my next post I&#8217;ll explore lambda expressions.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=B7F3wbGCpAM:R7gHP2qG16A:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=B7F3wbGCpAM:R7gHP2qG16A:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=B7F3wbGCpAM:R7gHP2qG16A:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?a=B7F3wbGCpAM:R7gHP2qG16A:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/i-thinkTwenty-two?i=B7F3wbGCpAM:R7gHP2qG16A:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/i-thinkTwenty-two/~4/B7F3wbGCpAM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
