<?xml version="1.0" encoding="UTF-8"?><!--RSS generated by Windows SharePoint Services V3 RSS Generator on 10/02/2012 15:00:29--><?xml-stylesheet type="text/xsl" href="/blogs/markrendle/_layouts/RssXslt.aspx?List=fa725f3f-509c-437c-80a4-24104cd7103e" version="1.0"?><rss version="2.0"><channel><title>On Coding</title><link>http://www.dotnetsolutions.co.uk/blogs/markrendle</link><description>RSS feed for the Posts list.</description><lastBuildDate>Fri, 10 Feb 2012 15:00:29 GMT</lastBuildDate><generator>SharePoint CKS:EBE</generator><ttl>60</ttl><image><title>On Coding</title><url>http://www.dotnetsolutions.co.uk/blogs/markrendle/_layouts/images/homepage.gif</url><link>http://www.dotnetsolutions.co.uk/blogs/markrendle</link></image><item><title>Functional Alchemy: Making Silverlight synchronous</title><link>http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/2010/06/11/functional-alchemy-making-silverlight-synchronous/</link><guid isPermaLink="False">/blogs/markrendle/archive/2010/06/11/functional-alchemy-making-silverlight-synchronous/</guid><description><![CDATA[<div class="ExternalClass10496C29CEED4BD6B863831CBF0CAE87"><p>Caught <a href="http://blog.jayway.com/2010/06/10/silverlight-prefer-synchronous-web-service-calls/" target="_blank">this article</a> on <a href="http://blog.cwa.me.uk/2010/06/11/the-morning-brew-619/" target="_blank">the Morning Brew</a> today, on making web service calls in Silverlight synchronous (which is fine as long as they're not running on the UI thread). Had a quick look through the code, including <a href="http://www.codeproject.com/KB/silverlight/SynchronousSilverlight.aspx" target="_blank">the CodeProject article</a> which provided the base, and thought it seemed a little complicated.</p>  <p>I've recently discovered that you can use the Reactive Framework extensions to wrap the event-based async pattern and make it synchronous; so far, I've just used it for unit testing, but I thought I'd try to apply it to this situation.</p>  <p>The basic pattern goes like this:</p>  <ul>   <li>Use Observable.FromEvent to get an IObservable from the XyzCompleted event. </li>    <li>Use the ToEnumerable extension method to convert the asynchronous IObservable to a blocking IEnumerable. </li>    <li>Call the XyzAsync method. </li>    <li>Get the First element off the IEnumerable. </li> </ul>  <p>You see, when you create an IEnumerable from an IObservable, and then start to iterate it, it creates an enumerator which blocks on the current thread until it gets an OnNext from the Observable. (Disclaimer: I don't know for sure how it actually does that, I just know that's how it works on the outside. If I was implementing it, I'd probably be using some sort of queuing and polling algorithm.)</p>  <h3>WebClient.DownloadString(Uri uri)</h3>  <p>To start off with, I added an extension method to WebClient which implemented the pattern around DownloadStringAsync/DownloadStringCompleted:</p>  <pre class="code"><span style="color:blue">public static string </span>DownloadString(<span style="color:blue">this </span><span style="color:#2b91af">WebClient </span>webClient, <span style="color:#2b91af">Uri </span>address)
{
    <span style="color:green">// Convert event to blocking IEnumerable
    </span><span style="color:blue">var </span>blocker = <span style="color:#2b91af">Observable</span>.FromEvent&lt;<span style="color:#2b91af">DownloadStringCompletedEventArgs</span>&gt;
        (webClient, <span style="color:#a31515">&quot;DownloadStringCompleted&quot;</span>)
        .SubscribeOnDispatcher()
        .ToEnumerable();

    <span style="color:green">// Call the Async method
    </span>webClient.DownloadStringAsync(address);

    <span style="color:green">// Get the first element off the blocking Enumerable
    </span><span style="color:blue">var </span>eventArgs = blocker.First().EventArgs;

    <span style="color:green">// Throw exception?
    </span><span style="color:blue">if </span>(eventArgs.Error != <span style="color:blue">null</span>)
    {
        <span style="color:blue">throw </span>eventArgs.Error;
    }

    <span style="color:blue">return </span>eventArgs.Result;
}</pre>

<p>That's pretty straightforward.</p>

<h3>Genericising the pattern</h3>

<p>In fact, looked at through functional goggles, there are only four variables: </p>

<ul>
  <li>the object with the Async method on it; </li>

  <li>the name of the Completed event; </li>

  <li>the Async method being invoked; </li>

  <li>the extraction of the actual result from the EventArgs. </li>
</ul>

<p>So we should be able to wrap this pattern up in a helper method with four parameters. And indeed we can:</p>

<pre class="code"><span style="color:blue">public static </span>TResult Execute&lt;TEventArgs, TResult&gt;(<span style="color:blue">object </span>obj,
    <span style="color:blue">string </span>eventName,
    <span style="color:#2b91af">Action</span>&lt;<span style="color:blue">object</span>&gt; asyncMethodInvoker,
    <span style="color:#2b91af">Func</span>&lt;TEventArgs, TResult&gt; resultSelector)
        <span style="color:blue">where </span>TEventArgs : <span style="color:#2b91af">AsyncCompletedEventArgs
</span>{
    <span style="color:green">// Convert event to blocking IEnumerable
    </span><span style="color:blue">var </span>blocker = <span style="color:#2b91af">Observable</span>.FromEvent&lt;TEventArgs&gt;(obj, eventName)
        .SubscribeOnDispatcher()
        .ToEnumerable();

<span style="color:green">    // Use Guid to identify our call </span></pre>

<pre class="code">    <span style="color:blue">var </span>guid = <span style="color:#2b91af">Guid</span>.NewGuid();

    <span style="color:green">// Call the Async method
    </span>asyncMethodInvoker(guid);

    <span style="color:green">// Get our element off the blocking Enumerable
    </span><span style="color:blue">var </span>eventArgs = blocker
        .First(e =&gt; e.EventArgs.UserState.Equals(guid))
        .EventArgs;

    <span style="color:green">// Throw exception?
    </span><span style="color:blue">if </span>(eventArgs.Error != <span style="color:blue">null</span>)
    {
        <span style="color:blue">throw </span>eventArgs.Error;
    }

    <span style="color:green">// Return result from EventArgs
    </span><span style="color:blue">return </span>resultSelector(eventArgs);
}</pre>

<p><a href="http://11011.net/software/vspaste"></a></p>

