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

<channel>
	<title>PeteGoo</title>
	<atom:link href="http://blog.petegoo.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.petegoo.com</link>
	<description>.Net Heebie Jeebies</description>
	<lastBuildDate>Sun, 29 Apr 2012 21:01:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Action Filter to support oData expands as EF includes in ASP.Net Web API</title>
		<link>http://blog.petegoo.com/index.php/2012/04/29/action-filter-to-support-odata-expands-as-ef-includes-in-asp-net-web-api/</link>
		<comments>http://blog.petegoo.com/index.php/2012/04/29/action-filter-to-support-odata-expands-as-ef-includes-in-asp-net-web-api/#comments</comments>
		<pubDate>Sun, 29 Apr 2012 04:23:46 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Entity Framewok]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/?p=351</guid>
		<description><![CDATA[Back in March I wrote a quick howto on supporting $expand for entities in ASP.Net Web API. That method used an extension method to pull the $expand clause out of the query string an apply it to the ObjectSet. I’ve &#8230; <a href="http://blog.petegoo.com/index.php/2012/04/29/action-filter-to-support-odata-expands-as-ef-includes-in-asp-net-web-api/">Continued</a>]]></description>
			<content:encoded><![CDATA[<p>Back in March <a href="http://blog.petegoo.com/index.php/2012/03/11/supporting-odata-expands-for-ef-includes-in-asp-net-web-api/" target="_blank">I wrote a quick howto</a> on supporting $expand for entities in ASP.Net Web API. That method used an extension method to pull the $expand clause out of the query string an apply it to the ObjectSet.</p>
<p>I’ve now added to that sample an <a href="http://msdn.microsoft.com/en-us/library/system.web.http.filters.actionfilterattribute(v=vs.108).aspx" target="_blank">ActionFilter</a> which will do this for you without any code in your controller.</p>
<p>To use it, change your global.asax and add the ActionFilter as part of your configuration.</p>
<pre>
public static void RegisterRoutes(RouteCollection routes) {
    ...
    ...

    HttpConfiguration configuration = GlobalConfiguration.Configuration;
    configuration.Filters.Add(new EFExpandActionFilter());

    ...
    ...
    ...
}</pre>
<p>&#160;</p>
<p>Now your api methods need only return an ObjectSet or ObjectQuery without any extension methods.</p>
<pre>
public IQueryable&lt;Customer&gt; GetCustomers() {
    return northwindEntities.Customers;
}</pre>
<p>Note that if you are using the default XML serializer you will find that the navigation properties do not serialize due to the XmlIgnore attribute, either customize your entities or use Json.Net (as in the sample project)</p>
<div class="alert alert-info"><strong>Download:</strong> <a href="https://github.com/PeteGoo/WebApiContext.Sample/commit/fadfe3649a95c36ac2b9d74d63054ff62cd89f3a" target="_blank">Source is on github</a>.</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2012/04/29/action-filter-to-support-odata-expands-as-ef-includes-in-asp-net-web-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>OData V3 any/all support</title>
		<link>http://blog.petegoo.com/index.php/2012/04/21/odata-v3-anyall-support/</link>
		<comments>http://blog.petegoo.com/index.php/2012/04/21/odata-v3-anyall-support/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 21:36:14 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ODAta]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Linq2Rest]]></category>
		<category><![CDATA[oData]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/?p=348</guid>
		<description><![CDATA[WCF Data Services 5 has been RTM’d and adds support for a whole bunch of scenarios: Any/All Actions Collections Named Streams/Stream Properties PATCH Verb Prefer Headers Properties on Derived Types Support for DateTimeOffset and TimeSpan Data Types Support for DbContext &#8230; <a href="http://blog.petegoo.com/index.php/2012/04/21/odata-v3-anyall-support/">Continued</a>]]></description>
			<content:encoded><![CDATA[<p>WCF Data Services 5 <a href="http://blogs.msdn.com/b/astoriateam/archive/2012/04/09/wcf-data-services-5-0-rtm-release.aspx" target="_blank">has been RTM’d</a> and adds support for a whole bunch of scenarios:</p>
<ul>
<li>Any/All </li>
<li>Actions </li>
<li>Collections </li>
<li>Named Streams/Stream Properties </li>
<li>PATCH Verb </li>
<li>Prefer Headers </li>
<li>Properties on Derived Types </li>
<li>Support for DateTimeOffset and TimeSpan Data Types </li>
<li>Support for DbContext as the DataService Source </li>
<li>Spatial </li>
<li>Vocabularies </li>
</ul>
<p>The most interesting bit for me initially was Any/All. Basically this has been one of those things that I get asked from time to time and have to explain that you could not (until now) filter a entity set based on some values in a sub-collection. E.g. give me all the customers who have ordered “x”.</p>
<p>With the inclusion of Any and All the following code is now possible</p>
<pre>// http://foo/?filter=Orders/any(o: o/OrderItems/any(i: i.Id eq 5))
var customers = Customers
                .Where(c =&gt;
                    c.Orders.Any(o =&gt;
                        o.OrderItems.Any(i =&gt;
                            i.Id == 5));</pre>
<p>&#160;</p>
<p>I like the lambda syntax in the URI $filter parameter. It makes it easy for anyone that is used to modern languages to see what is going on.</p>
<p>So right now you can get <a href="http://blogs.msdn.com/b/astoriateam/archive/2012/04/09/wcf-data-services-5-0-rtm-release.aspx" target="_blank">WCF Data Services 5</a> and start using the Any/All support in OData.</p>
<p><a href="http://www.reimers.dk/" target="_blank">Jacob Reimers</a> has also gracefully accepted and published my pull request so <a href="http://nuget.org/packages?q=linq2rest" target="_blank">Linq2Rest</a> now fully supports Any/All queries in both the server and client APIs.</p>
<p>I’ve also <a href="http://aspnetwebstack.codeplex.com/workitem/65" target="_blank">submitted an issue</a> on the ASP.Net Web API for support so please up vote that issue if it’s something that’s important to you. From that issue you can also go see the implementation that I’ve done for my fork of aspnetwebstack that implements server support for Any/All in ASP.Net Web API.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2012/04/21/odata-v3-anyall-support/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Assembly File Locking when using AppDomains in a Visual Studio package</title>
		<link>http://blog.petegoo.com/index.php/2012/03/30/assembly-file-locking-when-using-appdomains-in-a-visual-studio-package/</link>
		<comments>http://blog.petegoo.com/index.php/2012/03/30/assembly-file-locking-when-using-appdomains-in-a-visual-studio-package/#comments</comments>
		<pubDate>Thu, 29 Mar 2012 21:58:00 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[VSX]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/?p=344</guid>
		<description><![CDATA[Recently I was using a new AppDomain from within a Visual Studio package to reflect over a dll and get some metadata. I then unloaded the AppDomain expecting that the file locks on the dll file would be released…..but they &#8230; <a href="http://blog.petegoo.com/index.php/2012/03/30/assembly-file-locking-when-using-appdomains-in-a-visual-studio-package/">Continued</a>]]></description>
			<content:encoded><![CDATA[<p>Recently I was using a new AppDomain from within a Visual Studio package to reflect over a dll and get some metadata. I then unloaded the AppDomain expecting that the file locks on the dll file would be released…..but they weren’t.</p>
<p>I could see that another AppDomain in VS was holding a lock on my file. You can see this by switching on Native debugging when attaching another visual studio instance and from the immediate window use:</p>
<blockquote><p><font style="background-color: #ffffff">.load sos</font></p>
<p><font style="background-color: #ffffff">!dumpdomain</font></p>
</blockquote>
<p>It turns out this is due to the <a href="http://msdn.microsoft.com/en-us/library/system.appdomainsetup.loaderoptimization(v=vs.80).aspx" target="_blank">LoaderOptimization</a> attribute. Set this property to SingleDomain on your AppDomainSetup object to allow the file lock to be freed when unloading your AppDomain. This translates as.</p>
<blockquote><p><em>Indicates that the application will probably have a single domain, and loader must not share internal resources across application domains. </em></p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2012/03/30/assembly-file-locking-when-using-appdomains-in-a-visual-studio-package/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing Pushqa&#8211;Queryable Push Messages over OData</title>
		<link>http://blog.petegoo.com/index.php/2012/03/20/introducing-pushqaqueryable-push-messages-over-odata/</link>
		<comments>http://blog.petegoo.com/index.php/2012/03/20/introducing-pushqaqueryable-push-messages-over-odata/#comments</comments>
		<pubDate>Tue, 20 Mar 2012 09:32:17 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[ODAta]]></category>
		<category><![CDATA[Pushqa]]></category>
		<category><![CDATA[Rx]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[oData]]></category>
		<category><![CDATA[SignalR]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/?p=330</guid>
		<description><![CDATA[Pushqa is a smarter pub/sub model, allowing the subscriber to use LINQ to declare the messages they want to receive. Background LINQ has revolutionised the way we work with data in .Net, allowing us to compose and query data sources &#8230; <a href="http://blog.petegoo.com/index.php/2012/03/20/introducing-pushqaqueryable-push-messages-over-odata/">Continued</a>]]></description>
			<content:encoded><![CDATA[<p><strong>Pushqa is a smarter pub/sub model, allowing the subscriber to use LINQ to declare the messages they want to receive.</strong></p>
<h3>Background</h3>
<p>LINQ has revolutionised the way we work with data in .Net, allowing us to compose and query data sources of all types. When Microsoft introduced <a href="http://www.odata.org" target="_blank">OData</a> it opened up the ability to query server resources using a simple URI syntax or LINQ if you are using a .Net client. This was great news for accessing data stores like SQL using Entity Framework, NHibernate etc over HTTP such that the data manipulation and querying happens on the server before being sent to the client. A kind of LINQ remoting if you like. </p>
<p>Then came Reactive Extensions (<a title="Ractive Extensions" href="http://msdn.microsoft.com/en-us/data/gg577609" target="_blank">Rx</a>), a LINQ implementation that instead of accessing data sources, allows querying and composition of future events or event streams to produce new event streams. Rx revolutionises the event concept in .Net and makes dealing with asynchrony so much easier. </p>
<h3>Introducing Pushqa</h3>
<p>Suppose then, that we could also use Rx LINQ or OData uri syntax to filter an event stream of push messages before they leave the source. A kind of smarter Pub/Sub that allows the subscriber to specify which messages they want to receive from the server in a more natural declarative style. This is the goal of Pushqa, to give subscribers power over their own subscriptions. </p>
<p>Imagine a log viewer client that can filter to only the error level messages that happen to a specific user. Or a client cache that listens to specific domain events in order to evict only the items it cares about from it’s cache when they change.</p>
<p>By combining Rx, SignalR and OData Pushqa is able to translate LINQ queries to OData compliant URI conventions. The uri is used to initiate a persistent connection to the server that will then filter the events exposed by an Rx event stream into tailored streams for each client.</p>
<p>e.g.</p>
<p>The following code</p>
<pre class="brush: csharp;">eventProvider.Stocks
    .Where(s =&gt;
        s.Name == &quot;GOOG&quot; ||
        s.Name == &quot;MSFT&quot;)
    .AsObservable()
    .Subscribe(s =&gt; Console.WriteLine(“{0} – {1}”, s.Name, s.Price))</pre>
<p>results in the following OData query</p>
<pre>http://my.domain.com/Stocks/?filter=(Name eq 'GOOG') or (Name eq 'MSFT')</pre>
<p>and the following output</p>
<blockquote>
<p>MSFT &#8211; 24.11<br />
    <br />GOOG &#8211; 457.52</p>
<p>MSFT &#8211; 30.11</p>
<p>GOOG &#8211; 576.65</p>
<p></p>
<p>…</p>
</blockquote>
<p>The stock events generated by the source on the server will be filtered to only Google and Microsoft before being sent to the subscriber one at a time using HTTP long polling or similar HTTP based push messaging as provided by SignalR.</p>
<p>Fetch the early bits from <a title="Pushqa on GitHub" href="https://github.com/PeteGoo/Pushqa" target="_blank">GitHub</a>. Be warned these bits are early but hopefully the sample projects will give you some ideas. Samples include:</p>
<ul>
<li>Using Skip and Take to complete event streams. </li>
<li>A Process Viewer showing the server’s process information with live updates. </li>
<li>A Stock ticker. </li>
<li>WPF and Web examples. </li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2012/03/20/introducing-pushqaqueryable-push-messages-over-odata/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Supporting oData expands for EF includes in ASP.Net Web API</title>
		<link>http://blog.petegoo.com/index.php/2012/03/11/supporting-odata-expands-for-ef-includes-in-asp-net-web-api/</link>
		<comments>http://blog.petegoo.com/index.php/2012/03/11/supporting-odata-expands-for-ef-includes-in-asp-net-web-api/#comments</comments>
		<pubDate>Sun, 11 Mar 2012 07:46:06 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[ODAta]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Entity Framewok]]></category>
		<category><![CDATA[oData]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/?p=318</guid>
		<description><![CDATA[Hold Up!!! Please see the updated (and much nicer) implementation using an ActionFilter. Following on from my previous post on creating a client API for ASP.Net Web API queryable oData services, I wanted to prove that expand clauses could also &#8230; <a href="http://blog.petegoo.com/index.php/2012/03/11/supporting-odata-expands-for-ef-includes-in-asp-net-web-api/">Continued</a>]]></description>
			<content:encoded><![CDATA[<div class="alert alert-error">Hold Up!!! <a title="Updated sample using an ActionFilter" href="http://blog.petegoo.com/index.php/2012/04/29/action-filter-to-support-odata-expands-as-ef-includes-in-asp-net-web-api/">Please see the updated (and much nicer) implementation using an ActionFilter</a>.</div>
<p>Following on from my previous post on <a title="Creating a Queryable client for ASP.Net web api oData services" href="http://blog.petegoo.com/index.php/2012/03/11/creating-a-net-queryable-client-for-asp-net-web-api-odata-services/" target="_blank">creating a client API for ASP.Net Web API queryable oData services</a>, I wanted to prove that expand clauses could also work for Entity Framework object sets.</p>
<p>The <a title="oData expand" href="http://www.odata.org/developers/protocols/uri-conventions#ExpandSystemQueryOption" target="_blank">oData URI conventions</a> specifies that the desired depth of an entity can be represented in the $expand query string parameter. When using the ASP.Net Web API we need a way to pull this information from the querystring and convert it into Include statements on the ADO.Net Entity Framework object set. To achieve this I created an extension method that will pull the $expand query string parameter and translate it into multiple Include method calls.</p>
<pre class="brush: csharp;">public class NorthwindController : ApiController
{
    private readonly NorthwindEntities northwindEntities = new NorthwindEntities();

    public NorthwindController() {
        northwindEntities.ContextOptions.LazyLoadingEnabled = false;
    }

    public IQueryable&lt;Customer&gt; GetCustomers() {
        return northwindEntities.Customers.ProcessExpands();
    }
}

public static class ObjectQueryExtensions {
    public static ObjectQuery&lt;T&gt; ProcessExpands&lt;T&gt;(this ObjectSet&lt;T&gt; source) where T : class {
        string expandsQueryString = HttpContext.Current.Request.QueryString[&quot;$expand&quot;];
        if(string.IsNullOrWhiteSpace(expandsQueryString)) {
            return source;
        }

        ObjectQuery&lt;T&gt; query = source;

        expandsQueryString.Split(',').Select(s =&gt; s.Trim()).ToList().ForEach(
            expand =&gt; {
                query = query.Include(expand.Replace(&quot;/&quot;, &quot;.&quot;));
            });

        return query;
    }
}</pre>
<p>Now all that’s left is to figure out how to provide the client side support for this….</p>
<p>Meanwhile the full source for the above project is available on github. <a href="https://github.com/PeteGoo/WebApiContext.Sample">https://github.com/PeteGoo/WebApiContext.Sample</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2012/03/11/supporting-odata-expands-for-ef-includes-in-asp-net-web-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating a .Net queryable client for ASP.Net Web API oData services</title>
		<link>http://blog.petegoo.com/index.php/2012/03/11/creating-a-net-queryable-client-for-asp-net-web-api-odata-services/</link>
		<comments>http://blog.petegoo.com/index.php/2012/03/11/creating-a-net-queryable-client-for-asp-net-web-api-odata-services/#comments</comments>
		<pubDate>Sat, 10 Mar 2012 22:00:19 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[ODAta]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Linq2Rest]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/?p=314</guid>
		<description><![CDATA[TL;DR: How to create a client Linq api for querying IQueryable ASP.Net Web API rest services in very few lines of code using JSON.Net and Linq2Rest. &#160; The ASP.Net MVC4 Beta was released recently and included the Beta release of &#8230; <a href="http://blog.petegoo.com/index.php/2012/03/11/creating-a-net-queryable-client-for-asp-net-web-api-odata-services/">Continued</a>]]></description>
			<content:encoded><![CDATA[<h5>TL;DR: How to create a client Linq api for querying IQueryable ASP.Net Web API rest services in very few lines of code using JSON.Net and Linq2Rest.</h5>
<p>&#160;</p>
<p>The <a href="http://www.asp.net/mvc/mvc4" target="_blank">ASP.Net MVC4 Beta</a> was released recently and included the Beta release of <a title="ASP.Net Web API" href="http://www.asp.net/web-api" target="_blank">ASP.Net Web API</a>, formally known as the WCF Web API. Lots of people have already talked about the benefits of the Web API and how it has been built with <a title="Problem Solver on ASP.Net Web API" href="http://msmvps.com/blogs/theproblemsolver/archive/2012/03/09/getting-started-with-the-asp-net-web-api.aspx" target="_blank">simplicity</a>, <a title="WCF Web API on codeplex" href="http://wcf.codeplex.com/wikipage?title=WCF%20HTTP" target="_blank">transparency</a>, <a title="plugging in a JSON.Net formatter for Web API" href="http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx" target="_blank">extensibility</a> and <a title="ScottGu on web api" href="http://weblogs.asp.net/scottgu/archive/2012/02/23/asp-net-web-api-part-1.aspx" target="_blank">testability</a> in mind so I’ll not go into too many details about that here. </p>
<h3>Using ASP.Net Web Api instead of WCF Data Services</h3>
<h3></h3>
<p>One of the features that excites me about Web Api is the ability to expose an IQueryable on a Rest service and have Web Api automatically map queries in oData uri format to actual linq queries on the source i expose. For example, if my Web API controller looks like this:</p>
<pre class="brush: csharp;">public class PeopleController : ApiController {
    public IQueryable&lt;Person&gt; GetModels() {

        return people.AsQueryable();
    }

    private readonly Person[] people = new Person[] {
            new Person {
                Id = 1,
                FirstName = &quot;Peter&quot;,
                LastName = &quot;Goodman&quot;
            },
            new Person {
                Id = 2,
                FirstName = &quot;Peter&quot;,
                LastName = &quot;Skeeter&quot;
            },
            new Person {
                Id = 3,
                FirstName = &quot;Tony&quot;,
                LastName = &quot;Stark&quot;
            },
            new Person {
                Id = 4,
                FirstName = &quot;Frank&quot;,
                LastName = &quot;Grimes&quot;
            },
            new Person {
                Id = 5,
                FirstName = &quot;Doug&quot;,
                LastName = &quot;Kettle&quot;
            },
            new Person {
                Id = 6,
                FirstName = &quot;Finbar&quot;,
                LastName = &quot;Coole&quot;
            },
        };
}</pre>
<p>&#160;</p>
<p>Web Api will now let me access this resource and query it using oData syntax e.g.:</p>
<p><em>/api/People?$filter=FirstName eq ‘Peter&#8217;&amp;$orderby=LastName desc</em></p>
<p>This of course is just like the kind of thing you get out of WCF Data Services with a couple of very important differences.</p>
<ul>
<li>Web API does not currently support all of the features of oData, e.g. projection and expand</li>
<li><strong>Web API is highly configurable and extensible.</strong></li>
<li>Web API does not currently have a formatter Atom+Xml format, although an implementation is on the <a title="The ASP.Net MVC Roadmap" href="http://aspnet.codeplex.com/wikipage?title=asp.net%20mvc%204%20roadmap" target="_blank">roadmap</a></li>
<li><strong>There currently is no built in .Net client api for issuing Linq queries to Web API rest services</strong></li>
</ul>
<p>One of the pains of WCF Data Services has been the inability to configure or extend the implementation, for example it is very difficult or impossible to add your own formatter/serializer. With Web API, this kind of stuff is almost trivial.</p>
<p>The WCF Data Services client API (DataServiceContext) only allows you to use Atom+Xml which for a lot of purposes is extremely bloated in comparison to something like <a title="Javascript Object Notation" href="http://www.json.org/" target="_blank">JSON</a> or <a title="Google&#39;s Protocol Buffers" href="http://code.google.com/p/protobuf/" target="_blank">protobuf</a>.</p>
<p>Unfortunately there also is no equivalent to the DataServiceContext that allows you to query the above service in Web API, therefore you cannot use LINQ to query the above service. This is what we are going to build. </p>
<h3>Setting up the project</h3>
<p>Make sure you have ASP.Net MVC4 Beta installed and create a new ASP.Net MVC 4 application project. When you get prompted for the Project Template make sure to choose “Web API” and hit OK.</p>
<p>Under models add a new class called Person and add the following code.</p>
<pre class="brush: csharp;">public class Person {
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}</pre>
<p>Change the name of the ValuesController in the Controllers folder to PeopleController and add the code at the start of this article.</p>
<p>Run your project and in the browser change the url to something like the following remembering to use the hostname and port of your own project:</p>
<p><em>http://localhost:21449/api/People</em></p>
<p>You should see a list of the people we have defined.</p>
<p>Now we should be able to change this to the following to see only the ‘Peter’s</p>
<p><em>http://localhost:21449/api/People?$filter=FirstName = &#8216;Peter&#8217;</em></p>
<p>You will notice that the output is in Xml. We want to customize this to allow Json</p>
<h3></h3>
<h3>Creating the JSON.Net formatter</h3>
<p>To create a json formatted output for our service we are going to use JSON.Net, the Web API team have already said that they are going to ship with JSON.Net as the default JSON formatter when it goes RTM. Therefore you can skip this section if you are working with the RTM version.</p>
<p>Firstly, using <a title="Nuget package manager" href="http://www.nuget.org/" target="_blank">Nuget package manager</a>, add a package dependency to your project on JSON.Net</p>
<p>Create a folder in your web project called Infrastructure and add a class called JsonNetFormatter. Paste in the code for this class only from <a title="Henrik on Using JSON.Net with ASP.Net Web API" href="http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx" target="_blank">Henrik’s article on the subject</a>.</p>
<p>In the global.asax.cs file in your project add the following code in the RegisterRoutes method to register the JSON.Net formatter before the current default one. </p>
<pre class="brush: csharp;">JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());

HttpConfiguration configuration = GlobalConfiguration.Configuration;

configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings));</pre>
<p>You can test that works in <a title="Fiddler" href="http://fiddler2.com/fiddler2/" target="_blank">fiddler2</a> by starting fiddler, re-running the previous query in the browser (you may need to replace the hostname with ipv4.fiddler to see it), drag the session into the composer tab and change the accept header to </p>
<p><em>Accept: application/json</em></p>
<p>You should now see that we have JSON output.</p>
<h3>Creating the client application and api</h3>
<p>Add a new console application project to your solution named something sensible. This is going to be our .Net client.</p>
<p>To create our client side code we are going to need something that can take a LINQ query and convert it to the <a title="OData URI Conventions" href="http://www.odata.org/developers/protocols/uri-conventions" target="_blank">oData URI format</a>. In another project I am working on I have recently been using the excellent <a title="Linq2Rest on BitBucket" href="https://bitbucket.org/jjrdk/linq2rest" target="_blank">Linq2Rest</a> library written by <a title="Jacob Reimers&#39; Blog" href="http://www.reimers.dk/" target="_blank">Jacob Reimers</a>. He has written Linq2Rest to solve the problem of converting between IQueryables and OData URIs. Unfortunately the client and server pieces for Linq2Rest are in the same assembly so you will need to make your console app targets .Net 4.0 instead of the client profile in the project properties in order to support the dependency on System.Web.</p>
<p>Add a nuget package reference in your console app to Linq2Rest and Json.Net. </p>
<p>Next we need to create a matching JSON.Net deserializer for the Linq2Rest library so that it will match our server side implementation. This is just to ensure compatibility, you could of course reference the same common serializer settings etc. Create a folder in your console app called Infrastructure and add the following code for the JsonNetSerializerFactory and it’s serializer.</p>
<pre class="brush: csharp;">public class JsonNetSerializerFactory : ISerializerFactory {
    public ISerializer&lt;T&gt; Create&lt;T&gt;() {
        return new JsonNetSerializer&lt;T&gt;();
    }

    public class JsonNetSerializer&lt;T&gt; : ISerializer&lt;T&gt; {
        public T Deserialize(string input) {
            return JsonConvert.DeserializeObject&lt;T&gt;(input);
        }

        public IList&lt;T&gt; DeserializeList(string input) {
            return JsonConvert.DeserializeObject&lt;IList&lt;T&gt;&gt;(input);
        }
    }
}</pre>
<p>&#160;</p>
<p>Now we are ready to create our equivalent of the DataServiceContext. Add a new class to that project called PeopleContext and fill it out with the following code.</p>
<pre class="brush: csharp;">public class PeopleContext {
    private readonly RestContext&lt;Person&gt; restContext;

    public PeopleContext(Uri uri, Format format) {
        restContext = new RestContext&lt;Person&gt;(GetRestClient(uri, format), GetSerializerFactory(format));
    }

    public enum Format {
        Pox,
        Json
    }

    public static IRestClient GetRestClient(Uri uri, Format format) {
        switch (format) {
            case Format.Pox:
                return new XmlRestClient(uri);
            case Format.Json:
                return new JsonRestClient(uri);
            default:
                throw new NotImplementedException();
        }
    }

    public static ISerializerFactory GetSerializerFactory(Format format) {
        switch (format) {
            case Format.Pox:
                return new XmlSerializerFactory(knownTypes);
            case Format.Json:
                return new JsonNetSerializerFactory();

            default:
                throw new NotImplementedException();
        }
    }

    private static readonly IEnumerable&lt;Type&gt; knownTypes = new[] {
        typeof (Person)
    };

    public IQueryable&lt;Person&gt; People {
        get { return restContext.Query; }
    }

}</pre>
<p>Now we are ready to consume our new fancy pants context class. In the Program.cs add the following code to query the service and display the results. Remember to replace the hostname and port with your settings. I’ve used the ipv4.fiddler address to force fiddler to log the session, this of course won’t work if you don’t have fiddler running.</p>
<pre class="brush: csharp;">class Program {
    static void Main(string[] args) {
        PrintQuery(PeopleContext.Format.Pox);
        PrintQuery(PeopleContext.Format.Json);

        Console.ReadKey(true);
    }

    private static void PrintQuery(PeopleContext.Format wireFormat) {
        Console.WriteLine();
        Console.WriteLine(&quot;*** Querying in {0} format ***&quot;, wireFormat);
        Console.WriteLine();

        // Perform Query
        new PeopleContext(new Uri(&quot;http://ipv4.fiddler:14061/api/People&quot;), wireFormat)
            .People
            .Where(model =&gt; model.FirstName.StartsWith(&quot;Pe&quot;))
            .ToList()
            .ForEach(item =&gt; {
                Console.WriteLine(&quot;-----------------------------------&quot;);
                Console.WriteLine(&quot;Id:{0}&quot;, item.Id);
                Console.WriteLine(&quot;First Name:{0}&quot;, item.FirstName);
                Console.WriteLine(&quot;Last Name:{0}&quot;, item.LastName);
            });
        Console.WriteLine(&quot;-----------------------------------&quot;);
    }
}</pre>
<p>&#160;</p>
<p>Run the console app and you should see:</p>
<blockquote>
<p>
    </p>
<p>
    <br />*** Querying in Pox format ***</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
    <br />Id:1</p>
<p>First Name:Peter</p>
<p>Last Name:Goodman</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>Id:2</p>
<p>First Name:Peter</p>
<p>Last Name:Skeeter</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>*** Querying in Json format ***</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
    <br />Id:1</p>
<p>First Name:Peter</p>
<p>Last Name:Goodman</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>Id:2</p>
<p>First Name:Peter</p>
<p>Last Name:Skeeter</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>
    </p>
</blockquote>
<p>&#160;</p>
<p>And we’re done. You should be able to see in fiddler now that we have issued a request in each format (Xml and Json) and received the appropriate format in your response. I have even used this approach to implement a protobuf-net version for even greater speed and reduced payload.</p>
<p>You can get the source for this sample on GitHub</p>
<p><a href="https://github.com/PeteGoo/WebApiContext.Sample">https://github.com/PeteGoo/WebApiContext.Sample</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2012/03/11/creating-a-net-queryable-client-for-asp-net-web-api-odata-services/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>C# Static Field Initializers</title>
		<link>http://blog.petegoo.com/index.php/2012/01/18/c-static-field-initializers/</link>
		<comments>http://blog.petegoo.com/index.php/2012/01/18/c-static-field-initializers/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 09:14:41 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/?p=310</guid>
		<description><![CDATA[I hit a problem recently where a singleton I was calling from an assembly resolver was throwing an exception. It turned out that the sync object used in the lock for the singleton pattern was null. How was this possible? &#8230; <a href="http://blog.petegoo.com/index.php/2012/01/18/c-static-field-initializers/">Continued</a>]]></description>
			<content:encoded><![CDATA[<p>I hit a problem recently where a singleton I was calling from an assembly resolver was throwing an exception. It turned out that the sync object used in the lock for the <a title="MSDN C# Singleton Pattern" href="http://msdn.microsoft.com/en-us/library/ff650316.aspx" target="_blank">singleton pattern</a> was null. How was this possible? Look at the code below:</p>
<pre class="brush: csharp;">using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static readonly object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            lock (syncRoot)
            {
               if (instance == null)
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}</pre>
<p>How can this be, my static readonly field should be set by the field initializer. This should be run before it’s first usage. Normally, this is true but for some reason this was not the case. The C#spec though gives us a workaround, implement a static constructor. The <a href="http://msdn.microsoft.com/en-us/library/aa645612(v=vs.71).aspx" target="_blank">section on static constructors</a> states: </p>
<blockquote>
<p>If a class contains any static fields with initializers, those initializers are executed in textual order immediately prior to executing the static constructor.</p>
</blockquote>
<p>Therefore, if we add a static constructor to our Singleton class, we get guaranteed initialization of the static field initializers before it is run, also:</p>
<blockquote>
<p>The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:</p>
<ul>
<li>An instance of the class is created. </li>
<li>Any of the static members of the class are referenced. </li>
</ul>
</blockquote>
<p>Therefore our static constructor will run before our singleton Instance property.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2012/01/18/c-static-field-initializers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building an Auto Complete control with Reactive Extensions (Rx)</title>
		<link>http://blog.petegoo.com/index.php/2011/11/22/building-an-auto-complete-control-with-reactive-extensions-rx/</link>
		<comments>http://blog.petegoo.com/index.php/2011/11/22/building-an-auto-complete-control-with-reactive-extensions-rx/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 10:28:08 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Rx]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/index.php/2011/11/22/building-an-auto-complete-control-with-reactive-extensions-rx/</guid>
		<description><![CDATA[I have been meaning to get into Rx for a while now and haven’t quite found the excuse or opportunity to do so. While playing with SignalR it became apparent that Rx was something that could help and while I &#8230; <a href="http://blog.petegoo.com/index.php/2011/11/22/building-an-auto-complete-control-with-reactive-extensions-rx/">Continued</a>]]></description>
			<content:encoded><![CDATA[<p>I have been meaning to get into <a title="Ractive Extensions" href="http://msdn.microsoft.com/en-us/data/gg577609" target="_blank">Rx</a> for a while now and haven’t quite found the excuse or opportunity to do so. While playing with <a title="SignalR" href="https://github.com/SignalR/SignalR" target="_blank">SignalR</a> it became apparent that Rx was something that could help and while I was researching it I seen a lot of people talking about using Rx in UI frameworks and I thought, hmmm, that sounds interesting.</p>
<p>So I set myself a challenge, I wanted to use Rx to create an auto-complete WPF control with some of the major use cases I have seen in these types of controls.</p>
<h3>The App Shell</h3>
<p>First thing I was going to need was a WPF application with a MainWindow that would hold my text box, the results and a log window.</p>
<p>&#160;<a href="http://blog.petegoo.com/wp-content/uploads/2011/11/CropperCapture1.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="CropperCapture[1]" border="0" alt="CropperCapture[1]" src="http://blog.petegoo.com/wp-content/uploads/2011/11/CropperCapture1_thumb.jpg" width="478" height="320" /></a></p>
<p>The XAML looks something like this:</p>
<pre class="brush: xml;">&lt;Window
    x:Class=&quot;AutoCompleteWithRx.MainWindow&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    Title=&quot;AutoComplete with Rx&quot;
    Height=&quot;451&quot;
    Width=&quot;825&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:AutoCompleteWithRx=&quot;clr-namespace:AutoCompleteWithRx&quot;
    mc:Ignorable=&quot;d&quot;
    d:DataContext=&quot;{d:DesignInstance AutoCompleteWithRx:AutoCompleteViewModel}&quot;
    FocusManager.FocusedElement=&quot;{Binding ElementName=SearchBox}&quot;&gt;
    &lt;Grid&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition
                Height=&quot;Auto&quot; /&gt;
            &lt;RowDefinition /&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;Grid.ColumnDefinitions&gt;
            &lt;ColumnDefinition /&gt;
            &lt;ColumnDefinition /&gt;
        &lt;/Grid.ColumnDefinitions&gt;
        &lt;TextBlock
            FontFamily=&quot;Segoe WP Light&quot;
            FontSize=&quot;26.667&quot;
            Text=&quot;Auto-Complete Sample&quot;
            Grid.ColumnSpan=&quot;2&quot; 

            /&gt;

        &lt;StackPanel
            Grid.Row=&quot;2&quot;&gt;
            &lt;Label&gt;Search&lt;/Label&gt;
            &lt;TextBox
                x:Name=&quot;SearchBox&quot;
                Text=&quot;{Binding SearchText, UpdateSourceTrigger=PropertyChanged}&quot;/&gt;
            &lt;ProgressBar Height=&quot;19&quot; IsIndeterminate=&quot;True&quot;/&gt;
            &lt;ListBox
                ItemsSource=&quot;{Binding SearchResults}&quot; /&gt;
        &lt;/StackPanel&gt;
        &lt;StackPanel Grid.Column=&quot;1&quot; Orientation=&quot;Vertical&quot; Grid.Row=&quot;1&quot; d:LayoutOverrides=&quot;Height&quot;&gt;
            &lt;Label&gt;Log&lt;/Label&gt;
            &lt;ListBox
                ItemsSource=&quot;{Binding LogOutput}&quot; /&gt;
        &lt;/StackPanel&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;</pre>
<p>So that is basically the view for now. I have cheated and just instantiated my viewmodel in the code behind class for now.</p>
<pre class="brush: csharp;">public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();
        DataContext = new AutoCompleteViewModel();
    }
}</pre>
<p>Now that we have a window I need to get my view model up to scratch. I started with simply satisfying the data properties required by my form.</p>
<pre class="brush: csharp;">public class AutoCompleteViewModel : INotifyPropertyChanged {

    private string searchText;

    public string SearchText {
        get { return searchText; }
        set {
            if (searchText == value) {
                return;
            }
            searchText = value;
            NotifyPropertyChanged(&quot;SearchText&quot;);
        }
    }

    private readonly ObservableCollection&lt;string&gt; logOutput = new ObservableCollection&lt;string&gt;();

    public ObservableCollection&lt;string&gt; LogOutput {
        get { return logOutput; }
    }

    private readonly ObservableCollection&lt;string&gt; searchResults = new ObservableCollection&lt;string&gt;();

    public ObservableCollection&lt;string&gt; SearchResults {
        get { return searchResults; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyPropertyChanged(string propertyName) {
        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}</pre>
<h3>&#160;</h3>
<h3>Subscribing to Property Changed Events using Rx</h3>
<h3></h3>
<p>OK. So that is simple enough but now I need to make my textbox do something when the user types into it. Before I start doing this though I will need to add Rx to my project. Right click the project choose “Manage <a title="Get NuGet if you don&#39;t have it" href="http://www.nuget.org" target="_blank">Nuget</a> Packages” and search for Rx, install Rx-Main and Rx-WPF.</p>
<p>Let’s start by simply logging the fact that the user has typed something. Add a constructor to our view model class with the following code:</p>
<pre class="brush: csharp;">public AutoCompleteViewModel() {
    // Listen to all property change events on SearchText
    var searchTextChanged = Observable.FromEventPattern&lt;PropertyChangedEventHandler, PropertyChangedEventArgs&gt;(
        ev =&gt; PropertyChanged += ev,
        ev =&gt; PropertyChanged -= ev
        )
        .Where(ev =&gt; ev.EventArgs.PropertyName == &quot;SearchText&quot;);

    // Transform the event stream into a stream of strings (the input values)
    var input = searchTextChanged
        .Select(args =&gt; SearchText);

    // Log all events in the event stream to the Log viewer
    input.ObserveOn(DispatcherScheduler.Instance)
        .Subscribe(e =&gt; LogOutput.Insert(0,
            string.Format(&quot;Text Changed. Current Value - {0}&quot;, e)));
}</pre>
<p>The first section of slightly unwieldy syntax creates an <a title="IObservable(Of T) on MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx" target="_blank">IObservable</a> from the <a title="PropertyChanged" href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx" target="_blank">PropertyChanged</a> event of <a title="INotifyPropertyChanged" href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank">INotifyPropertyChanged</a> which our view model implements. You can think of the IObservable as a stream of events that will happen or a collection of future objects that will be added to each time the event is raised. Our code will then filter those events to only those concerning the SearchText that our textbox is bound to.</p>
<p>The next line transforms the type of the events in our IObservable from <a title="PropertyChangeEventsArgs" href="http://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventargs.aspx" target="_blank">PropertyChangeEventsArgs</a> to string, the content of the textbox. Much more useful.</p>
<p>Finally we need to subscribe to the event stream and do something with the string, firstly though we tell the subscription that we want to observe the events on the WPF dispatcher (This helper singleton comes from the Rx-WPF package). Then we simply provide an inline function to execute for each event, in our case inserting into the log stack which our LogOutput list box is bound to.</p>
<p>The result looks like this.</p>
<p><a href="http://blog.petegoo.com/wp-content/uploads/2011/11/CropperCapture2.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="CropperCapture[2]" border="0" alt="CropperCapture[2]" src="http://blog.petegoo.com/wp-content/uploads/2011/11/CropperCapture2_thumb.jpg" width="521" height="286" /></a></p>
<p>OK. So far so good. Now let’s add an actual search to the mix.</p>
<h3>Chaining the Asynchronous Search</h3>
<p>Before I add my search function I want to create a structure that will encapsulate the search term and it’s result.</p>
<pre class="brush: csharp;">public struct SearchResult {
    public string SearchTerm { get; set; }
    public IEnumerable&lt;string&gt; Results { get; set; }
}</pre>
<p>Next I add my search function. For now I’ve just created a synchronous function but chances are you would be calling an external service with <a title="Asynchronous Design Pattern Overview" href="http://msdn.microsoft.com/en-us/library/aa719595(v=vs.71).aspx" target="_blank">Async</a> methods (BeginXXX and EndXXX) for which you should use the <a href="http://rxwiki.wikidot.com/101samples#toc10" target="_blank">FromAsyncPattern</a> method instead of the <a title="Run a method asynchronously on demand" href="http://rxwiki.wikidot.com/101samples#toc2" target="_blank">ToAsync</a> I am using.</p>
<pre class="brush: csharp;">private SearchResult DoSearch(string searchTerm) {
    return new SearchResult {
        SearchTerm = searchTerm,
        Results =
            phrases.Where(item =&gt; item.ToUpperInvariant().Contains(searchTerm.ToUpperInvariant())).ToArray()
    };
}

private readonly string[] phrases = new[] {
    &quot;The badger knows something&quot;,
    &quot;Your head looks like a pineapple&quot;,
    &quot;etc...&quot;,
};</pre>
<p>And now for the magic. To invoke our search we add the following to our constructor:</p>
<pre class="brush: csharp;">// Setup an Observer for the search operation
var search = Observable.ToAsync&lt;string, SearchResult&gt;(DoSearch);

// Chain the input event stream and the search stream
var results = from searchTerm in input
              from result in search(searchTerm)
              select result;

// Log the search result and add the results to the results collection
results.ObserveOn(DispatcherScheduler.Instance)
.Subscribe(result =&gt; {
    searchResults.Clear();
    LogOutput.Insert(0, string.Format(&quot;Search for '{0}' returned '{1}' items&quot;, result.SearchTerm, result.Results.Count()));
    result.Results.ToList().ForEach(item =&gt; searchResults.Add(item));
    }
);</pre>
<p align="left">Here we firstly call <a title="Run a method asynchronously on demand" href="http://rxwiki.wikidot.com/101samples#toc2" target="_blank">ToAsync</a>, this will create a function that takes a string (our search term) and returns an Observable that will only ever produce one event (the Completed / End) and then close.</p>
<p align="left">We chain the incoming input stream with the result of the search function using <a href="http://msdn.microsoft.com/en-us/library/bb308959.aspx#linqoverview_topic5" target="_blank">simplified LINQ syntax</a> and produce a new observable of SearchResult. We then observe the result, logging and updating the autocomplete items.</p>
<p>The result is this:</p>
<p><a href="http://blog.petegoo.com/wp-content/uploads/2011/11/CropperCapture4.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="CropperCapture[4]" border="0" alt="CropperCapture[4]" src="http://blog.petegoo.com/wp-content/uploads/2011/11/CropperCapture4_thumb.jpg" width="477" height="302" /></a></p>
<p>OK. So this is round about where my mind exploded and grey matter started to leak out of my ears. Basically what is happening is we are treating these incoming events as collections before they actually happen, then we can manipulate them using LINQ and even chain the events much like pipelining in UNIX / Powershell.</p>
<p>We’re not done yet. We still have a number of issues.</p>
<h3>Using Throttle to enforce an idle period before searching</h3>
<p>One of the issues you can see in the above screenshot is that the search was done after every single key press. The owner of the service we are calling will not be too happy with us flooding them with unnecessary searches, so how do we stop this from happening. Typically we would create a timer that would wait for a period of inactivity before searching, we would have to reset the timer every time the user typed something so that the search is not performed for each of the previous characters and there would be quite a few lines of code required to actually do this.</p>
<p>With Rx we can use the <a href="http://rxwiki.wikidot.com/101samples#toc29" target="_blank">Throttle</a> operator which will quite effectively do exactly the behaviour we want for free. We change our previous declaration of the input stream to add the Throttle method.</p>
<pre class="brush: csharp;">var input = searchTextChanged
    .Throttle(TimeSpan.FromMilliseconds(400))
    .Select(args =&gt; SearchText);</pre>
<p align="left">Now if we test we should get something like the following:</p>
<p><a href="http://blog.petegoo.com/wp-content/uploads/2011/11/CropperCapture5.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="CropperCapture[5]" border="0" alt="CropperCapture[5]" src="http://blog.petegoo.com/wp-content/uploads/2011/11/CropperCapture5_thumb.jpg" width="428" height="182" /></a></p>
<p>That was too easy.</p>
<h3>Merging two event streams</h3>
<p>The next requirement was that I may want a larger throttle timeout for strings of less than 3 characters as people tend to type slower at the start of a search. To do this I needed to split my input stream into two different event streams that could be throttled differently.</p>
<pre class="brush: csharp;">var input = searchTextChanged
    .Where(ev =&gt; SearchText == null || SearchText.Length &lt; 4)
    .Throttle(TimeSpan.FromSeconds(3))
    .Merge(searchTextChanged
        .Where(ev =&gt; SearchText != null &amp;&amp; SearchText.Length &gt;= 4)
        .Throttle(TimeSpan.FromMilliseconds(400)))
    .Select(args =&gt; SearchText);</pre>
<p>So above I have simply cut the searchTextChanged stream 2 different ways, throttled them differently and then I can use the <a title="Merge" href="http://rxwiki.wikidot.com/101samples#toc41" target="_blank">Merge</a> operator to join the streams back together again into one.</p>
<h3></h3>
<h3>Creating a Reactive ICommand for MVVM</h3>
<p>The next requirement is that the search should be executed immediately if the user hits the <strong><em>enter</em></strong> key. To do this I decided to use the <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" target="_blank">MVVM ICommand</a> pattern. We need to add the following Input <a title="KeyBinding on MSDN" href="http://msdn.microsoft.com/en-us/library/system.windows.input.keybinding.aspx" target="_blank">KeyBinding</a> to the TextBox in our XAML so that the enter key will be picked up and we point it at the command we will write below.</p>
<pre class="brush: xml;">&lt;TextBox
    x:Name=&quot;SearchBox&quot;
    Text=&quot;{Binding SearchText, UpdateSourceTrigger=PropertyChanged}&quot;&gt;
    &lt;TextBox.InputBindings&gt;
        &lt;KeyBinding
            Command=&quot;{Binding TextBoxEnterCommand}&quot;
            Key=&quot;Enter&quot; /&gt;
    &lt;/TextBox.InputBindings&gt;
&lt;/TextBox&gt;</pre>
<p>The next thing we need to do is create our own command type. If you use an MVVM framework that understands Rx like ReactiveUI then you should get this for free but implementing a simple version yourself is not difficult. We simply take the <a title="RelayCommand" href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030" target="_blank">RelayCommand</a> defined by Josh Smith and add a <a title="Subject(Of T)" href="http://rxwiki.wikidot.com/101samples#toc48" target="_blank">Subject&lt;T&gt;</a> exposed as an Observable.</p>
<pre class="brush: csharp;">public class ReactiveRelayCommand : ICommand {
    private readonly Action&lt;object&gt; execute;
    private readonly Predicate&lt;object&gt; canExecute;

    public ReactiveRelayCommand(Action&lt;object&gt; execute)
        : this(execute, null) {
    }

    public ReactiveRelayCommand(Action&lt;object&gt; execute, Predicate&lt;object&gt; canExecute) {
        if (execute == null)
            throw new ArgumentNullException(&quot;execute&quot;);

        this.execute = execute;
        this.canExecute = canExecute;
    }

    [DebuggerStepThrough]
    public bool CanExecute(object parameter) {
        return canExecute == null || canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter) {
        execute(parameter);
        executed.OnNext(parameter);
    }

    private readonly Subject&lt;object&gt; executed = new Subject&lt;object&gt;();

    public IObservable&lt;object&gt; Executed {
        get { return executed; }
    }
}</pre>
<p>Notice that it exactly the same as the standard RelayCommand except that we use a Subject&lt;object&gt; as the backing implementation for our IObservable. We call <a title="OnNext of IObserver" href="http://msdn.microsoft.com/en-us/library/dd782792.aspx" target="_blank">OnNext</a> whenever the command is Executed.</p>
<p>Add the following field and property to the viewmodel class to store our command:</p>
<pre class="brush: csharp;">private ReactiveRelayCommand textBoxEnterCommand;
public ReactiveRelayCommand TextBoxEnterCommand {
    get { return textBoxEnterCommand; }
    set { textBoxEnterCommand = value; }
}</pre>
<p>Then at the start of our constructor we setup the command itself:</p>
<pre class="brush: csharp;">// Setup the command for the enter key on the textbox
textBoxEnterCommand = new ReactiveRelayCommand(obj =&gt; { });</pre>
<p>Next we need to change our input event stream to take into account our command and merge that with our SearchText property change events so that either can fire our search:</p>
<pre class="brush: csharp;">// Transform the event stream into a stream of strings (the input values)
var input = searchTextChanged
    .Where(ev =&gt; SearchText == null || SearchText.Length &lt; 4)
    .Throttle(TimeSpan.FromSeconds(3))
    .Merge(searchTextChanged
        .Where(ev =&gt; SearchText != null &amp;&amp; SearchText.Length &gt;= 4)
        .Throttle(TimeSpan.FromMilliseconds(400)))
    .Select(args =&gt; SearchText)
    .Merge(
        textBoxEnterCommand.Executed.Select(e =&gt; SearchText));</pre>
<p>Notice we have just added the last line to merge the Executed observable on our command. Now when we run we can type a single character and hit enter if we do not want to wait for the idle period. How easy was that? Are we done? Almost.</p>
<h3></h3>
<h3>Removing duplicate consecutive events</h3>
<p>We still have an issue that when the user presses Enter, the idle timeout will expire some time later and we will get another event firing, essentially performing our search twice. So how do we stop the second duplicate event from being fired, easy, we just use <a title="DistinctUntilChanged" href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.distinctuntilchanged(v=vs.103).aspx" target="_blank">DistinctUntilChanged</a>. </p>
<p>We want a distinct search but we still want to allow the same search to be done later if the user tries another search in between. In other words we can have the same search done twice as long as they aren’t consecutive searches.</p>
<pre class="brush: csharp;">// Transform the event stream into a stream of strings (the input values)
var input = searchTextChanged
    .Where(ev =&gt; SearchText == null || SearchText.Length &lt; 4)
    .Throttle(TimeSpan.FromSeconds(3))
    .Merge(searchTextChanged
        .Where(ev =&gt; SearchText != null &amp;&amp; SearchText.Length &gt;= 4)
        .Throttle(TimeSpan.FromMilliseconds(400)))
    .Select(args =&gt; SearchText)
    .Merge(
        textBoxEnterCommand.Executed.Select(e =&gt; SearchText))
    .DistinctUntilChanged();</pre>
<p>&#160;</p>
<h3>Cancelling previous searches with TakeUntil</h3>
<p>The last issue here is that when searches return out of sequence, we could get the wrong results displayed. For example, the user searches for <strong>cr</strong> hits enter but then types <strong>crazy</strong> and hits enter. If the first search is taking a long time because of the number of results then the results for it will end up being displayed after the actual current search term is displayed. To simulate this we could add some latency to our search.</p>
<pre class="brush: csharp;">private readonly Random random = new Random(5);
private SearchResult DoSearch(string searchTerm) {
    Thread.Sleep(random.Next(100, 500)); // Simulate latency
    return new SearchResult {
        SearchTerm = searchTerm,
        Results =
            phrases.Where(item =&gt; item.ToUpperInvariant().Contains(searchTerm.ToUpperInvariant())).ToArray()
    };
}</pre>
<p>To solve this we need to stop the Async stream when more input is given, this is pretty easy with the TakeUntil operator. Take operators define a completion for an event stream. In the case of an Async operation this will effectively cancel the Async subscription. TakeUntil takes an observable as input such that an event on that stream will complete the current stream. To implement this change we simply say the we TakeUntil the <strong><em>input</em></strong> stream in our chaining code.</p>
<pre class="brush: csharp;">// Chain the input event stream and the search stream, cancelling searches when input is received
var results = from searchTerm in input
              from result in search(searchTerm).TakeUntil(input)
              select result;</pre>
<h3></h3>
<h3>Summary</h3>
<p>So we have managed to create the guts of an auto-complete control using Rx in a much more declarative way by responding to events in observables instead of writing lots of imperative code with little items of state sitting about to represent our state machine.</p>
<p>All of the heavy work can be easily seen in a single declaration of intent:</p>
<pre class="brush: csharp;">// Setup the command for the enter key on the textbox
textBoxEnterCommand = new ReactiveRelayCommand(obj =&gt; { });

// Listen to all property change events on SearchText
var searchTextChanged = Observable.FromEventPattern&lt;PropertyChangedEventHandler, PropertyChangedEventArgs&gt;(
    ev =&gt; PropertyChanged += ev,
    ev =&gt; PropertyChanged -= ev
    )
    .Where(ev =&gt; ev.EventArgs.PropertyName == &quot;SearchText&quot;);

// Transform the event stream into a stream of strings (the input values)
var input = searchTextChanged
    .Where(ev =&gt; SearchText == null || SearchText.Length &lt; 4)
    .Throttle(TimeSpan.FromSeconds(3))
    .Merge(searchTextChanged
        .Where(ev =&gt; SearchText != null &amp;&amp; SearchText.Length &gt;= 4)
        .Throttle(TimeSpan.FromMilliseconds(400)))
    .Select(args =&gt; SearchText)
    .Merge(
        textBoxEnterCommand.Executed.Select(e =&gt; SearchText))
    .DistinctUntilChanged();

// Log all events in the event stream to the Log viewer
input.ObserveOn(DispatcherScheduler.Instance)
    .Subscribe(e =&gt; LogOutput.Insert(0,
        string.Format(&quot;Text Changed. Current Value - {0}&quot;, e)));

// Setup an Observer for the search operation
var search = Observable.ToAsync&lt;string, SearchResult&gt;(DoSearch);

// Chain the input event stream and the search stream, cancelling searches when input is received
var results = from searchTerm in input
              from result in search(searchTerm).TakeUntil(input)
              select result;

// Log the search result and add the results to the results collection
results.ObserveOn(DispatcherScheduler.Instance)
.Subscribe(result =&gt; {
    searchResults.Clear();
    LogOutput.Insert(0, string.Format(&quot;Search for '{0}' returned '{1}' items&quot;, result.SearchTerm, result.Results.Count()));
    result.Results.ToList().ForEach(item =&gt; searchResults.Add(item));
    }
);</pre>
<p>&#160;</p>
<p>Lots of the ideas and even the odd piece of code were taken from:</p>
<ul>
<li><a title="Bart De Smet - Blog" href="http://bartdesmet.net/blogs/bart/default.aspx" target="_blank">Bart De Smet</a> on <a title="DevCamp 2010 Keynote - Rx: Curing your asynchronous programming blues" href="http://channel9.msdn.com/Blogs/codefest/DC2010T0100-Keynote-Rx-curing-your-asynchronous-programming-blues" target="_blank">Curing Asynchronous Blues</a> </li>
<li><a href="http://stackoverflow.com/questions/1763411/reactive-extensions-rx-mvvm" target="_blank">Stack Overflow</a>
<p></p>
<div class="xdownload">
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F60BB8FA-6F02-4999-8F5E-9DD4E92C4DA7:fc7f2917-f963-4fbb-b889-f5b061331d26" class="wlWriterEditableSmartContent">
<div><a href="http://blog.petegoo.com/wp-content/uploads/2011/11/AutoCompleteBlog.zip" target="_self">AutoCompleteBlog.zip</a></div>
</div></div>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2011/11/22/building-an-auto-complete-control-with-reactive-extensions-rx/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>More efficient file enumeration in .Net 4</title>
		<link>http://blog.petegoo.com/index.php/2011/11/18/more-efficient-file-enumeration-in-net-4/</link>
		<comments>http://blog.petegoo.com/index.php/2011/11/18/more-efficient-file-enumeration-in-net-4/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 09:39:59 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[BCL]]></category>
		<category><![CDATA[File System]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/index.php/2011/11/18/more-efficient-file-enumeration-in-net-4/</guid>
		<description><![CDATA[This may be basics to some people but I thought it was worth mentioning. I was writing some simple code recently to compare the files in a remote directory with those in a local directory to determined if the remote &#8230; <a href="http://blog.petegoo.com/index.php/2011/11/18/more-efficient-file-enumeration-in-net-4/">Continued</a>]]></description>
			<content:encoded><![CDATA[<p>This may be basics to some people but I thought it was worth mentioning. I was writing some simple code recently to compare the files in a remote directory with those in a local directory to determined if the remote was newer in any way. This seemed like a really simple problem so I made my first stab at it.</p>
<pre class="brush: csharp;">return (from remoteFile in Directory.GetFiles(remotePath)
        join localFile in Directory.GetFiles(localPath)
            on Path.GetFileName(remoteFile) equals Path.GetFileName(localFile)
        where File.GetLastWriteTimeUtc(remotePath) &gt; File.GetLastWriteTimeUtc(localPath)
        select remoteFile).Any();</pre>
<p>&#160;</p>
<p>It became very apparent that there were some performance issues when running this code, especially when the remote location introduces any form of latency. The first issue is with Directory.GetFiles, if you actually reflect this method you will see that it ultimately calls the following:</p>
<pre class="brush: csharp;">return new List&lt;string&gt;(FileSystemEnumerableFactory.CreateFileNameIterator(path, userPathOriginal, searchPattern, includeFiles, includeDirs, searchOption)).ToArray();</pre>
<p>The existence of the ToArray means the full file list will be enumerated before the method returns, however we only care if any file has changed so it would be better if we had an enumerator so we could exit early when the first newer file is found. This is also true when performing the join as this will enumerate the joined collection first before enumerating the full original collection of remote files and then joining them.</p>
<p>We could solve the above issues using the new <a title="Directory.EnumerateFiles on MSDN" href="http://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles.aspx" target="_blank">Directory.EnumerateFiles</a> method which will return an enumerator that will yield each file as it is enumerated. We could also get rid of the join and enumerate all the local files first before in a separate operation to allow the more expensive remote enumeration happen in sequence.</p>
<p>The next problem in the original attempt is that we are returning to the remote files to call another operation to evaluate the last write time stamp on the file metadata. This requires us to return to the remote file system and incur the same latency per file. I originally tried to solve this problem using the <a href="http://www.codeproject.com/KB/files/FastDirectoryEnumerator.aspx?msg=3218547" target="_blank">Fast Directory Enumerator on code project</a> which allowed me to enumerate the list of remote files at the same time as retrieving the file info, thus removing the need to return to the scene of the crime. This seemed to work ok but I was having an issue with it not completing the remote file enumeration sequence and discovered that there is actually an implementation introduced in .Net 4. The very well hidden <a title="DirectoryInfo.EnumerateFiles on MSDN" href="http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.enumeratefiles.aspx" target="_blank">EnumerateFiles</a> on DirectoryInfo was the answer.</p>
<pre class="brush: csharp;">var localFiles = new DirectoryInfo(localPath).GetFiles();

return new DirectoryInfo(remotePath).EnumerateFiles()
    .Any(remoteFile =&gt; (from localFile in localFiles
                        where localFile.Name == remoteFile.Name
                        &amp;&amp; remoteFile.LastWriteTimeUtc &gt; localFile.LastWriteTimeUtc
                        select remoteFile).Any());</pre>
<p>Notice the remote files retrieval now uses the EnumerateFiles method on DirectoryInfo. This allows us to exit when the first item matches the condition in the Any clause.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2011/11/18/more-efficient-file-enumeration-in-net-4/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Arghhh! Simultaneous Connection Limit in IIS (Windows 7)</title>
		<link>http://blog.petegoo.com/index.php/2011/11/10/arghhh-simultaneous-connection-limit-in-iis-windows-7/</link>
		<comments>http://blog.petegoo.com/index.php/2011/11/10/arghhh-simultaneous-connection-limit-in-iis-windows-7/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 09:27:36 +0000</pubDate>
		<dc:creator>PeteGoo</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[IIS]]></category>
		<category><![CDATA[SignalR]]></category>

		<guid isPermaLink="false">http://blog.petegoo.com/index.php/2011/11/10/arghhh-simultaneous-connection-limit-in-iis-windows-7/</guid>
		<description><![CDATA[I’ve been playing with SignalR recently and it drives me nuts that I can’t have more than a few simultaneous long polling requests open to the IIS server on Windows 7. It stops responding after about 2 clients. Even IIS &#8230; <a href="http://blog.petegoo.com/index.php/2011/11/10/arghhh-simultaneous-connection-limit-in-iis-windows-7/">Continued</a>]]></description>
			<content:encoded><![CDATA[<p>I’ve been playing with <a title="SignalR" href="https://github.com/SignalR" target="_blank">SignalR</a> recently and it drives me nuts that I can’t have more than a few simultaneous long polling requests open to the IIS server on Windows 7. It stops responding after about 2 clients. Even IIS Express supports unlimited simultaneous connections but we need AppFabric support.</p>
<p>We would seriously consider using it for our messaging solution but on a single machine developer install, we would need to come up with another solution for our many client apps.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.petegoo.com/index.php/2011/11/10/arghhh-simultaneous-connection-limit-in-iis-windows-7/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