<p>Woo. OK, we've got two generic parameters, one for the type of EventArgs involved, and one for the final return type. We don't need to know the type of the object which holds the Async method, because we're only using it for the Rx FromEvent call, and that just takes <strong>object</strong>.</p>

<p>We've wrapped up the actual invocation of the Async method in an Action delegate which we can just call; the consumer of this method can include any parameters, such as Uri, in the Action body as closures. But we've added a parameter to the delegate, just an object, for which we're going to supply a Guid to identify the Completed event.</p>

<p>By adding the generic constraint to say we only deal with AsyncCompletedEventArgs and its derivatives, we can handle the exception cases because we know we've got the Error property available to us.</p>

<p>And we can call the supplied Func delegate which takes whatever the actual completed EventArgs is and returns the Result bit of it.</p>

<p>So, you can call this helper method from anywhere to dynamically make any Async Event Pattern synchronous, but it's a bit messy, so I think the better approach is to use it inside an extension method like the WebClient.DownloadString method above. Here's that method reimplemented using the helper method:</p>

<pre class="code"><span style="color:blue">public static string </span>DownloadString(<span style="color:blue">this </span><span style="color:#2b91af">WebClient </span>webClient, <span style="color:#2b91af">Uri </span>address)
{
    <span style="color:blue">return </span><span style="color:#2b91af">Sync</span>.Execute
        &lt;<span style="color:#2b91af">DownloadStringCompletedEventArgs</span>, <span style="color:blue">string</span>&gt;
        (webClient, <span style="color:#a31515">&quot;DownloadStringCompleted&quot;</span>,
         (o) =&gt; webClient.DownloadStringAsync(address, o),
         (e) =&gt; e.Result);
}</pre>

<p> </p>

<p><em>Caveat lector</em>: I've only hacked this together quickly and run a couple of tests, so if you try it and find problems, please let me know.</p></div>]]></description><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DOTNETSOL\SharepointSA</dc:creator><pubDate>Fri, 11 Jun 2010 11:44:34 GMT</pubDate></item><item><title>Azure Table Service REST API, part 1: headers &amp; authentication</title><link>http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/2010/03/18/azure-table-service-rest-api-part-1-headers-amp-authentication/</link><guid isPermaLink="False">/blogs/markrendle/archive/2010/03/18/azure-table-service-rest-api-part-1-headers-amp-authentication/</guid><description><![CDATA[<div class="ExternalClassE1FB675F0C4740D398C5E179ED0CB190"><p><strong>One of the nice things about Microsoft Windows Azure services</strong> is that they have a very well-defined and consistent REST API, meaning that they can be accessed from any language which can formulate an HTTP request; pretty much any language you can realistically expect to build an application in today. So as well as accessing the storage services from .NET/Silverlight CLR (or DLR) languages via the official SDK, you can access them from Rich Internet Applications written in HTML5 and Javascript, or from mobile phone services using Compact Framework, Java, or even Objective-C if you're doing penance for past-life atrocities against entire galaxies.</p>  <p><strong>The only slight catch</strong> is that you have to authenticate the request, which involves some slightly complicated hashing of certain values with certain keys and which, if done in the wrong order, won't work. So I hope here to present a definitively working process for anybody else who is having bother and for me the next time I need to implement this in another language or framework.</p>  <p>Before signing, you need to make sure you've got the request headers right. You will need</p>  <p><strong>There are two levels of signing</strong>: <em>Shared Key, </em>which involves the full set of headers and canonicalized headers and the resource being acted upon; and <em>Shared Key Lite, </em>which involves hashing a subset of headers and the resource being acted upon. We are going to use <em>Shared Key Lite</em>, because it is easier and because it works. Don't feel bad about not using the &quot;real&quot; Shared Key; the <em>.NET Client Library for ADO.NET</em> uses <em>Shared Key Lite</em>, so it must be OK.</p>  <p><strong>The headers you need</strong> to include before signing are:</p>  <ul>   <li>content-length: either the length of the XML body of the request, or 0 if there is no body. </li>    <li>x-ms-date: the current date and UTC time, formatted like this - &quot;Thu, 11 Mar 2010 15:35:12 GMT&quot;. This time must be within the last 15 minutes when Azure processes the request. </li> </ul>  <p><strong>If there is content in the body of the request</strong> then you need a content type header:</p>  <ul>   <li>content-type: application/atom+xml </li> </ul>  <p><strong>If you are doing an Update against a Table entity</strong> (i.e. a PUT request) then you should also include:</p>  <ul>   <li>If-Match: * </li> </ul>  <p>This forces an unconditional update; if you wish for a conditional update, replace &quot;*&quot; with some criteria in <a href="http://msdn.microsoft.com/en-us/library/cc668784(v=VS.90).aspx" target="_blank">the same format you would use for a query</a>.</p>  <p><strong>You are now ready to sign your request.</strong> You will need:</p>  <ul>   <li>The Shared Access Key from your Azure Storage project, which will probably be a base-64 encoded string; </li>    <li>An implementation of the SHA256 algorithm. </li> </ul>  <p><strong>The signing process</strong> involves constructing a Hash-based Message Authentication Code, or HMAC, by hashing together the Shared Access Key and a string made of bits of the request using the SHA256 algorithm. If you are using .NET, you can use <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha256.aspx" target="_blank">System.Security.Cryptography.HMACSHA256</a> to do this quite easily. If you are using something else, it might have a standard library class to handle it. If not, and you need to roll your own, you can find pseudocode describing the HMAC algorithm <a href="http://en.wikipedia.org/wiki/HMAC#Implementation" target="_blank">here</a>.</p>  <p><strong>The string made of bits of the request </strong>is, more accurately:</p>  <ul>   <li>the date as it appears in the x-ms-date header </li>    <li>a newline character (\n, not the CRLF combo) </li>    <li>your account name </li>    <li>the path (and any query parameters) of the REST resource URI </li> </ul>  <p><strong>For example</strong>, for an insert:</p>  <p><font face="Courier New">Thu, 11 Mar 2010 15:35:12 GMT      <br>myazureaccount/mytable</font></p>  <p><strong>or</strong> for a query:</p>  <p><font face="Courier New">Thu, 11 Mar 2010 15:35:12 GMT      <br>myazureaccount/mytable?$filter=(foo eq 'bar')</font></p>  <p><strong>Calculate the HMAC</strong> for this string, convert to Base 64 encoding, and then add it as a header to your request in the form:</p>  <ul>   <li>Authorization: SharedKeyLite myazureaccount:q9324jr0+93qwfk+4ou93r8wsrf89owuj3f== </li> </ul>  <p><strong>Your request is now signed</strong> and good to be accepted by the Windows Azure Table Storage service for the next 15 minutes.</p>  <p>The Blob and Queue services use similar authentication, but with more headers. I haven't yet implemented these services as direct REST calls yet, but when I do I'll post an update.</p>  <p>Part 2 of this series of posts will cover creating the body of requests for Insert and Update operation, and parsing the body of responses for all operations.</p></div>]]></description><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DOTNETSOL\SharepointSA</dc:creator><pubDate>Thu, 18 Mar 2010 15:58:15 GMT</pubDate></item><item><title>RDBMS vs NoSQL</title><link>http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/2010/03/18/rdbms-vs-nosql/</link><guid isPermaLink="False">/blogs/markrendle/archive/2010/03/18/rdbms-vs-nosql/</guid><description><![CDATA[<div class="ExternalClass7B6293D413F14F4FB8ACFD3E06EEB4F6">
<h3></h3>
<p>(Yes, again.)</p>
<p>There's an awful lot of buzz around new-fangled &quot;NoSQL&quot; or &quot;non-relational&quot; databases at the moment. I'm hearing a lot of people asking why they'd choose one of these new-fangled storage models over the relational databases they know and (mostly) like. This post aims to shed some light on the choices available, and to maybe give some guidance if you're trying to make a decision.</p>
<h4>Let's define some terms</h4>
<p>I find it always helps to make sure you're talking about the same thing if you think you might be arguing.</p>
<h4>Relational database management system (RDBMS)</h4>
<p>When I say &quot;relational database&quot;, I'm referring to an application or service which stores information in tables. Tables are divided into columns, and columns have a type, such as integer, date, text etc. The data held in the tables is divided into rows, and each row contains a value (possibly including NULL) for each of the columns. The RDBMS can maintain and enforce &quot;master-detail&quot; relationships between rows in different tables using primary and foreign keys.</p>
<p>The big commercial relational database systems are Microsoft SQL Server and Oracle; the main open-source alternatives are MySQL, PostgreSQL and SQLite.</p>
<h4>New-fangled data stores (NoSQL)</h4>
<p>I'm going to use the term NoSQL to cover everything else, which is a massive generalisation and therefore inevitably inaccurate (several new-fangled data stores actually support a SQL-like syntax). However, in the interests of a bit of clarity, I'll try to outline some of the distinct types here, although the distinctions can be a bit vague.</p>
<p><strong>Key/Value Stores</strong> are the most basic NoSQL databases, and are essentially hashes with disk persistence. In some cases the value is a single binary or text object; in others it is a tuple with named properties, sometimes with searching supported against those properties. These solutions are schema-less: entities within a collection, domain or table may have completely different properties. Microsoft's Azure Table Storage and Amazon's SimpleDB are both cloud-based, pay-as-you-go Key/Value stores. Open-source implementations include BerkeleyDB, MemcacheDB, Redis and TokyoCabinet.</p>
<p><strong>Wide Column, Tabular</strong> or <strong>Column Family Stores</strong> are scalable, distributed systems that support a defined schema for each &quot;table&quot;, but not relationships between tables. Google's BigTable database, which is the storage solution for their AppEngine cloud platform, is a Wide Column store. Open-source alternatives include Cassandra and Hypertable.</p>
<p><strong>Document Stores</strong> work with data structured using Object Notation, usually JSON or BSON. Not to be confused with SharePoint, Domino etc. This format allows complex data structures, including arrays and hashes, to be represented within a single entity that can be retrieved in one read operation; they also often support complex update operations such as adding elements to an array within a document. Some popular Document Stores are CouchDB, MongoDB and Riak.</p>
<p><strong>Object Databases</strong> are superficially similar to Document Stores, but have predefined schema and inheritance hierarchies. In an Object Database, graphs are persisted using pointers between objects rather than by embedding graphs within other graphs. The most popular Object Database is db4o.</p>
<h4>So which is best?</h4>
<p><em>&lt;SocraticDialectic&gt;</em></p>
<p><span style="color:#004080">Hello.</span></p>
<p><span style="color:#400000">Hello.</span></p>
<p><span style="color:#004080">Right, so. Why should I use any of these new-fangled &quot;stores&quot; instead of a relational database?</span></p>
<p><span style="color:#400000">Mu.</span></p>
<p><span style="color:#004080">Beg pardon?</span></p>
<p><span style="color:#400000">I said &quot;mu&quot;. I keep hearing this question, and I submit that the answer is &quot;mu&quot;, which means &quot;your question cannot be answered because it depends on incorrect assumptions.&quot;</span></p>
<p><span style="color:#004080">What incorrect assumption is that?</span></p>
<p><span style="color:#400000">The assumption that the relational database is axiomatically the correct storage solution in all situations, and that the onus is on all other options to prove that they are better.</span></p>
<p><span style="color:#004080">Is that not right then?</span></p>
<p><span style="color:#400000">No, it isn't. Have you heard of <a href="http://c2.com/cgi/wiki?DoTheSimplestThingThatCouldPossiblyWork" target="_blank">doing the simplest thing that could possibly work</a>? Or <a href="http://c2.com/cgi/wiki?YouArentGonnaNeedIt" target="_blank">YAGNI</a>? It's possible to add unnecessary features to a system without coding them yourself. The first thing you should rule out as a storage medium is the file-system.</span></p>
<p><span style="color:#004080">What, text files? Isn't that a bit 1980s?</span></p>
<p><span style="color:#400000">Not at all. Let me ask you a question: what requirements or properties of your application preclude using one or more flat text files to persist your data?</span></p>
<p><span style="color:#004080">I need structured data.</span></p>
<p><span style="color:#400000">What's wrong with tab-delimited, CSV or even fixed-length field files?</span></p>
<p><span style="color:#004080">I need master-detail structured data.</span></p>
<p><span style="color:#400000">In which case, you could use XML, YAML or even JSON. Let's say we're using XML, even though it's quite the worst of those three options.</span></p>
<p><span style="color:#004080">I need details with many masters.</span></p>
<p><span style="color:#400000">You mean lookups? Why on earth would you want to use those?</span></p>
<p><span style="color:#004080">To save space.</span></p>
<p><span style="color:#400000">Right, because storage space is so expensive these days. You can buy a 2-terabyte hard disk and get change from <a href="http://www.google.co.uk/products?hl=en&amp;source=hp&amp;q=2tb hard drive&amp;um=1&amp;ie=UTF-8&amp;sa=N&amp;tab=wf" target="_blank">£120</a> (or <a href="http://www.google.com/products?q=2tb+internal+hard+drive&amp;hl=en&amp;aq=f" target="_blank">$150US</a>). Keeping a gigabyte in the cloud'll cost you 15 cents a month.</span></p>
<p><span style="color:#004080">OK, I don't need to save space. But I still need one copy of each piece of data, so I only have to update it in one place.</span></p>
<p><span style="color:#400000">That's fine, but does that need to be supported by your persistence layer? Are you going to re-read those lookup descriptions every time you pull a record? Add multiple joins to every SELECT statement just to read back those varchar(40) descriptions?</span></p>
<p><span style="color:#004080">As opposed to…?</span></p>
<p><span style="color:#400000">As opposed to reading those lookups into memory once the first time they're needed, and maybe refreshing them in background every now and then if you're in a multi-user smart-client system and they're particularly dynamic, which they're probably not. How often does somebody add a new country to the system? Or a new type of customer, or method of payment, or whatever?</span></p>
<p><span style="color:#004080">OK. I accept that lookups are not a valid reason to use a relational database.</span></p>
<p><span style="color:#400000">Good. So, next requirement or property?</span></p>
<p><span style="color:#004080">I need many-to-many relationships. For example, in my library application, each customer can borrow many books, and each book (over time) can be borrowed by many customers.</span></p>
<p><span style="color:#400000">Well, we're still using XML, so you can have a list of child elements in your customer record detailing the books they've borrowed, and a list of child elements in the book record detailing the customers who have borrowed it.</span></p>
<p><span style="color:#004080">So when somebody borrows a book, I have to update two records? That's bad, isn't it?</span></p>
<p><span style="color:#400000">I don't know; it's your application. Do both records have to get updated in the same split second? Is it likely that another user will do a read that could get inaccurate information while the two updates are happening? Or is it enough that the customer and book records should be <em><a href="http://queue.acm.org/detail.cfm?id=1466448" target="_blank">eventually consistent</a></em> (for a given value of <em>eventually</em>)?</span></p>
<p><span style="color:#004080">But then I'd have to read a bunch of files individually to get the details of those books, or the names of those customers.</span></p>
<p><span style="color:#400000">Not at all.</span></p>
<p><span style="color:#004080">Well how would you display sensible data on the screen? Are you going to cache the entire book catalogue and customer list in memory as well?</span></p>
<p><span style="color:#400000">It's an option. But no, I would probably just decide which details about the book I need in the customer views, and which details about the customer I need in the book views, and then I'd include those details in the child records.</span></p>
<p><span style="color:#004080">You'd duplicate the data?</span></p>
<p><span style="color:#400000">Oh, yes.</span></p>
<p><em>[Shocked gasps from enthralled onlookers]</em></p>
<p><span style="color:#004080">You're mad.</span></p>
<p><span style="color:#400000">Not a bit of it. Books don't change their titles, or authors. Customers don't change their names very often; certainly not so often that it's beyond reason to bulk-update a bunch of book records when they do.</span></p>
<p><span style="color:#004080">So you just duplicate the data?</span></p>
<p><span style="color:#400000">Absolutely. Saves a whole bunch of extra disk reads, and those join tables you keep using in many-to-many relationships, well, let's be honest: they're a kludge, and they're one of the most common causes of performance issues due to volume of data.</span></p>
<p><span style="color:#004080">I remain unconvinced.</span></p>
<p><span style="color:#400000">OK. Let's take your library example. Let's say your library is in a particularly literate part of the world and has 10,000 active customers, and 100,000 books. And let's say that each customer borrows two books a week. After one year, your many-to-many join table has 1,000,000 rows in it. Meanwhile, each of my customers' records have 100 book record keys, titles, author names, publishers, and loan start- and end-dates, and each of my book records have, on average, 10 customer record keys, names, maybe addresses, and loan start- and end-dates. In storage terms, let's say you've used probably 32 bytes per row (two 32-bit keys and two 64-bit date/times, plus overhead), so that's 32MB, plus the same again for indexing. Meanwhile, let's just hazard a guess and say I've used a whole gigabyte with all my duplicated data.</span></p>
<p><span style="color:#004080">Exactly. Look at all that storage you're wasting.</span></p>
<p><span style="color:#400000">My goodness, you're right! That's 0.1% of a £120 hard-disk I've just frittered away! Or nearly $2 a year for the cloud storage.</span></p>
<p><span style="color:#004080">There's no need to be sarcastic.</span></p>
<p><span style="color:#400000">I wasn't; I was being ironic. Anyway, my point is, pulling a customer record and displaying the complete list of books they've borrowed for me is a single read operation; for you it's a three-table join with one of those tables containing a million records for each year your software's been in use.</span></p>
<p><span style="color:#004080">I-</span></p>
<p><span style="color:#400000">Actually, scratch that.</span></p>
<p><span style="color:#004080">Really?</span></p>
<p><span style="color:#400000">Yes, I was wrong.</span></p>
<p><span style="color:#004080">I thought you were.</span></p>
<p><span style="color:#400000">I forgot that you'll have normalised out your book catalogue into a book table with a many-to-many join to an author table, and another many-to-many join to a publisher table, so you've actually got seven tables totalling a few million rows that you need to reference to get the same information that I can get in a single read operation. How's your EXPLAIN output looking, by the way?</span></p>
<p><span style="color:#004080">I'm not sure. What does DEPENDENT SUBQUERY mean?</span></p>
<p><span style="color:#400000">No idea, but it sounds nasty. You can fix it later. You're supposed to be giving me reasons you need a relational database.</span></p>
<p><span style="color:#004080">So I am. OK, well, I need to search the data.</span></p>
<p><span style="color:#400000">Aha! Very good. Much closer. That would be a reason for a database management system, but not necessarily a relational one. There are lots of NoSQL solutions that will let you run queries against your datasets, with varying degrees of performance. I've written queries in MongoDB that run against massive datasets so fast it'd make your eyes bleed.</span></p>
<p><em>[Suddenly, a heavenly light shines down upon the pupil. Or some scales fall from his eyes.]</em></p>
<p><span style="color:#004080">I've been such a fool! I drank the relational database kool-aid and no mistake! Thank you for showing me the error of my ways. I'm going NoSQL all the way for my next project.</span></p>
<p><span style="color:#400000">What? No, wait, come back.</span></p>
<p><span style="color:#004080">Why? I'm convinced. You made your case.</span></p>
<p><span style="color:#400000">No, I haven't. I've just stopped you from being one kind of wrong and you've immediately started being another, completely different, but equally bad kind of wrong.</span></p>
<p><span style="color:#004080">No need to be rude.</span></p>
<p><span style="color:#400000">Sorry. But flat text files and  NoSQL databases aren't the solution to every persistence problem. There are perfectly good reasons to use a SQL database.</span></p>
<p><span style="color:#004080">Such as?</span></p>
<p><span style="color:#400000">You might need the whole ACID thing: Atomicity, Consistency, Isolation and Durability. If your system deals with financial data, or medical records, or other sensitive information, you're going to want a robust transaction system.</span></p>
<p><span style="color:#004080">True.</span></p>
<p><span style="color:#400000">And if you've got a lot of concurrent users who might try to update the same bit of data at the same time, like an entry in a Stock table in an e-commerce system, then isolation and locking could be very handy.</span></p>
<p><span style="color:#004080">And NoSQL systems can't do ACID and locking and so on?</span></p>
<p><span style="color:#400000">Oh, they <em>can</em>, one way or another. But a lot of the time you end up writing extra code in your data access layer to do stuff that a decent RDBMS will do for you. And if you've got a room-full of developers who are dead good with SQL Server or Entity Framework or whatever, why force them to learn a new technology?</span></p>
<p><span style="color:#004080">I <em>would</em> have a hard time justifying the time and money required for our developers to learn the new skills.</span></p>
<p><span style="color:#400000">Then again, in the cloud the NoSQL storage can be much, much cheaper than the RDBMS. For example, Windows Azure storage costs $0.15 per gigabyte per month, whereas a 1GB SQL Azure instance is $9.99 per month; 10GB is $99.99 per month.</span></p>
<p><span style="color:#004080">So Windows Azure storage is cheaper than SQL Azure storage?</span></p>
<p><span style="color:#400000">Not necessarily. With Windows Azure Storage you also pay for transactions, at the rate of $0.01 for every ten thousand. SQL Azure doesn't charge for transactions. So if you're storing less than a gigabyte but running more than ten million transactions per month, SQL Azure would be cheaper. Or if you're storing less than ten gigabytes but running more than a hundred million transactions-</span></p>
<p><span style="color:#004080">Stop! I'm all confused. Please, just tell me, <em>what should I use?</em></span></p>
<p><span style="color:#400000">You want a definite answer?</span></p>
<p><span style="color:#004080">Yes.</span></p>
<p><span style="color:#400000">OK.</span></p>
<p><span style="color:#004080">There really is one?</span></p>
<p><span style="color:#400000">There really is one.</span></p>
<p><span style="color:#004080">And are you going to tell me what it is?</span></p>
<p><span style="color:#400000">I am.</span></p>
<p><span style="color:#004080">Now?</span></p>
<p><span style="color:#400000">Now.</span></p>
<p><span style="color:#004080">Wow.</span></p>
<p><span style="color:#400000">Although I don't think you're going to like it*.</span></p>
<p><span style="color:#004080">It doesn't matter! I must know!</span></p>
<p><span style="color:#400000">Now?</span></p>
<p><span style="color:#004080">Yes, now!</span></p>
<p><span style="color:#400000">Alright.</span></p>
<p><span style="color:#004080">Well?</span></p>
<p><span style="color:#400000">You're really not going to like it.</span></p>
<p><span style="color:#004080">Tell me!</span></p>
<p><span style="color:#400000">The answer is…</span></p>
<p><span style="color:#004080">Yes?</span></p>
<p><span style="color:#400000">The answer is: <em>It All Depends</em>.</span></p>
<p><span style="color:#004080">…</span></p>
<p><span style="color:#004080">I want the last 5 minutes of my life back.</span></p>
<p><span style="color:#400000">5 minutes? I've spent hours writing this.</span></p>
<p> </p>
<p><em>&lt;/SocraticDialectic&gt;</em></p>
<h4>Anyway, the point is…</h4>
<p>…every system is different. Which persistence paradigm is best depends on the project and its requirements and properties. All I want to say is that you shouldn't start with RDBMS and then look for reasons not to use it; at the same time, don't start with Project Voldemort or CouchDB just because they're new and exciting. Approach every project with no preconceptions about what you're going to use; or have &quot;flat text files&quot; as the default choice.</p>
<h4>A non-exhaustive list of things to consider:</h4>
<ul>
    <li>If constant consistency is a key requirement then you should probably use an RDBMS. </li>
    <li>If horizontal scalability is important and eventual consistency is good enough, then a NoSQL solution might be better. </li>
    <li>If you're deploying an application to Windows Azure or Amazon Web Services, then you should probably compare the costs of Windows Azure Storage Services or SimpleDB to SQL Azure or Elastic RDBMS for your particular application. </li>
    <li>If you're writing an application for a mobile platform, you're back to limited storage space so you might get back to RDBMS and normalising for efficient use of that space. </li>
    <li>If you're writing a small application you want to knock out quickly using Entity Framework or NHibernate or ActiveRecord then use SQL Server Compact or SQLite, or skip that stuff altogether and serialise object graphs to files on the hard-disk. </li>
</ul>
<p>In fact, if you really design your architecture with an open mind (or <a href="http://en.wikipedia.org/wiki/Shoshin" target="_blank">beginner's mind</a>), you'll come up with a combination of technologies and paradigms that properly meet different parts of the requirements; maybe use SQL Server 2008 R2 for stock control, invoicing and geo-spatial search operations, but Azure Table Storage for auditing, text files for logging. And why not evaluate distributed Document Stores for the awesome customer review and discussion features that you're adding in phase two?</p>
<p><strong>Most important of all</strong>, before making any decisions, take the time to do some apples-to-apples comparisons of potential solutions, with use cases,  data volumes and loads that are representative of your system. I recently chose MongoDB for a personal project, but I started out comparing SQL Server, MySQL and PostgreSQL and finding them all wanting, which is how I ended up looking at NoSQL databases in the first place. </p>
<p>(Just for the record, the most important query and most frequently-run query for the application took nearly 15 seconds on the fastest relational database (even after some violent denormalization); MongoDB can retrieve the same information in under half a second.)</p>
<h4>Further reading</h4>
<p>A comprehensive – and very balanced – list of articles on NoSQL databases: <a href="http://nosql-database.org/links.html">http://nosql-database.org/links.html</a></p>
<p> </p>
<p><span style="font-size:13px"><em>*All apologies to Douglas Adams.</em></span></p>

</div>]]></description><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DOTNETSOL\SharepointSA</dc:creator><pubDate>Thu, 11 Mar 2010 15:56:00 GMT</pubDate></item><item><title>XmlElementAsDictionary: A very simple wrapper for LINQ to XML</title><link>http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/2010/03/18/xmlelementasdictionary-a-very-simple-wrapper-for-linq-to-xml/</link><guid isPermaLink="False">/blogs/markrendle/archive/2010/03/18/xmlelementasdictionary-a-very-simple-wrapper-for-linq-to-xml/</guid><description><![CDATA[<div class="ExternalClass0D6AC2A911C24217B839663E5E30DBD1">
<h2></h2>
<h2></h2>
<h4>Why?</h4>
I've been forced into engaging with XML in all its gory details recently, as part of my AzureKit project (more on which in another post). Being a big fan of all things LINQ, I started out trying to use the LINQ-to-XML framework. <a href="http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/2010/02/17/working-with-namespaces-in-linq-to-xml" target="_blank">I had problems</a>. This is not a fault of the framework; as a fundamental part of the .NET Framework it must provide a way to achieve everything, and that's not the same as providing a way to do things simply. <br>
The REST API for Windows Azure uses a hybrid of the Atom syndication format and the ADO.NET Data Services format. Here is the XML required for an Insert to an Azure Table: <br>
<pre class="code"><span style="color:#0000ff">&lt;?</span><span style="color:#a31515">xml </span><span style="color:#ff0000">version</span><span style="color:#0000ff">=</span>&quot;<span style="color:#0000ff">1.0</span>&quot; <span style="color:#ff0000">encoding</span><span style="color:#0000ff">=</span>&quot;<span style="color:#0000ff">utf-8</span>&quot; <span style="color:#ff0000">standalone</span><span style="color:#0000ff">=</span>&quot;<span style="color:#0000ff">yes</span>&quot;<span style="color:#0000ff">?&gt;<br>&lt;</span><span style="color:#a31515">entry </span><span style="color:#ff0000">xmlns:d</span><span style="color:#0000ff">=</span>&quot;<span style="color:#0000ff">http://schemas.microsoft.com/ado/2007/08/dataservices</span>&quot;<br><span style="color:#ff0000">xmlns:m</span><span style="color:#0000ff">=</span>&quot;<span style="color:#0000ff">http://schemas.microsoft.com/ado/2007/08/dataservices/metadata</span>&quot;<br><span style="color:#ff0000">xmlns</span><span style="color:#0000ff">=</span>&quot;<span style="color:#0000ff">http://www.w3.org/2005/Atom</span>&quot;<span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">title </span><span style="color:#0000ff">/&gt;<br>&lt;</span><span style="color:#a31515">updated</span><span style="color:#0000ff">&gt;</span>2008-09-18T23:46:19.3857256Z<span style="color:#0000ff">&lt;/</span><span style="color:#a31515">updated</span><span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">author</span><span style="color:#0000ff">&gt;&lt;</span><span style="color:#a31515">name </span><span style="color:#0000ff">/&gt;&lt;/</span><span style="color:#a31515">author</span><span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">id </span><span style="color:#0000ff">/&gt;<br>&lt;</span><span style="color:#a31515">content </span><span style="color:#ff0000">type</span><span style="color:#0000ff">=</span>&quot;<span style="color:#0000ff">application/xml</span>&quot;<span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">m:properties</span><span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">d:Address</span><span style="color:#0000ff">&gt;</span>Mountain View<span style="color:#0000ff">&lt;/</span><span style="color:#a31515">d:Address</span><span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">d:PartitionKey</span><span style="color:#0000ff">&gt;</span>mypartitionkey<span style="color:#0000ff">&lt;/</span><span style="color:#a31515">d:PartitionKey</span><span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">d:RowKey</span><span style="color:#0000ff">&gt;</span>myrowkey1<span style="color:#0000ff">&lt;/</span><span style="color:#a31515">d:RowKey</span><span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">d:Timestamp </span><span style="color:#ff0000">m:type</span><span style="color:#0000ff">=</span>&quot;<span style="color:#0000ff">Edm.DateTime</span>&quot;<span style="color:#0000ff">&gt;</span>0001-01-01T00:00:00<span style="color:#0000ff">&lt;/</span><span style="color:#a31515">d:Timestamp</span><span style="color:#0000ff">&gt;<br>&lt;/</span><span style="color:#a31515">m:properties</span><span style="color:#0000ff">&gt;<br>&lt;/</span><span style="color:#a31515">content</span><span style="color:#0000ff">&gt;<br>&lt;/</span><span style="color:#a31515">entry</span><span style="color:#0000ff">&gt;<br></span></pre>
<br>
I can't post the LINQ-to-XML code you need to use to create that small document, because I deleted it. Then I formatted the hard drive that it had been on. Then I burned it, just to be on the safe side. The code was not clean. The code was <em>feculent</em>. <br>
<br>
The quickest example that I can give is that to use a prefixed namespace, you don't use <span style="font-family:'courier new', courier, monospace;font-size:small" class="Apple-style-span"><b>new XElement(&quot;m:properties&quot;)</b></span>; you use <span style="font-family:'courier new', courier, monospace;font-size:small" class="Apple-style-span"><b>new XElement(parentElement.GetNamespaceForPrefix(&quot;m&quot;) + &quot;properties&quot;)</b></span>. Seriously. I'm just not doing that. <br>
<br>
<h4>If you don't like an interface, wrap it</h4>
For these purposes, an XML tree is a collection of named elements, some of which have values, some of which have sub-elements, and each of which may have a number of attributes. <br>
<br>
More importantly a single Atom entry does not involve &quot;lists&quot;; that is, there are not multiple children with the same name within a parent element, like this: <br>
<br>
<pre class="code"><span style="color:#0000ff">&lt;</span><span style="color:#a31515">numbers</span><span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">number</span><span style="color:#0000ff">&gt;</span>One<span style="color:#0000ff">&lt;/</span><span style="color:#a31515">number</span><span style="color:#0000ff">&gt;<br>&lt;</span><span style="color:#a31515">number</span><span style="color:#0000ff">&gt;</span>Two<span style="color:#0000ff">&lt;/</span><span style="color:#a31515">number</span><span style="color:#0000ff">&gt;<br>&lt;/</span><span style="color:#a31515">numbers</span><span style="color:#0000ff">&gt;<br></span></pre>
<br>
In fact, an Azure Atom entry is a lot like a dictionary, except with nesting. <br>
<br>
I like dictionaries. In some other languages, I like hashes. But we're talking about .NET and C# here, so I like dictionaries. <br>
<br>
<h4>XmlElementAsDictionary</h4>
I've created a very simple class which wraps around an XElement object and provides access to that element's children, attributes and value using the Dictionary paradigm. Into this class I have baked support for namespaces which does not violate the Principle of Least Astonishment. <br>
<br>
Using this class to create the Azure/Atom XML element above looks like this: <br>
<br>
<pre class="code"><span style="color:#0000ff">var </span>entry = <span style="color:#0000ff">new </span><span style="color:#2b91af">XmlElementAsDictionary</span>(<span style="color:#a31515">&quot;entry&quot;</span>, <span style="color:#a31515">&quot;http://www.w3.org/2005/Atom&quot;</span>);<br><br>entry.AddPrefixedNamespace(<span style="color:#a31515">&quot;d&quot;</span>, <span style="color:#a31515">&quot;http://schemas.microsoft.com/ado/2007/08/dataservices&quot;</span>);<br>entry.AddPrefixedNamespace(<span style="color:#a31515">&quot;m&quot;</span>, <span style="color:#a31515">&quot;http://schemas.microsoft.com/ado/2007/08/dataservices/metadata&quot;</span>);<br><br>entry[<span style="color:#a31515">&quot;title&quot;</span>].Clear();<br>entry[<span style="color:#a31515">&quot;updated&quot;</span>].Value = <span style="color:#2b91af">DateTime</span>.Now.ToString(<span style="color:#a31515">&quot;s&quot;</span>);<br>entry[<span style="color:#a31515">&quot;author&quot;</span>][<span style="color:#a31515">&quot;name&quot;</span>].Clear();<br>entry[<span style="color:#a31515">&quot;id&quot;</span>].Clear();<br>entry[<span style="color:#a31515">&quot;content&quot;</span>].Attributes[<span style="color:#a31515">&quot;type&quot;</span>] = <span style="color:#a31515">&quot;application/xml&quot;</span>;<br>entry[<span style="color:#a31515">&quot;content&quot;</span>][<span style="color:#a31515">&quot;m:properties&quot;</span>][<span style="color:#a31515">&quot;d:Address&quot;</span>].Value = <span style="color:#a31515">&quot;Mountain View&quot;</span>;<br>entry[<span style="color:#a31515">&quot;content&quot;</span>][<span style="color:#a31515">&quot;m:properties&quot;</span>][<span style="color:#a31515">&quot;d:PartitionKey&quot;</span>].Value = <span style="color:#a31515">&quot;mypartitionkey&quot;</span>;<br>entry[<span style="color:#a31515">&quot;content&quot;</span>][<span style="color:#a31515">&quot;m:properties&quot;</span>][<span style="color:#a31515">&quot;d:RowKey&quot;</span>].Value = <span style="color:#a31515">&quot;myrowkey1&quot;</span>;<br>entry[<span style="color:#a31515">&quot;content&quot;</span>][<span style="color:#a31515">&quot;m:properties&quot;</span>][<span style="color:#a31515">&quot;d:Timestamp&quot;</span>].Value = <span style="color:#2b91af">DateTime</span>.MinValue.ToString(<span style="color:#a31515">&quot;s&quot;</span>);<br>entry[<span style="color:#a31515">&quot;content&quot;</span>][<span style="color:#a31515">&quot;m:properties&quot;</span>][<span style="color:#a31515">&quot;d:Timestamp&quot;</span>].Attributes[<span style="color:#a31515">&quot;m:type&quot;</span>] = <span style="color:#a31515">&quot;Edm.DateTime&quot;</span>;</pre>
<br>
The class will also accept an XElement to its constructor, and so can be used for reading XML in this manner as well as writing. <br>
<br>
Once complete, the element can be converted back into XML using ToElement() or ToDocument(), or to plain-text using ToString() (which gives the same result as calling ToElement().ToString(). <br>
<br>
<h3>Limitations</h3>
As specified, this approach also applies the Dictionary limitation of unique keys, so you can't have lists. But you can construct elements using this wrapper and then compose them into lists. <br>
<br>
<h3>Availability</h3>
I'm collecting various helpful utility classes that get created in support of other projects together in an open-source project called NExtLib. You can download the source from <a href="http://nextlib.codeplex.com/" target="_blank">Codeplex</a>. Releases will happen in sync with other, higher-level projects, including AzureKit, the first version of which I'm releasing later this month and hope to present on at user groups in the near future. <br>
<br>
<h3>Feedback</h3>
I'd love to hear any thoughts, ideas for improvement, criticisms, abuse or death threats. 
</div>]]></description><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DOTNETSOL\SharepointSA</dc:creator><pubDate>Tue, 09 Mar 2010 16:00:00 GMT</pubDate><category domain="http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/tags/xml/">xml</category><category domain="http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/tags/C#/">C#</category><category domain="http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/tags/.NET/">.NET</category></item><item><title>Reactive Extensions (Rx) and MVVM</title><link>http://www.dotnetsolutions.co.uk/blogs/markrendle/archive/2010/03/18/reactive-extensions-rx-and-mvvm/</link><guid isPermaLink="False">/blogs/markrendle/archive/2010/03/18/reactive-extensions-rx-and-mvvm/</guid><description><![CDATA[<div class="ExternalClass5EEED59306DB4E91BC9622BAC233FFED">
<h2>Overview</h2>
<p>Reactive Extensions (Rx) is the hot new toy out of Microsoft's DevLabs, which is included in Silverlight 4 and .NET 4, and is available as a download for Silverlight 3 and .NET 3.5. It provides a new LINQish way of managing and handling events. More information and downloads available at <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx" target="_blank">the DevLabs project page</a>.</p>
<p>I'd read quite a bit about Rx but hadn't taken the time to have a play with it until today, when I found myself looking at the code for a Model-View-ViewModel messaging implementation. The MVVM Messaging pattern consists of a static/global class through which separate parts of the application can communicate without requiring knowledge of each other. Classes can <strong>register</strong> to receive messages from the Messenger/Mediator, or <strong>send</strong> messages through the Messenger/Mediator for consumption elsewhere.</p>
<p>Hang on, I thought, that's the Rx pattern pair. I wonder if the two sit well together. So I had a go.</p>
<h2>The basics</h2>
<p>The Messaging Dispatcher pattern implementation, at its simplest, requires a method for registering to receive messages, and a method to send messages. The <a href="http://msdn.microsoft.com/en-us/library/dd990377(VS.100).aspx" target="_blank">IObservable&lt;T&gt;</a> interface consists of a single method, Subscribe, which takes an instance of <a href="http://msdn.microsoft.com/en-us/library/dd783449(VS.100).aspx" target="_blank">IObserver&lt;T&gt;</a>. The Messenger interface popularly provides a Subscribe method which takes an Action&lt;TMessage&gt; delegate, but that will be provided by the Rx extension methods if we implement IObservable&lt;T&gt;, so let's just include that in the IMessenger interface:</p>
<pre class="code"><span style="color:#0000ff">public interface </span><span style="color:#2b91af">IMessenger </span>: <span style="color:#2b91af">IObservable</span>&lt;<span style="color:#2b91af">IMessage</span>&gt;
{
    <span style="color:#0000ff">void </span>Send(<span style="color:#2b91af">IMessage </span>message);
}</pre>
<p>The Messenger class can be implemented as a very simple wrapper around the Rx Subject&lt;T&gt; class, which is both an IObservable&lt;T&gt; and an IObserver&lt;T&gt;; essentially, calling OnNext on the Subject causes it to call OnNext on its own observers.</p>
<pre class="code"><span style="color:#0000ff">public class </span><span style="color:#2b91af">Messenger </span>: <span style="color:#2b91af">IMessenger</span>{
    <span style="color:#0000ff">private readonly </span><span style="color:#2b91af">Subject</span>&lt;<span style="color:#2b91af">IMessage</span>&gt; _subject = <span style="color:#0000ff">new </span><span style="color:#2b91af">Subject</span>&lt;<span style="color:#2b91af">IMessage</span>&gt;();

    <span style="color:#0000ff">public </span><span style="color:#2b91af">IDisposable </span>Subscribe(<span style="color:#2b91af">IObserver</span>&lt;<span style="color:#2b91af">IMessage</span>&gt; observer)
    {
        <span style="color:#0000ff">return </span>_subject.Subscribe(observer);
    }

    <span style="color:#0000ff">public void </span>Send(<span style="color:#2b91af">IMessage </span>message)
    {
        _subject.OnNext(message);
    }

    <span style="color:#0000ff">private static readonly </span><span style="color:#2b91af">Messenger </span>_default = <span style="color:#0000ff">new </span><span style="color:#2b91af">Messenger</span>();

    <span style="color:#0000ff">public static </span><span style="color:#2b91af">Messenger </span>Default
    {
        <span style="color:#0000ff">get </span>{ <span style="color:#0000ff">return </span>_default; }
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>
<p>That was easy. That can't be it, can it?</p>
<p>Well, we get a lot of stuff for free with Rx. For example, the Subscribe method in the class above takes an instance of a class which implements IObserver&lt;T&gt;, but the System.Reactive.dll assembly provides a fistful of extension methods which accept one or more Action delegates and dynamically construct a class to implement the interface.</p>
<h2>Specifying which messages to receive</h2>
<p>One of the key features of a Messaging Dispatcher is the ability to register to receive only messages of specific types. I initially looked for an OfType&lt;T&gt; method on IObservable&lt;T&gt; (to match the OfType&lt;T&gt; on IEnumerable) but there is none, possibly because OfType&lt;T&gt; is implemented on the non-generic IEnumerable and there is no non-generic IObservable. This is reasonable enough: if IEnumerable were implemented today I don't suppose there'd be a non-generic version of that, or indeed any of the Collection classes.</p>
<p>But there is still a valid use case for being able to filter an IObservable&lt;T&gt; for more-derived types than T, as in this MVVM Messenger class. We could add an OfType&lt;T&gt; method to the Messenger class directly, but it is both more useful and more fun to apply it directly to the IObservable&lt;T&gt; type as an extension method.</p>
<p>Here we can make use of the Subject&lt;T&gt; primitive again; we subscribe to the IObservable&lt;T&gt; to be filtered, and when it fires an OnNext passing an argument of the requested type, we pass that on to the Subject. I've implemented OfType to include sub-types, and OfTypeExact to match only the specified type.</p>
<pre class="code"><span style="color:#0000ff">public static class </span><span style="color:#2b91af">IObservableExtensions</span>{
    <span style="color:#808080">/// &lt;summary&gt; /// </span><span style="color:#008000">Filter an IObservable for the specified type or derivatives. </span><span style="color:#808080">/// &lt;/summary&gt;</span><span style="color:#808080"> </span><span style="color:#0000ff">public static </span><span style="color:#2b91af">IObservable</span>&lt;TResult&gt; OfType&lt;TResult&gt;(<span style="color:#0000ff">this </span><span style="color:#2b91af">IObservable</span>&lt;<span style="color:#0000ff">object</span>&gt; src)
    {
        <span style="color:#0000ff">return from </span>item <span style="color:#0000ff">in <span style="color:#004462">src</span></span>
               <span style="color:#0000ff">where </span>item <span style="color:#0000ff">is </span>TResult
               <span style="color:#0000ff">select </span>(TResult)item;
    }
}</pre>
<p>This code highlights the &quot;LINQ to Events&quot; aspect of the Rx framework; we can construct natural queries against IObservable&lt;T&gt; sources just as we can against IEnumerable&lt;T&gt;.</p>
<p> </p>
<a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a>
<p> </p>
<h2 align="left">Consuming messages</h2>
<p align="left">Now, any component which needs to react to messages can subscribe very easily, using methods which are already familiar from the IEnumerable paradigm. To use a common example, here is a WPF Window which looks for DisplayMessage messages and displays a Message Box:</p>
<pre class="code"><span style="color:#0000ff">public partial class </span><span style="color:#2b91af">MainWindow </span>: <span style="color:#2b91af">Window</span>{
    <span style="color:#0000ff">public </span>MainWindow()
    {
        InitializeComponent();

        MvvmRx.Messaging.<span style="color:#2b91af">Messenger</span>.Default<br>            .OfType&lt;<span style="color:#2b91af">DisplayMessage</span>&gt;()<br>            .Subscribe(ShowMessageBox);
    }

    <span style="color:#0000ff">private void </span>ShowMessageBox(<span style="color:#2b91af">DisplayMessage </span>message)
    {
        <span style="color:#2b91af">MessageBox</span>.Show(message.Text, message.Caption);
    }
}</pre>
<p>You can download the solution file containing the code for this post, as well as a sample application, at <a href="http://github.com/markrendle/MvvmRx">http://github.com/markrendle/MvvmRx</a>.</p>

</div>]]></description><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DOTNETSOL\SharepointSA</dc:creator><pubDate>Fri, 05 Mar 2010 15:57:00 GMT</pubDate></item></channel></rss>
