<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>My Logic Is Undeniable</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/mrtechnocal/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/mrtechnocal/feed.xml</link>
    <description />
    <lastBuildDate>Tue, 16 Apr 2019 05:19:42 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Unit of Work - Expanded</title>
      <link>https://docs.microsoft.com/archive/blogs/mrtechnocal/unit-of-work-expanded</link>
      <pubDate>Fri, 18 Apr 2014 15:28:00 GMT</pubDate>
      <dc:creator><![CDATA[Chris_Martinez_77]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mrtechnocal/2014/04/18/unit-of-work-expanded/</guid>
      <description><![CDATA[In a previous post I discussed asynchronous repositories. A closely related and complimentary design...]]></description>
      <content:encoded><![CDATA[<p>In a previous post I discussed <a href="http://blogs.msdn.com/b/mrtechnocal/archive/2014/03/16/asynchronous-repositories.aspx">asynchronous repositories</a>. A closely related and complimentary design pattern is the <em>Unit of Work</em> pattern. In this post, I'll summarize the design pattern and cover a few non-conventional, but useful extensions.</p>
<h1>Overview</h1>
<p>The <em>Unit of Work</em> is a common design pattern used to manage the state changes to a set of objects. A unit of work abstracts all of the persistence operations and logic from other aspects of an application. Applying the pattern not only simplifies code that possess persistence needs, but it also makes changing or otherwise swapping out persistence strategies and methods easy.</p>
<p>A basic <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">unit of work</a> has the following characteristics:</p>
<ul>
<li><strong>Register New</strong> - registers an object for insertion.</li>
<li><strong>Register Updated</strong> - registers an object for modification.</li>
<li><strong>Register Removed</strong> - registers an object for deletion.</li>
<li><strong>Commit</strong> - commits all pending work.</li>
<li><strong>Rollback </strong>- discards all pending work.</li>
</ul>
<h1>Extensions</h1>
<p>The basic design pattern supports most scenarios, but there are a few additional use cases that are typically not addressed. For stateful applications, it is usually desirable to support cancellation or simple undo operations by using deferred persistence. While this capability is covered via a rollback, there is not a way to interrogate whether a unit of work has pending changes.</p>
<p>Imagine your application has the following requirements:</p>
<ul>
<li>As a user, I should only be able to save when there are uncommitted changes.</li>
<li>As a user, I should be prompted when I cancel an operation with uncommitted changes.</li>
</ul>
<p>To satisfy these requirements, we only need to make a couple of additions:</p>
<ul>
<li><strong>Unregister</strong> - unregisters pending work for an object.</li>
<li><strong>Has Pending Changes </strong>- indicates whether the unit of work contains uncommitted items.</li>
<li><strong>Property Changed</strong> - raises an event when a property has changed.</li>
</ul>
<h1>Generic Interface</h1>
<p>After reconsidering what is likely the majority of all plausible usage scenarios, we now have enough information to create a general purpose interface.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">interface</span> <span style="color: #2b91af;">IUnitOfWork</span>&lt;T&gt; : <span style="color: #2b91af;">INotifyPropertyChanged</span> <span style="color: blue;">where</span> T : <span style="color: blue;">class</span><br />{<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">bool</span> HasPendingChanges<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">get</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">void</span> RegisterNew( T item );<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">void</span> RegisterChanged( T item );<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">void</span> RegisterRemoved( T item );<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">void</span> Unregister( T item );<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">void</span> Rollback();<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #2b91af;">Task</span> CommitAsync( <span style="color: #2b91af;">CancellationToken</span> cancellationToken );<br />} </span></p>
<h1>Base Implementation</h1>
<p>It would be easy to stop at the generic interface definition, but we can do better. It is pretty straightforward to create a base implementation that handles just about everything except the commit operation.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">abstract</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">UnitOfWork</span>&lt;T&gt; : <span style="color: #2b91af;">IUnitOfWork</span>&lt;T&gt; <span style="color: blue;">where</span> T : <span style="color: blue;">class</span><br />{<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">IEqualityComparer</span>&lt;T&gt; comparer;<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">HashSet</span>&lt;T&gt; inserted;<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">HashSet</span>&lt;T&gt; updated;<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">HashSet</span>&lt;T&gt; deleted;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">protected</span> UnitOfWork()<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">protected</span> UnitOfWork( <span style="color: #2b91af;">IEqualityComparer</span>&lt;T&gt; comparer )<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">protected</span> <span style="color: #2b91af;">IEqualityComparer</span>&lt;T&gt; Comparer { <span style="color: blue;">get</span>; }<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">protected</span> <span style="color: blue;">virtual</span> <span style="color: #2b91af;">ICollection</span>&lt;T&gt; InsertedItems { <span style="color: blue;">get</span>; }<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">protected</span> <span style="color: blue;">virtual</span> <span style="color: #2b91af;">ICollection</span>&lt;T&gt; UpdatedItems { <span style="color: blue;">get</span>; }<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">protected</span> <span style="color: blue;">virtual</span> <span style="color: #2b91af;">ICollection</span>&lt;T&gt; DeletedItems { <span style="color: blue;">get</span>; }<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">bool</span> HasPendingChanges { <span style="color: blue;">get</span>; }<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">protected</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> OnPropertyChanged( <span style="color: #2b91af;">PropertyChangedEventArgs</span> e )<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;protected</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> AcceptChanges()<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;protected</span> <span style="color: blue;">abstract</span> <span style="color: blue;">bool</span> IsNew( T item )<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> RegisterNew( T item )<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> RegisterChanged( T item )<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> RegisterRemoved( T item )<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> Unregister( T item )<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> Rollback()<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">abstract</span> <span style="color: #2b91af;">Task</span> CommitAsync( <span style="color: #2b91af;">CancellationToken</span> cancellationToken );<br /><br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">event</span> <span style="color: #2b91af;">PropertyChangedEventHandler</span> PropertyChanged;<br />} </span></p>
<p>Obviously by now, you've noticed that we've added a few protected members to support the implementation. We use <strong>HashSet&lt;T&gt;</strong> to track all inserts, updates, and deletes. By using <strong>HashSet&lt;T&gt;</strong>, we can easily ensure we don't track an entity more than once. We can also now apply some basic logic such as inserts should never enqueue for updates and deletes against uncommitted inserts should be negated. In addition, we add the ability to accept (e.g. clear) all pending work after the commit operation has completed successfully.</p>
<h1>Supporting a Unit of Work Service Locator</h1>
<p>Once we have all the previous pieces in place, we could again stop, but there are multiple ways in which a unit of work could be used in an application that we should consider:</p>
<ul>
<li>Imperatively instantiated in code</li>
<li>Composed or inserted via dependency injection</li>
<li>Centrally retrieved via a special service locator facade</li>
</ul>
<p>The decision as to which approach to use is at a developer's discretion. In general, when composition or dependency injection is used, the implementation is handed by another library and some mediating object (ex: a controller) will own the logic as to when or if entities are added to the unit of work. When a service locator is used, most or all of the logic can be baked directly into an object to enable self-tracking. In the rest of this section, we'll explore a <strong>UnitOfWork </strong>singleton that plays the role of a service locator.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 8pt;"><span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">UnitOfWork</span><br />{<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">IUnitOfWorkFactoryProvider</span> Provider<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;get</span>;<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;set</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">IUnitOfWork</span>&lt;TItem&gt; Create&lt;TItem&gt;() <span style="color: blue;">where</span> TItem : <span style="color: blue;">class</span><br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">IUnitOfWork</span>&lt;TItem&gt; GetCurrent&lt;TItem&gt;() <span style="color: blue;">where</span> TItem : <span style="color: blue;">class</span><br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> <span style="color: #2b91af;">SetCurrent</span>&lt;TItem&gt;( <span style="color: #2b91af;">IUnitOfWork</span>&lt;TItem&gt; unitOfWork ) <span style="color: blue;">where</span> TItem : <span style="color: blue;">class</span><br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">IUnitOfWork</span>&lt;TItem&gt; NewCurrent&lt;TItem&gt;() <span style="color: blue;">where</span> TItem : <span style="color: blue;">class</span><br />} </span></p>
<h2>Populating the Service Locator</h2>
<p>In order to locate a unit of work, the locator must be backed with code that can resolve it. We should also consider composite applications where there may be many units of work defined by different sources. The <strong>UnitOfWork </strong>singleton is configured by supplying an instance to the static <strong>Provider </strong>property.</p>
<h3>Unit of Work Factory Provider</h3>
<p>The <strong>IUnitOfWorkFactoryProvider </strong>interface can simply be thought of as a factory of factories. It provides a central mechanism for the service locator to resolve a unit of work via all known factories. In composite applications, implementers will likely want to use dependency injection. For ease of use, a default implementation is provided whose constructor accepts <strong>Func&lt;IEnumerable&lt;IUnitOfWorkFactory&gt;&gt;</strong>.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">interface</span> <span style="color: #2b91af;">IUnitOfWorkFactoryProvider</span><br />{<br /><span style="color: #2b91af;">&nbsp;&nbsp;&nbsp;&nbsp;IEnumerable</span>&lt;<span style="color: #2b91af;">IUnitOfWorkFactory</span>&gt; Factories<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">get</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />} </span></p>
<h3>Unit of Work Factory</h3>
<p>The <strong>IUnitOfWorkFactory </strong>interface is used to register, create, and resolve units of work. Implementers have the option to map as many units of work to a factory as they like. In most scenarios, only one factory is required per application or composite component (ex: plug-in). A default implementation is provided that only requires the factory to register a function to create or resolve a unit of work for a given type. The <em>Specification</em> pattern is used to match or select the appropriate factory, but the exploration of that pattern is reserved for another time.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">interface</span> <span style="color: #2b91af;">IUnitOfWorkFactory</span><br />{<br /><span style="color: #2b91af;">&nbsp;&nbsp;&nbsp;&nbsp;ISpecification</span>&lt;<span style="color: #2b91af;">Type</span>&gt; Specification<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;get</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br /><span style="color: #2b91af;">&nbsp;&nbsp;&nbsp;&nbsp;IUnitOfWork</span>&lt;TItem&gt; Create&lt;TItem&gt;() <span style="color: blue;">where</span> TItem : <span style="color: blue;">class</span>;<br /><span style="color: #2b91af;">&nbsp;&nbsp;&nbsp;&nbsp;IUnitOfWork</span>&lt;TItem&gt; GetCurrent&lt;TItem&gt;() <span style="color: blue;">where</span> TItem : <span style="color: blue;">class</span>;<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;void</span> SetCurrent&lt;TItem&gt;( <span style="color: #2b91af;">IUnitOfWork</span>&lt;TItem&gt; unitOfWork ) <span style="color: blue;">where</span> TItem : <span style="color: blue;">class</span>;<br />} </span></p>
<h2>Minimizing Test Setup</h2>
<p>While all of factory interfaces make it flexible to support a configurable <strong>UnitOfWork </strong>singleton, it is somewhat painful to set up test cases. If the required unit of work is not resolved, an exception will be thrown; however, if the test doesn't involve a unit of work, why should we have to set one up?</p>
<p>To solve this problem, the service locator will internally create a compatible <em>uncommitable unit of work</em> instance whenever a unit of work cannot be resolved. This behavior allows self-tracking objects to be used without having to explicitly set up a mock or stub unit of work. You might be thinking that this behavior hides composition or dependency resolution failures and that is true. However, any attempt to commit against these instances will throw an <strong>InvalidOperationException</strong>, indicating that the unit of work is uncommitable. This approach is the most sensible method of avoiding unnecessary setups, while not completely hiding resolution failures. Whenever a unit of work fails in this manner, a developer should realize that they have not set up their test correctly (ex: verifying commit behavior) or resolution is failing at run time.</p>
<h1>Examples</h1>
<p>The following outlines some scenarios as to how a unit of work might be used. For each example, we'll use the following model:</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Person</span><br />{<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">int</span> PersonId { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: blue;">string</span> FirstName { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: blue;">string</span> LastName { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<br />} </span></p>
<h2>Implementing a Unit of Work with the Entity Framework</h2>
<p>The following demonstrates a simple unit of work that is backed by the Entity Framework:</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">PersonUnitOfWork</span> : <span style="color: #2b91af;">UnitOfWork</span>&lt;<span style="color: #2b91af;">Person</span>&gt;<br />{<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;protected</span> <span style="color: blue;">override</span> <span style="color: blue;">bool</span> IsNew( <span style="color: #2b91af;">Person</span> item )<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: green;">// any unsaved item will have an unset id</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">return</span> item.PersonId == 0;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">async</span> <span style="color: #2b91af;">Task</span> CommitAsync( <span style="color: #2b91af;">CancellationToken</span> cancellationToken )<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">using</span> ( <span style="color: blue;">var</span> context = <span style="color: blue;">new</span> <span style="color: #2b91af;">MyDbContext</span>() )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">foreach</span> ( <span style="color: blue;">var</span> item <span style="color: blue;">in</span> <span style="color: blue;">this</span>.Inserted )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;context.People.Add( item );<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">foreach</span> ( <span style="color: blue;">var</span> item <span style="color: blue;">in</span> <span style="color: blue;">this</span>.Updated )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;context.People.Attach( item );<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">foreach</span> ( <span style="color: blue;">var</span> item <span style="color: blue;">in</span> <span style="color: blue;">this</span>.Deleted )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;context.People.Remove( item );<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">await</span> context.SaveChangesAsync( cancellationToken );<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.AcceptChanges();<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />} </span></p>
<h2>Using a Unit of Work to Drive User Interactions</h2>
<p>The following example illustrates using a unit of work in a rudimentary Windows Presentation Foundation (WPF) window that contains buttons to add, remove, cancel, and apply (or save) changes to a collection of people. The recommended approach to working with presentation layers such as WPF is to use the Model-View-View Model (MVVM) design pattern. For the sake of brevity and demonstration purposes, this example will use simple, albeit difficult to test, event handlers. All of the persistence logic is contained within the unit of work and the unit of work can report whether it has any pending work to help inform a user when there are changes. The unit of work can also be used to verify that the user truly wants to discard uncommitted changes, if there are any.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">partial</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyWindow</span> : <span style="color: #2b91af;">Window</span><br />{<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">IUnitOfWork</span>&lt;<span style="color: #2b91af;">Person</span>&gt; unitOfWork;<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> MyWindow() : <span style="color: blue;">this</span>( <span style="color: blue;">new</span> <span style="color: #2b91af;">PersonUnitOfWork</span>() ) { }<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> MyWindow( <span style="color: #2b91af;">IUnitOfWork</span>&lt;<span style="color: #2b91af;">Person</span>&gt; unitOfWork )<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.InitializeComponent();<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this</span>.ApplyButton.IsEnabled = <span style="color: blue;">false</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.People = <span style="color: blue;">new</span> <span style="color: #2b91af;">ObservableCollection</span>&lt;<span style="color: #2b91af;">Person</span>&gt;();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.unitOfWork = unitOfWork;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.unitOfWork.PropertyChanged +=<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;( s, e ) =&gt; <span style="color: blue;">this</span>.ApplyButton.IsEnabled = <span style="color: blue;">this</span>.unitOfWork.HasPendingChanges;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: #2b91af;">Person</span> SelectedPerson { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: #2b91af;">ObservableCollection</span>&lt;<span style="color: #2b91af;">Person</span>&gt; People { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">void</span> AddButton_Click( <span style="color: blue;">object</span> sender, <span style="color: #2b91af;">RoutedEventArgs</span> e )<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">var</span> person = <span style="color: blue;">new</span> <span style="color: #2b91af;">Person</span>();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: green;">// TODO: custom logic</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.People.Add( person );<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.unitOfWork.RegisterNew( person );<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">void</span> RemoveButton_Click( <span style="color: blue;">object</span> sender, <span style="color: #2b91af;">RoutedEventArgs</span> e )<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">var</span> person = <span style="color: blue;">this</span>.SelectedPerson;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">if</span> ( person == <span style="color: blue;">null</span> ) <span style="color: blue;">return</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.People.Remove( person );<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.unitOfWork.RegisterRemoved( person );<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">async</span> <span style="color: blue;">void</span> ApplyButton_Click( <span style="color: blue;">object</span> sender, <span style="color: #2b91af;">RoutedEventArgs</span> e )<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">await</span> <span style="color: blue;">this</span>.unitOfWork.CommitAsync( <span style="color: #2b91af;">CancellationToken</span>.None );<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">void</span> CancelButton_Click( <span style="color: blue;">object</span> sender, <span style="color: #2b91af;">RoutedEventArgs</span> e )<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">if</span> ( <span style="color: blue;">this</span>.unitOfWork.HasPendingChanges )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">var</span> message = <span style="color: #a31515;">"Discard unsaved changes?"</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">var</span> title = <span style="color: #a31515;">"Save"</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">var</span> buttons = <span style="color: #2b91af;">MessageBoxButton</span>.YesNo;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">var</span> answer = <span style="color: #2b91af;">MessageBox</span>.Show( message, title, buttons );<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">if</span> ( answer == <span style="color: #2b91af;">DialogResult</span>.No ) <span style="color: blue;">return</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.unitOfWork.Rollback();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.Close();<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />} </span></p>
<h2>Implementing a Self-Tracking Entity</h2>
<p>There are many different ways and varying degrees of functionality that can be implemented for a self-tracking entity. The following is one of many possibilities that illustrates just enough to convey the idea. The first thing we need to do is create a factory.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyUnitOfWorkFactory</span> : <span style="color: #2b91af;">UnitOfWorkFactory</span><br />{<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> MyUnitOfWorkFactory()<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.RegisterFactoryMethod( () =&gt; <span style="color: blue;">new</span> <span style="color: #2b91af;">PersonUnitOfWork</span>() );<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: green;">// additional units of work could be defined here</span><br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />} </span></p>
<p>Then we need to wire up the service locator with a provider that contains the factory.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">var</span> factories = <span style="color: blue;">new</span> <span style="color: #2b91af;">IUnitOfWorkFactory</span>[]{ <span style="color: blue;">new</span> <span style="color: #2b91af;">MyUnitOfWorkFactory</span>() };<br /><span style="color: #2b91af;">UnitOfWork</span>.Provider = <span style="color: blue;">new</span> <span style="color: #2b91af;">UnitOfWorkFactoryProvider</span>( () =&gt; factories ); </span></p>
<p>Finally, we can refactor the entity to enable self-tracking.</p>
<p style="background: #f2f2f2;"><span style="font-family: Consolas; font-size: 9pt;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Person</span><br />{<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">string</span> firstName;<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">private</span> <span style="color: blue;">string</span> lastName;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: blue;">int</span> PersonId<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">get</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">set</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br /><span style="color: blue;">&nbsp;&nbsp;&nbsp;&nbsp;public</span> <span style="color: blue;">string</span> FirstName<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">get</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">return</span> <span style="color: blue;">this</span>.firstName;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">set</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.firstName = <span style="color: blue;">value</span>;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #2b91af;">UnitOfWork</span>.GetCurrent&lt;<span style="color: #2b91af;">Person</span>&gt;().RegisterChanged( <span style="color: blue;">this</span> );<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: blue;">string</span> LastName<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">get</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">return</span> <span style="color: blue;">this</span>.lastName;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">set</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">this</span>.lastName = value;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #2b91af;">UnitOfWork</span>.GetCurrent&lt;<span style="color: #2b91af;">Person</span>&gt;().RegisterChanged( <span style="color: blue;">this</span> );<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">Person</span> CreateNew()<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">var</span> person = <span style="color: blue;">new</span> <span style="color: #2b91af;">Person</span>();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #2b91af;">UnitOfWork</span>.GetCurrent&lt;<span style="color: #2b91af;">Person</span>&gt;().RegisterNew( person );<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">return</span> person;<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: blue;">void</span> Delete()<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #2b91af;">UnitOfWork</span>.GetCurrent&lt;<span style="color: #2b91af;">Person</span>&gt;().RegisterRemoved( <span style="color: blue;">this</span> );<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">public</span> <span style="color: #2b91af;">Task</span> SaveAsync()<br />&nbsp;&nbsp;&nbsp;&nbsp;{<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: blue;">return</span> <span style="color: #2b91af;">UnitOfWork</span>.GetCurrent&lt;<span style="color: #2b91af;">Person</span>&gt;().CommitAsync( <span style="color: #2b91af;">CancellationToken</span>.None );<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />} </span></p>
<h1>Conclusion</h1>
<p>In this article we examined the <em>Unit of Work</em> pattern, added a few useful extensions to it, and demonstrated some common uses cases as to how you can apply the pattern. There are many implementations for the <em>Unit of Work</em> pattern and the concepts outlined in this article are no more <em>correct</em> than any of the alternatives. Hopefully you finish this article with a better understanding of the pattern and its potential uses. Although I didn't explicitly discuss unit testing, my belief is that most readers will recognize the benefits and ease in which cross-cutting persistence requirements can be tested using a unit of work. I've attached all the code required to leverage the <em>Unit of Work</em> pattern as described in this article in order to accelerate your own development, should you choose to do so.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/51/86/82/UnitOfWorkExpanded.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-51-86-82/UnitOfWorkExpanded.zip">UnitOfWorkExpanded.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Asynchronous Repositories</title>
      <link>https://docs.microsoft.com/archive/blogs/mrtechnocal/asynchronous-repositories</link>
      <pubDate>Sun, 16 Mar 2014 15:16:00 GMT</pubDate>
      <dc:creator><![CDATA[Chris_Martinez_77]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mrtechnocal/2014/03/16/asynchronous-repositories/</guid>
      <description><![CDATA[The Repository pattern has long been tried and tested. There are also countless scaffolding tools...]]></description>
      <content:encoded><![CDATA[<p>The <em>Repository</em> pattern has long been tried and tested. There are also countless scaffolding tools for generating boilerplate repositories for established data access technologies, such as the <a href="http://msdn.microsoft.com/en-us/data/ef.aspx">Entity Framework</a>. Despite improvements in tools like the Entity Framework, not much has been done to update the <em>Repository </em>pattern to leverage the best of LINQ and the asynchronous enhancements in the .NET Framework.</p>
<p>In this article, I'll describe how to improve upon the classic <em>Repository </em>pattern by maintaining the fidelity of the original design, while adding asynchronous support and providing LINQ query composition for more complex scenarios.</p>
<h1>The Read-Only Repository</h1>
<p>When I first began evaluating whether a generic interface could be extracted from the numerous, existing scaffolding examples I found, two things became abundantly clear. First, it was definitely possible to extract a simple, reusable interface. It also occurred to me that there are a number of scenarios where you might want a read-only repository; thus, the <strong>IReadOnlyRepository&lt;T&gt;</strong> interface was born.</p>
<p>The idea behind this interface is analogous to <strong>IReadOnlyList&lt;T&gt;</strong>. I also had the goal of making the required implementation as minimal as possible.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/7762.031714_2059_Asynchronou1.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/7762.031714_5F00_2059_5F00_Asynchronou1.png" alt="" /></p>
<p>&nbsp;</p>
<p>The method signatures might seem a little strange at first, but it will make sense soon enough. I attempted many variations, but this was the only one that retained LINQ query composition without requiring the repository to be disposable. It also made creating a repository for the <em>Per-Request</em> model easy.</p>
<p>You might think that only one method is needed, but as we'll see in an example later, there is a subtle difference. The first signature will match most query operations, while the second signature is used primarily for query projections to scalar results, such as an asynchronous count.</p>
<h2>Asynchronous Queries</h2>
<p>To further explain the method signatures, we first need to examine what it takes to execute a LINQ query asynchronously. LINQ is based on <strong>IQueryable&lt;T&gt;</strong>, which is based on <strong>IEnumerable&lt;T&gt;</strong>. Since <strong>IEnumerable&lt;T&gt;</strong> is not asynchronous, neither is <strong>IQueryable&lt;T&gt;</strong>. To solve this problem and maintain query capabilities, we use a callback function to <em>shape </em>the query just prior to execution. This also provides a lot of flexibility in how the query is executed. For example, if the repository is backed by the <a href="http://msdn.microsoft.com/en-us/data/ef.aspx">Entity Framework</a> 6.0 or above, you can simply leverage its intrinsic asynchronous extensions. However, if you're using another queryable source, such as a <strong>DataServiceContext</strong>, you'll have to wrap and execute the query with a Task on your own. Ultimately, this approach enables asynchronous query execution regardless of whether the underlying query provider supports such operations. In a follow up post, I'll illustrate how take the concepts from the <a href="http://msdn.microsoft.com/en-us/data/ef.aspx">Entity Framework</a> to make any <strong>IQueryable&lt;T&gt;</strong> asynchronous, even when underlying query provider doesn't directly support it.</p>
<h2>Sample Implementation</h2>
<p>To illustrate pulling all the pieces together, let's create a repository that is backed by the <a href="http://msdn.microsoft.com/en-us/data/ef.aspx">Entity Framework</a>. Also note that this approach can work for versions earlier than 6.0, but you'll have to execute the query in your own Task.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/0250.031714_2059_Asynchronou2.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/0250.031714_5F00_2059_5F00_Asynchronou2.png" alt="" /></p>
<h1>&nbsp;</h1>
<h1>Extension Methods</h1>
<p>Up to this point, you may be wondering where all the other standard operations for a repository are. Since we now have a way to generically create and execute asynchronous LINQ queries, adding extension methods to fill in the gaps is straightforward. I chose to use extension methods because my objective was to minimize the effort required to implement the interface.</p>
<p>The following outlines the provided extension methods that support the standard repository operations:</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/5226.031714_2059_Asynchronou3.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/5226.031714_5F00_2059_5F00_Asynchronou3.png" alt="" /></p>
<h1>Sample Usage</h1>
<p>By now, the overall picture is solidifying; however, to really drive the point home, let's examine some sample usage scenarios of our implementation. For brevity, all of the examples will use the non-cancellable extension methods.</p>
<h2>Retrieving All Data</h2>
<p>The following example demonstrates how all data from the repository can be retrieved. In almost all scenarios, I'm not sure why anyone would want to allow returning all data without pagination, but since most repositories have this capability, I preserved it for consistency.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/5148.031714_2059_Asynchronou4.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/5148.031714_5F00_2059_5F00_Asynchronou4.png" alt="" /></p>
<h2>Retrieving a Single Entity</h2>
<p>The following example demonstrates retrieving a single entity. Since each entity should be matched by a unique key and it is not an error if the repository does not have a match, the execution behavior is the same as the LINQ extension method <strong>SingleOrDefault</strong>.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/3005.031714_2059_Asynchronou5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/3005.031714_5F00_2059_5F00_Asynchronou5.png" alt="" /></p>
<h2>Searching for Entities</h2>
<p>The following example demonstrates how to search for entities. Unlike <strong>GetSingleAsync</strong>, this method will return a sequence of all matches.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/4666.031714_2059_Asynchronou6.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/4666.031714_5F00_2059_5F00_Asynchronou6.png" alt="" /></p>
<h2>Paging</h2>
<p>The following example demonstrates how to paginate entity queries. The <strong>PagedCollection&lt;T&gt;</strong> isn't anything special; it is simply a <strong>ReadOnlyCollection&lt;T&gt;</strong> that also includes a <strong>TotalCount</strong> property.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/4064.031714_2059_Asynchronou7.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/4064.031714_5F00_2059_5F00_Asynchronou7.png" alt="" /></p>
<h2>Complex Queries</h2>
<p>All of previous examples illustrate a strong affinity to the typical definition and implementation of the <em>Repository</em> pattern. However, what happens when you encounter a query scenario that isn't addressed? Common situations include sorting, composite predicates, and so on. In some cases, this could be internally handled by the repository implementation, but this would be limiting to the implementation and not very clear in usage. Other alternatives are possible, but many of them result in changing the signature of the interface or concrete class that is used. Since this design still incorporates the fundamental query capabilities of LINQ, we can use it to solve these issues.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/0777.031714_2059_Asynchronou8.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/0777.031714_5F00_2059_5F00_Asynchronou8.png" alt="" /></p>
<p>While some of these complex query scenarios are undeniably verbose, you could easily create your own succinct extension methods to suit your needs without changing the core interface.</p>
<h2>Web API and OData</h2>
<p>Another great, <em>real world</em> example is using this style of repository with an OData-based ASP.NET Web API controller. Enabling an asynchronous, queryable action method for the controller is now very simple.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/4571.031714_2059_Asynchronou9.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/4571.031714_5F00_2059_5F00_Asynchronou9.png" alt="" /></p>
<h1>Writable Repositories</h1>
<p>Before wrapping up this article, it's worth discussing a writable repository. According to <a href="http://www.martinfowler.com/eaaCatalog/repository.html">Fowler</a>, "Objects can be added to and removed from the Repository". While Fowler doesn't explicitly discuss updating items stored in a repository, it is almost certainly implied. Furthermore, if you can add, remove, and update items within a repository, then you'll need a way to persist those changes.</p>
<p>There is already a design pattern that is dedicated to managing the changes that must be persisted to a data store - <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">unit of work</a>. I'll cover the unit of work in an upcoming post, but I'll briefly describe its relationship here. A writable repository should have a collaborating unit of work that manages the underlying state changes. I could have had this interface implement the unit of work interface, but a repository <em>is</em> not a unit of work; rather, it <em>uses</em> a unit of work. Furthermore, the vernacular of the two patterns is different. For example, you <em>commit</em> a unit of work, but you don't <em>commit</em> a repository; you save the changes within a repository. For this reason, although the behaviors are similar, the repository interface does not directly implement a unit of work interface.</p>
<p>While <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">Fowler</a> does describe <em>rolling back</em> changes in a unit of work, he doesn't mention exposing whether it contains any changes and you may be wondering why it is here. For mostly stateless applications, such as web applications and services, it is not particularly useful. However, for stateful applications such as Windows Store applications, Windows Phone applications, and so on, this capability is particularly useful. It enables you to detect and expose when there are user changes; for example, to enable or disable a <em>save</em> button. When a user cancels an operation you can discard or roll back the changes.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/2845.031714_2059_Asynchronou10.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/2845.031714_5F00_2059_5F00_Asynchronou10.png" alt="" /></p>
<h1>Conclusion</h1>
<p>In this article we examined a reimaging of the classic <em>Repository</em> pattern with a breath of fresh air to support asynchronous operations and complex query composition. There are many implementations of the <em>Repository</em> pattern and the ideas presented here are in no way anymore <em>correct</em> than any other. My objective was to present new ideas that, hopefully, provide more flexibility in your applications. Feel free to provide questions, comments, or feedback. In two upcoming, related posts, I'll dive into the unit of work pattern and making <strong>IQueryable&lt;T&gt;</strong> asynchronous.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/50/83/03/AsyncRepositories.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-50-83-03/AsyncRepositories.zip">AsyncRepositories.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>OData Web API Batching with Actions</title>
      <link>https://docs.microsoft.com/archive/blogs/mrtechnocal/odata-web-api-batching-with-actions</link>
      <pubDate>Fri, 08 Nov 2013 12:58:00 GMT</pubDate>
      <dc:creator><![CDATA[Chris_Martinez_77]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mrtechnocal/2013/11/08/odata-web-api-batching-with-actions/</guid>
      <description><![CDATA[Batching has been supported in OData for some time. In WCF Data Services, batching was largely a...]]></description>
      <content:encoded><![CDATA[<p>Batching has been supported in OData for some time. In WCF Data Services, batching was largely a black box. The OData support for Web API opens up the batching pipeline, but you are still limited to batched queries and change sets out-of-the-box. What if you wanted to allow batched actions as well?</p>
<p>As it turns out the <strong>DefaultODataBatchHandler</strong> will only accept the POST method when the request is for a change set. Since an OData action could have side effects, they are required to be requested via the POST method. This clearly causes a problem if we want to support batching and actions. What can we do about it?</p>
<h1>Extending the Default OData Batch Handler</h1>
<p>HTTP batching has become an intrinsic capability in ASP.NET Web API and OData. Altering or otherwise extending the default behavior is now very straight forward &ndash; almost.</p>
<p>While it's true that we can easily subclass <strong>DefaultODataBatchHandler</strong> and override its behaviors, we are not able to change how the OData APIs parse the batch request. As a result, we are not able to influence the batch parsing process - or are we?</p>
<p>One solution would be to completely supplant the default OData parsing routines and replace them with our own. This approach is highly undesirable because we don't want to change any of the inherent query or change set behaviors. What other options do we have?</p>
<h1>Applying Pipes and Filters</h1>
<p>A batch request is nothing more than a multipart MIME encoded document that contains nested HTTP requests. All we need to do is evaluate each nested request, determine if it represents an OData action, and filter those requests from the requests that you would normally provide to the OData parsing routines. For each action we identify, we need to create and return an <strong>OperationRequestItem</strong> from our batch handler. For all other requests, we'll just let them flow through to the base implementation and combine the returned items with our action items.</p>
<p>There's just one caveat that we've overlooked. The OData specification has stringent rules about how batch requests are to be processed. Specifically, it states that requests must be processed in the order that they are received. This requirement doesn't derail our solution, but now we need to ensure that the items we create for actions are merged with the normally created items in the same order as they appear in the request.</p>
<p>The following diagram provides a visualization of the process:</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/6266.110813_2134_ODataWebAPI1.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/6266.110813_5F00_2134_5F00_ODataWebAPI1.png" alt="" /><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/2061.110813_2134_ODataWebAPI2.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/2061.110813_5F00_2134_5F00_ODataWebAPI2.png" alt="" /><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/5621.110813_2134_ODataWebAPI3.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/5621.110813_5F00_2134_5F00_ODataWebAPI3.png" alt="" /><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/1732.110813_2134_ODataWebAPI4.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/1732.110813_5F00_2134_5F00_ODataWebAPI4.png" alt="" /><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/0250.110813_2134_ODataWebAPI5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/0250.110813_5F00_2134_5F00_ODataWebAPI5.png" alt="" /><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/3580.110813_2134_ODataWebAPI6.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/3580.110813_5F00_2134_5F00_ODataWebAPI6.png" alt="" /><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/4174.110813_2134_ODataWebAPI7.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/4174.110813_5F00_2134_5F00_ODataWebAPI7.png" alt="" /><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/5076.110813_2134_ODataWebAPI8.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/5076.110813_5F00_2134_5F00_ODataWebAPI8.png" alt="" /><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/5008.110813_2134_ODataWebAPI9.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/5008.110813_5F00_2134_5F00_ODataWebAPI9.png" alt="" /></p>
<h1>Identifying an OData Action Request</h1>
<p>We now have a workable design to support actions in a batch request, but how do we identify that an item in the batch represents an action? The answer is surprisingly easier than we might think. There are three criteria we can use to concretely identify an OData action:</p>
<ol>
<li>The request is a POST&nbsp;&nbsp;&nbsp;&nbsp;</li>
<li>The request is not nested multipart MIME content (e.g. a change set)</li>
<li>The request URL matches an <strong>ActionPathSegment</strong></li>
</ol>
<p>The first two criteria are easy to implement using the <strong>ReadAsHttpRequestMessageAsync</strong> and <strong>IsMimeMultipartContent</strong> extension methods provided by Web API.</p>
<p>We'll satisfy the third criterion by creating our own extension method &ndash; <strong>IsODataAction</strong>. In order to determine whether the nested request is an action, we'll use the path handler associated with batch request to parse the OData path. If the path parses successfully and the last segment is an <strong>ActionPathSegment</strong>, then we know we have a match.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/8228.110813_2134_ODataWebAPI10.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/8228.110813_5F00_2134_5F00_ODataWebAPI10.png" alt="" /></p>
<h1>Custom Batch Handler Landmines</h1>
<p>While poking around in the source code for the <strong>DefaultODataBatchHandler</strong>, I realized that the OData batch processing does not use the Web API libraries to parse the request. This really isn't a big deal and in all likelihood the code is the same as it is in WCF Data Services. The surprise and initial frustration to me was the fickleness of the <strong>HttpRequestMessage</strong> class when you try to read it from <strong>HttpContent</strong> using the <strong>ReadAsHttpRequestMessageAsync</strong>.</p>
<p>First, the <strong>HttpRequestMessage</strong> class enforces the HTTP 1.1 requirement for the <em>Host</em> header. Under most scenarios this would be completely reasonable; however, in a batch request the client must already provide the <em>Host</em> header in the root request, which makes it unlikely or easy to forget to specify in the nested requests. To be tolerant of this potential issue, I had to programmatically inject the <em>Host</em> header from the main batch request to each child request before it is deserialized &ndash; if it's not already present.</p>
<p>The second issue is similar in nature. The URL specified for each of the nested requests in the batch will almost certainly be relative. The examples for batch requests you can find online vary, where some show the relative URL with a leading '/' and others do not. It turns out that the relative URL will fail to build properly using <strong>ReadAsHttpRequestMessageAsync</strong> if it does not have the leading '/'. If you examine the implementation of the private <strong>CreateRequestUri</strong> method within <strong>HttpContentMessageExtensions</strong>, you'll see that it fails because the URL is constructed as an absolute URL using <strong>String.Format</strong>. I'm not quite sure I would qualify this as a bug, but at a minimum the code should be more tolerant of this behavior or use <strong>Uri</strong> to combine the URLs. A comment in the source code does mention why it doesn't use <strong>UriBuilder</strong>, but it doesn't explain why it doesn't use <strong>Uri</strong>.</p>
<p>Ultimately, these were not huge issues to overcome, but they were certainly unexpected. I could have written all my own parsing as needed (and in some cases I still had to), but my objective was to make the Web API libraries do as much as that work for me as possible.</p>
<h1>Putting It All Together</h1>
<p>One of the greatest strengths of how batching is supported in ASP.NET Web API is that it is completely orthogonal to everything else. Why should a controller know it's executing something from a batched request? It is a cross-cutting concern after all. To enable OData batching in your application, you only need to add the following Web API configuration:</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/5826.110813_2134_ODataWebAPI11.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/5826.110813_5F00_2134_5F00_ODataWebAPI11.png" alt="" /></p>
<p>This will light up a new endpoint at <strong>[route prefix]/$batch</strong>, which is the out-of-the-box route mapping for OData. A batch request can be made to any entity controller operation and, now, to any action. Also keep in mind that batch requests do not need to target the same controller. This means a client can issue a query, change set, or execute an action against any combination of services!</p>
<h2>Making a Batch Request with JavaScript</h2>
<p>There are countless ways to make a HTTP batch request to one or more of your services. If you're using .NET, the web client APIs make it really easy to compose a MIME encoded document with nested HTTP requests. However, if you're using some other client &ndash; say JavaScript &ndash; it's not so trivial to build up the request correctly; enter <a href="http://datajs.codeplex.com/">DataJs</a>. DataJs is a JavaScript library (available on NuGet), which has rich support for OData, including batching.</p>
<p>I've excluded much of the HTML page for brevity, but the following demonstrates how to compose an OData action and query in a batch request and then display the results in the page. The complete example is included in the sample code.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/5432.110813_2134_ODataWebAPI12.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/5432.110813_5F00_2134_5F00_ODataWebAPI12.png" alt="" /></p>
<h1>Conclusion</h1>
<p>Although we had to jump through a few hoops, it is possible to support OData batching with actions. Hopefully, you'll find this useful in expanding batching support in your applications. As always, the full source code is provided with all of the relevant unit tests. The solution was built with Visual Studio .NET 2013, .NET 4.5.1, ASP.NET MVC 5.0, and ASP.NET Web API 2.0 for OData.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/46/52/79/ODataBatchingWithActions.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-46-52-79/ODataBatchingWithActions.zip">ODataBatchingWithActions.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Media Resource Support for OData in Web API</title>
      <link>https://docs.microsoft.com/archive/blogs/mrtechnocal/media-resource-support-for-odata-in-web-api</link>
      <pubDate>Thu, 31 Oct 2013 09:16:00 GMT</pubDate>
      <dc:creator><![CDATA[Chris_Martinez_77]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mrtechnocal/2013/10/31/media-resource-support-for-odata-in-web-api/</guid>
      <description><![CDATA[OData has long had solid support for streams via Media Link Entries (MLE) and Media Resources (MR),...]]></description>
      <content:encoded><![CDATA[<p>OData has long had solid support for streams via Media Link Entries (MLE) and Media Resources (MR), but the things you need to do in order to enable them in Microsoft ASP.NET Web API is significantly different from the mechanics used in WCF Data Services. Initially I wasn't even sure whether there was any support for OData streaming support in Web API, but a short discussion with the OData Web API team confirmed that all the plumbing is in place; however, there aren't any controllers or other out-of-the-box base classes that support it - yet.</p>
<p>Fortunately, the team was kind enough to provide an example of the world's simplest implementation of a bare-bones controller with support for Media Resources. With a na&iuml;ve, but functional example in-hand, I've been able to take their example and refactor the bits into something that can be reused by all. In this post, I'll illustrate the pieces that you need to configure in order to enable OData streaming and I'll discuss the MediaResourceController base class that will allow you to quickly enable Media Resources in your application.</p>
<h1>Required Components</h1>
<p>In order to enable streaming in accordance with the OData specification, there's a couple of things we must create:</p>
<ul>
<li>A custom OData routing convention</li>
<li>A custom OData path handler</li>
<li>A custom OData entity type serializer</li>
<li>An OData MediaResourceController</li>
</ul>
<p>That might seem like a lot to create, but most of the work relies on just extending the base classes already available in the OData assembly for Web API. I'll leave a deep analysis of the code to the reader, but I'll highlight the important segments in the sections to follow.</p>
<h1>Media Resource Entry Routing Convention</h1>
<p>The first thing we need is a way to select a controller to dispatch Media Resource related links to. Since the mapping and semantics of OData are more well-defined than a basic Web API controller, we can't simply decorate a method such as <strong>GetMediaResource</strong> with the <strong>HttpGetAttribute</strong> and expect it to light up. However, since the operations for a Media Resource will intrinsically be CRUD operations for the resource and queries would never be supported for a stream, it is relatively straightforward to define a generic routing convention.</p>
<p>We begin by inheriting from the <strong>EntityRoutingConvention</strong>. Our routing convention only needs to override the <strong>SelectAction</strong> method. We'll be looking to see if we get an OData path template that matches <strong>~/entityset/key/$value</strong>. If we get a match, then we'll use the Convention-Over-Configuration semantics commonly used in ASP.NET MVC and Web API to match the HTTP method to one of four expected actions: <strong>GetMediaResource</strong>, <strong>PostMediaResource</strong>, <strong>PutMediaResource</strong>, or <strong>DeleteMediaResource</strong>.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/7080.103113_1731_MediaResour1.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/7080.103113_5F00_1731_5F00_MediaResour1.png" alt="" /></p>
<h1>Media Resource Entry Path Handler</h1>
<p>Creating a custom path handler to process the Media Resource OData segment is one of the easiest tasks. We start by inheriting from the <strong>DefaultODataPathHandler</strong> and override the <strong>ParseAtEntity</strong> method. The only thing we need to do is return the <strong>ValuePathSegment</strong> if the segment equals <strong>$value</strong>; otherwise, we just let the base implementation work its magic.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/0636.103113_1731_MediaResour2.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/0636.103113_5F00_1731_5F00_MediaResour2.png" alt="" /></p>
<h1>Media Link Entry Entity Type Serializer</h1>
<p>The secret to rendering the Media Link Entry in OData responses is to override the <strong>CreateEntry</strong> method in the <strong>ODataEntityTypeSerializer</strong>. In this method, we need to detect whether the entity being serialized has a Media Resource (e.g. stream) associated with its model. If it does, then we need to add a Media Link Entry for the Media Resource. If there is no associated Media Resource defined, then we just let the base implementation run its course.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/1220.103113_1731_MediaResour3.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/1220.103113_5F00_1731_5F00_MediaResour3.png" alt="" /></p>
<p>The one challenge we face with this solution is that the way the Media Link Entry is created can vary by controller and entity. Hard-coding or otherwise having to create a new serializer for each variant simply will not do. To solve this problem, as illustrated in the above example, we'll define an <strong>IMediaLinkEntryProvider</strong> interface and connect it to the current request using the extension methods <strong>GetMediaLinkEntryProvider</strong> and <strong>SetMediaLinkEntryProvider</strong>. The interface itself only contains one method - <strong>GetMediaLinkEntry</strong>, which provides a callback mechanism for a controller to decide how or if a Media Link Entry should be created. A controller might be read-only or the current entity might have a Media Resource, but it is currently unset. There is no clear way for the serializer to be cognizant of this information.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/8176.103113_1731_MediaResour4.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/8176.103113_5F00_1731_5F00_MediaResour4.png" alt="" /></p>
<h1>Media Resource Controller</h1>
<p>We now have all the constituent components required to create a reusable Media Resource controller. We start by extending the <strong>AsyncEntitySetController</strong>. The <strong>MediaResourceController</strong> has the following, basic signature:</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/7180.103113_1731_MediaResour5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/7180.103113_5F00_1731_5F00_MediaResour5.png" alt="" /></p>
<p>There are three things you must do in addition to what is normally required to set up an <strong>AsyncEntityController</strong>.</p>
<ul>
<li>Override the <strong>GetStream</strong> method to retrieve a stream from an entity. The way the stream is retrieved can vary as your entity may have an associated <strong>Stream</strong>, a byte array, or may use some other mechanism to retrieve the stream.</li>
<li>Override the <strong>GetContentTypeForStream</strong> method to retrieve the stream media type. The media type cannot be derived directly from the <strong>Stream</strong>; however, your entity should have an attribute that can provide it.</li>
<li>Override the <strong>GetMediaLinkEntry</strong> method to create a Media Link Entry for an entity. This will provide the implementation for the <strong>IMediaEntryLinkProvider</strong> interface.</li>
</ul>
<p>As is the case with the <strong>AsyncEntityController</strong>, the default implementation of the <strong>PostMediaResource</strong>, <strong>PutMediaResource</strong>, and <strong>DeleteMediaResource</strong> will return HTTP 501 (Not Implemented). By overriding the <strong>Initialize</strong> method, the <strong>MediaResourceController</strong> will assign itself as the <strong>IMediaEntryLinkProvider</strong> associated with the current request; therefore, there is nothing for you to do to set this up in your controllers.</p>
<h2>Batching and Partial Content</h2>
<p>Depending on the size of your Media Resources, it may be desirable to support batching and partial content. Fortunately, this is really easy to support in ASP.NET Web API using the <em>Range</em> HTTP header and the <strong>ByteRangeStreamContent</strong> class. The partial stream behavior is baked into the default implementation of the <strong>GetMediaResource</strong> method, so there is nothing extra for you to do in order to take advantage of this capability.</p>
<h1>Creating Your First Media Resource Controller</h1>
<p>To demonstrate all the pieces coming together, we'll create a simple, read-only Media Resource controller for an entity set of images. The first thing we need is our entity definition for an <strong>Image</strong>.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/6332.103113_1731_MediaResour6.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/6332.103113_5F00_1731_5F00_MediaResour6.png" alt="" /></p>
<p>Creating a controller with our defined entity is now a cinch. In the spirit of keeping the demonstration simple, we'll just enumerate the images in a folder hosted on the website. In this example, we also build up the entity and its corresponding stream in a single pass. To prevent unnecessarily opening a <strong>FileStream</strong>, we'll use the provided <strong>LazyStream</strong>, which enables a lazy-loaded stream. As noted previously, this technique is only one of several possibilities for returning the <strong>Stream</strong> in the <strong>GetStream</strong> method.</p>
<p>The majority of the controller's implementation shouldn't require much explanation. The <strong>GetMediaLinkEntry</strong> is the only part that isn't entirely straightforward. To ensure developers have the maximum fidelity over how the Media Link Entry is created, you are provided the entity and the serializer context being used. Given this information, we are able to create a Media Link Entry with a read link and its media type. We could optionally add an edit link and ETag. The edit link would typically be the same as the read link, but will be routed based on the POST, PUT, or DELETE verb.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/3223.103113_1731_MediaResour7.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/3223.103113_5F00_1731_5F00_MediaResour7.png" alt="" /></p>
<h1>Setting Up the Web API Configuration</h1>
<p>The final step that must be completed before we can reap the rewards of our efforts is to update the Web API configuration. First, we need an EDM model to provide to the OData route.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/7418.103113_1731_MediaResour8.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/7418.103113_5F00_1731_5F00_MediaResour8.png" alt="" /></p>
<p>The last thing we need to do is update the Web API registration with the required OData configuration. We override the default OData routing conventions, path handler, and serializer provider with our extended implementations that support Media Link Entries.</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/6431.103113_1731_MediaResour9.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/6431.103113_5F00_1731_5F00_MediaResour9.png" alt="" /></p>
<h1>Viewing the Results</h1>
<p>At long last we can hit F5 and view the results. A single entity result in JSON now looks like:</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/3730.103113_1731_MediaResour10.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/3730.103113_5F00_1731_5F00_MediaResour10.png" alt="" /></p>
<p>If we following the Media Link Entry, we'll get the associated Media Resource as an image:</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/28/11/metablogapi/2234.103113_1731_MediaResour11.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-28-11-metablogapi/2234.103113_5F00_1731_5F00_MediaResour11.png" alt="" /></p>
<h1>Conclusion</h1>
<p>Ultimately this post ended up being longer than I wanted; however, I felt it was important to outline all of the moving parts required to enable Media Resources and Media Link Entries. I didn't demonstrate a controller that writes Media Resources, but it's not much of a stretch to implement one by overriding the appropriate methods and reading the stream sent in a request. Hopefully you find that using the sample library provided, it is relatively quick and easy to setup any number of Media Resource controllers in your application.</p>
<p>Although omitted from the post for brevity, all of the code provided is well-documented to help guide you through it. Of course, no example would be complete without unit tests, so all of the related unit tests are also included with the source. I'm a big fan of <a href="http://xunit.codeplex.com">XUnit.NET</a>, so if you don't have the test runner installed, you'll need to grab it from the <a href="http://visualstudiogallery.msdn.microsoft.com/463c5987-f82b-46c8-a97e-b1cde42b9099">Visual Studio Extension Gallery</a>. I'm also a fan of Design-By-Contract and <a href="http://research.microsoft.com/en-us/projects/contracts/">Microsoft Code Contracts</a>. The code contracts defined are unobtrusive, require no special tools, and can even be removed if you so desire; however, if you want to leverage the full Code Contracts toolset, you can also get it from the <a href="http://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970?SRC=VSIDE">Visual Studio Extension Gallery</a>. The solution was built with Visual Studio .NET 2013, .NET 4.5.1, ASP.NET MVC 5.0, and ASP.NET Web API 2.0 for OData.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/46/22/58/ODataMediaLinkEntries.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-46-22-58/ODataMediaLinkEntries.zip">ODataMediaLinkEntries.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Hacking Connection String Settings</title>
      <link>https://docs.microsoft.com/archive/blogs/mrtechnocal/hacking-connection-string-settings</link>
      <pubDate>Sun, 08 Nov 2009 20:46:00 GMT</pubDate>
      <dc:creator><![CDATA[Chris.Martinez.77]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mrtechnocal/2009/11/08/hacking-connection-string-settings/</guid>
      <description><![CDATA[The .NET Framework configuration system was welcomed with a number of significant improvements in...]]></description>
      <content:encoded><![CDATA[<P>The .NET Framework configuration system was welcomed with a number of significant improvements in the 2.0 release. Despite the many enhancements to the configuration system, particularly the XML-to-class mapping, there are still a number of failings. A few of the most significant issues in my opinion are: the inability to simply point to any valid *.xml file and load it into a <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">Configuration</SPAN> object, limited or no ability to make configuration changes at run-time, and numerous BCL implementations that only use the configuration system without an alternate means of configuration via code. I'm not going to discuss all of these topics; however, I thought I would share some recent experiences where I was required to effectively <EM>hack</EM> the configuration system in order to get it to do what I wanted. </P>
<P>The story begins when I wanted to create a custom <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">SqlProfileProvider</SPAN> implementation. By default, the <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">SqlProfileProvider</SPAN> does everything I needed except that it only allows for the <SPAN style="FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 10pt">connectionStringName</SPAN> attribute in the application configuration. Following the wisdom of my astute colleague, <A href="http://blogs.msdn.com/schlepticons/default.aspx" mce_href="http://blogs.msdn.com/schlepticons/default.aspx">James Zimmerman</A>, I'm in the habit of entering connection string information in UDDI. This is a cogent assertion as a data source can be thought of a type of service and the connection string is kind of binding for that service. I assumed it would be simple to subclass the <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">SqlProfileProvider</SPAN> class and override the <STRONG>Initialize</STRONG> method to supply required connection string or <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">IDbConnection</SPAN> object dynamically. I was wrong. </P>
<P>Unfortunately, the <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">SqlProfileProvider</SPAN> will only work if the connection string is present in the <SPAN style="COLOR: blue"><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">&lt;<SPAN style="COLOR: #a31515">connectionStrings<SPAN style="COLOR: blue">/&gt;</SPAN></SPAN></SPAN> </SPAN>section in the application configuration. This is obviously a problem since the desired result is to resolve the connection string dynamically. The next idea was to resolve the connection string and add the expected item into the <SPAN style="COLOR: #2b91af"><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">ConfigurationManager<SPAN style="COLOR: black">.ConnectionStrings</SPAN></SPAN> </SPAN>collection. Again, I was stopped in my tracks; the collection is read-only. At this point, I had pretty much given up, but I thought it was also worth adding an empty connection string entry and subsequently updating the value at run-time. Once more, I was quickly met by <EM>epic failure</EM>. </P>
<P>Most people probably would have concluded that dynamically adding the connection string is not possible and moved on. In a last ditch effort, I began to research the feasibility of performing <EM>invasive surgery</EM> on the configuration system - enter <A href="http://www.red-gate.com/products/reflector/" mce_href="http://www.red-gate.com/products/reflector/"><EM>Reflector</EM></A>. Using <EM>Reflector</EM>, I was able to perform a <EM>biopsy</EM> that confirms that the connection strings settings collection is made read-only as soon as it is parsed. Fortunately, the read-only state is governed by the simple toggling of a private Boolean field. One caveat is that the <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">ConfigurationElement</SPAN> and <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">ConfigurationElementCollection</SPAN> have different read-only flags. Since the <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">ConfigurationElementCollection</SPAN> inherits from <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">ConfigurationElement</SPAN>, both values must be set to false in order to make any changes. Armed with this information, I was able to use Reflection to perform a <EM>bypass</EM> and dynamically insert a connection string. </P>
<P>The first step to implement this solution is to resolve the fields via Reflection. </P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">private</SPAN> <SPAN style="COLOR: blue">static</SPAN> <SPAN style="COLOR: #2b91af">FieldInfo</SPAN> elementField; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">private</SPAN> <SPAN style="COLOR: blue">static</SPAN> <SPAN style="COLOR: #2b91af">FieldInfo</SPAN> collectionField; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">private</SPAN> <SPAN style="COLOR: blue">static</SPAN> <SPAN style="COLOR: blue">void</SPAN> EnsureFieldInfo() </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">if</SPAN> ( elementField != <SPAN style="COLOR: blue">null</SPAN> ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">return</SPAN>; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">ReflectionPermission</SPAN>( <SPAN style="COLOR: #2b91af">ReflectionPermissionFlag</SPAN>.MemberAccess | <SPAN style="COLOR: #2b91af">ReflectionPermissionFlag</SPAN>.RestrictedMemberAccess ).Assert(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">var</SPAN> flags = <SPAN style="COLOR: #2b91af">BindingFlags</SPAN>.Instance | <SPAN style="COLOR: #2b91af">BindingFlags</SPAN>.NonPublic; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">try </SPAN></SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">elementField = <SPAN style="COLOR: blue">typeof</SPAN>( ConfigurationElement ).GetField( <SPAN style="COLOR: #a31515">"_bReadOnly"</SPAN>, flags ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">collectionField = <SPAN style="COLOR: blue">typeof</SPAN>( ConfigurationElementCollection ).GetField( <SPAN style="COLOR: #a31515">"bReadOnly"</SPAN>, flags ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">finally </SPAN></SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: #2b91af">CodeAccessPermission</SPAN>.RevertAssert(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">if</SPAN> ( elementField == <SPAN style="COLOR: blue">null</SPAN> ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">throw</SPAN> <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">MemberAccessException</SPAN>( <SPAN style="COLOR: blue">string</SPAN>.Format( <SPAN style="COLOR: blue">null</SPAN>, <SPAN style="COLOR: #a31515">"The operation to access field '{0}' failed."</SPAN>, <SPAN style="COLOR: #a31515">"_bReadOnly"</SPAN> ) ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">if</SPAN> ( collectionField == <SPAN style="COLOR: blue">null</SPAN> ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">throw</SPAN> <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">MemberAccessException</SPAN>( <SPAN style="COLOR: blue">string</SPAN>.Format( <SPAN style="COLOR: blue">null</SPAN>, <SPAN style="COLOR: #a31515">"The operation to access field '{0}' failed."</SPAN>, <SPAN style="COLOR: #a31515">"bReadOnly"</SPAN> ) ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P>Now that we have the fields, we can build a couple of simple methods to do the work. </P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">private</SPAN> <SPAN style="COLOR: blue">static</SPAN> <SPAN style="COLOR: blue">void</SPAN> SetElementIsReadOnly( <SPAN style="COLOR: #2b91af">ConfigurationElement</SPAN> element, <SPAN style="COLOR: blue">bool</SPAN> readOnly ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">elementField.SetValue( element, readOnly ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">private</SPAN> <SPAN style="COLOR: blue">static</SPAN> <SPAN style="COLOR: blue">void</SPAN> SetCollectionIsReadOnly( <SPAN style="COLOR: #2b91af">ConfigurationElementCollection</SPAN> collection, <SPAN style="COLOR: blue">bool</SPAN> readOnly ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">SetElementIsReadOnly( collection, readOnly ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">collectionField.SetValue( collection, readOnly ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P>We now have everything we need to dynamically add a connection string. </P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">protected</SPAN> <SPAN style="COLOR: blue">virtual</SPAN> <SPAN style="COLOR: blue">void</SPAN> AddConnectionString( <SPAN style="COLOR: #2b91af">ConnectionStringSettings</SPAN> settings ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">if</SPAN> ( !<SPAN style="COLOR: #2b91af">ConfigurationManager</SPAN>.ConnectionStrings.IsReadOnly() ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: #2b91af">ConfigurationManager</SPAN>.ConnectionStrings.Add( settings ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">return</SPAN>; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">EnsureFieldInfo(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">ReflectionPermission</SPAN>( <SPAN style="COLOR: #2b91af">ReflectionPermissionFlag</SPAN>.MemberAccess | <SPAN style="COLOR: #2b91af">ReflectionPermissionFlag</SPAN>.RestrictedMemberAccess ).Assert(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">try </SPAN></SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">SetCollectionIsReadOnly( <SPAN style="COLOR: #2b91af">ConfigurationManager</SPAN>.ConnectionStrings, <SPAN style="COLOR: blue">false</SPAN> ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: #2b91af">ConfigurationManager</SPAN>.ConnectionStrings.Add( settings ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">SetCollectionIsReadOnly( <SPAN style="COLOR: #2b91af">ConfigurationManager</SPAN>.ConnectionStrings, <SPAN style="COLOR: blue">true</SPAN> ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">finally </SPAN></SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: #2b91af">CodeAccessPermission</SPAN>.RevertAssert(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P>I'll leave you to your own devices with regard to how you resolve your connection strings. The implementation of <STRONG>Initialize</STRONG> will look something similar to the following: </P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">public</SPAN> <SPAN style="COLOR: blue">override</SPAN> <SPAN style="COLOR: blue">void</SPAN> Initialize( <SPAN style="COLOR: blue">string</SPAN> name, <SPAN style="COLOR: #2b91af">NameValueCollection</SPAN> config ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">var</SPAN> key = config[<SPAN style="COLOR: #a31515">"connectionStringName"</SPAN>]; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: green">// TODO: your method to get a ConnectionStringSettings object </SPAN></SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">var</SPAN> settings = <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">ConnectionStringSettings</SPAN>( key, <SPAN style="COLOR: blue">string</SPAN>.Empty, <SPAN style="COLOR: blue">string</SPAN>.Empty ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">this</SPAN>.SetConnectionString( settings ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">if</SPAN> ( <SPAN style="COLOR: blue">string</SPAN>.IsNullOrEmpty( name ) ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">name = <SPAN style="COLOR: blue">this</SPAN>.GetType().Name; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">base</SPAN>.Initialize( name, config ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P>While this is solution is analogous to lighting a hula-hoop on fire while diving through it, it does demonstrate that if we carefully use a <EM>scalpel</EM>, we can perform <EM>cosmetic surgery</EM> to make the configuration system <EM>look</EM> the way we want. The ultimate goal of this implementation was to resolve the connection string for the profile service dynamically, but it could be used any number of additional ways. I'll let you use your imagination. Enjoy!</P>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/09/91/93/83/CustomSqlProfileProvider.cs" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-91-93-83/CustomSqlProfileProvider.cs">CustomSqlProfileProvider.cs</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Deferred Service Operations</title>
      <link>https://docs.microsoft.com/archive/blogs/mrtechnocal/deferred-service-operations</link>
      <pubDate>Mon, 26 Oct 2009 23:28:00 GMT</pubDate>
      <dc:creator><![CDATA[Chris.Martinez.77]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mrtechnocal/2009/10/26/deferred-service-operations/</guid>
      <description><![CDATA[I've been working a lot with Silverlight over the past few months and changing my approaches to...]]></description>
      <content:encoded><![CDATA[<P>I've been working a lot with Silverlight over the past few months and changing my approaches to solving common programming problems in order to accommodate the Silverlight asynchronous model has had its challenges. I'm no stranger to asynchronous programming, but several aspects of the Silverlight threading model do not quite behave as advertised. For example, wait handles seemingly cannot be used, but are present in the framework. Additionally, EndInvoke always blocks the UI thread even when started on a separate thread. </P>
<P>One of the key challenges I have faced has been coming up with ways to simplify asynchronous code and make it have the appearance of traditional synchronous code. A pivotal piece of the puzzle that helped solve that problem was the <A href="https://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/" mce_href="https://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/">Reactive Framework (Rx)</A>. While Rx doesn't solve everything, it certainly goes a long way in simplifying the problem. Another aspect that significantly simplified the code was to provide a façade over WCF service proxies. I call this type of service a <EM>local service</EM>. </P>
<P>A local service doesn't have to be WCF service proxy. The word <EM>service</EM> is exceptionally overloaded. A local service can be any type of service that is local to a domain such as a spell checker, event broker, WCF service proxy, etc. For those of you who are familiar with <EM>Inversion of Control (IoC) </EM>design patterns, you'll appreciate providing a level of indirection against service proxies. This approach is also easy to test, even if you replace the WCF service proxy or don't have an actual service proxy to work with. After all, a test doesn't care if you have a <EM>real</EM> WCF service to communicate with. </P>
<P>The final challenge in creating a local service that is a façade for a WCF service proxy is retrieving and setting the endpoint address. Service endpoints will change; it's an absolute certainty. The <EM>ServiceReferences.clientConfig</EM> is exceptionally limited and can't be easily changed once you've deployed an application. There are a number of ways to overcome this problem, but my team has chosen to use UDDI to have the Silverlight client resolve the endpoint address. </P>
<P>In an asynchronous programming model, here's where we get into trouble. If my local service needs to locate a URL dynamically from UDDI, but some other code calls it before that endpoint address is returned, what do I do? Blocking the thread is not an option as that will just hang the entire application. Enter the deferred action queue. </P>
<P>The deferred action queue is exactly what it sounds like; a <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">Queue</SPAN>&lt;<SPAN style="COLOR: #2b91af"><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">Action<SPAN style="COLOR: black">&gt;</SPAN></SPAN> </SPAN>deferred for execution. If the service isn't ready, it can use the <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">DeferredActionQueue</SPAN> to enqueue a callback to itself. This seems odd at first, but when we combine it with an <SPAN style="COLOR: #2b91af"><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">IObserver<SPAN style="COLOR: black">&lt;T&gt;</SPAN></SPAN> from </SPAN>Rx, the caller never knows the difference. </P>
<P>Let's assume we have an interface <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">IMyService</SPAN> that has just a single method <SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">void</SPAN> DoWork( <SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: blue">string</SPAN>&gt; observer )</SPAN>. Let's also assume that the concrete implementation <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">MyService</SPAN> will create a WCF proxy as needed and have a dependency on an <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">IUrlLocator</SPAN> object whose only method is <SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">void</SPAN> Locate( <SPAN style="COLOR: blue">string <SPAN style="COLOR: black">key,<SPAN style="COLOR: blue"> <SPAN style="COLOR: #2b91af">Action</SPAN>&lt;<SPAN style="COLOR: #2b91af">Uri&gt;</SPAN> </SPAN>located</SPAN> )</SPAN></SPAN>. In order to not block the current thread and still allow callers to invoke the service, we'll use the <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">DeferredActionQueue</SPAN>. The complete implementation would look something like this: </P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">public</SPAN> <SPAN style="COLOR: blue">class</SPAN> <SPAN style="COLOR: #2b91af">MyService</SPAN> : <SPAN style="COLOR: #2b91af">IMyService</SPAN> </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">private</SPAN> <SPAN style="COLOR: blue">readonly</SPAN> <SPAN style="COLOR: #2b91af">MyWcfProxy</SPAN> proxy; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">private</SPAN> <SPAN style="COLOR: blue">readonly</SPAN> <SPAN style="COLOR: #2b91af">DeferredActionQueue</SPAN> callbacks; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">public</SPAN> MyService( <SPAN style="COLOR: #2b91af">IUrlLocator</SPAN> locator ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">this</SPAN>.callbacks = <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">DeferredActionQueue</SPAN>( () =&gt; <SPAN style="COLOR: blue">this</SPAN>.proxy == <SPAN style="COLOR: blue">null</SPAN> ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">locator.Locate( </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: #a31515">"MyWcfServiceKey"</SPAN>, </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">url =&gt; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">lock</SPAN> ( <SPAN style="COLOR: blue">this</SPAN>.callbacks.SyncLock ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">this</SPAN>.proxy = <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">MyWcfProxy</SPAN>(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">this</SPAN>.proxy.Endpoint = <SPAN style="COLOR: blue">new</SPAN> EndpointAddress( url ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">this</SPAN>.callbacks.DequeueAll(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">public</SPAN> <SPAN style="COLOR: blue">void</SPAN> DoWork( <SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: blue">string</SPAN>&gt; observer ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">if</SPAN> ( <SPAN style="COLOR: blue">this</SPAN>.callbacks.Enqueue( () =&gt; <SPAN style="COLOR: blue">this</SPAN>.DoWork( observer ) ) ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">return</SPAN>; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">this</SPAN>.proxy.BeginDoWork( </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">ar =&gt; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">string</SPAN> result; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">var</SPAN> dispatcher = System.Windows.<SPAN style="COLOR: #2b91af">Deployment</SPAN>.Current.Dispatcher; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">try </SPAN></SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">result = <SPAN style="COLOR: blue">this</SPAN>.proxy.EndDoWork( ar ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">catch</SPAN> ( System.ServiceModel.<SPAN style="COLOR: #2b91af">CommunicationException</SPAN> ex ) </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">dispatcher.BeginInvoke( () =&gt; observer.OnError( ex ) ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">return</SPAN>; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">dispatcher.BeginInvoke( </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">() =&gt; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">observer.OnNext( result ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">observer.OnCompleted(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">}, <SPAN style="COLOR: blue">null</SPAN> ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">}</SPAN> </P>
<P>The <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">DeferredActionQueue</SPAN> does the work of managing all, if any, deferred actions. The constructor accepts <SPAN style="COLOR: #2b91af"><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt">Func<SPAN style="COLOR: black">&lt;<SPAN style="COLOR: blue">bool<SPAN style="COLOR: black">&gt;</SPAN></SPAN></SPAN></SPAN> </SPAN>which is used to determine whether an action should be deferred. The <EM>Enqueue</EM> method accepts any <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">Action</SPAN> and enqueues it into an internal queue as necessary. The method returns <SPAN style="FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 10pt">false</SPAN> if the operation does not need to be queued (and ultimately results in no operation). In this example, the <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">DeferredActionQueue</SPAN> is used to coordinate requests while the underlying WCF service proxy endpoint address is being resolved. Once the endpoint has been resolved, all enqueued actions are dequeued. The <SPAN style="FONT-FAMILY: Courier New; COLOR: #2b91af; FONT-SIZE: 10pt">DeferredActionQueue</SPAN> exposes a <EM>SyncLock</EM> property that can be used for synchronization to avoid race conditions. Another thing to note is that the callback automatically calls the supplied observer via the dispatcher. This absolves the caller from the responsibility of having to marshal callbacks to the correct thread. </P>
<P>Let's quickly take a look at how this might be used. </P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">var</SPAN> locator = <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">UddiUrlLocator</SPAN>();<SPAN style="COLOR: blue"><BR>var</SPAN> service = <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">MyService</SPAN>( locator ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Courier New; FONT-SIZE: 10pt"><SPAN style="COLOR: blue">var</SPAN> observer = <SPAN style="COLOR: #2b91af">Observer</SPAN>&lt;<SPAN style="COLOR: blue">string</SPAN>&gt;.Create( m =&gt; <SPAN style="COLOR: blue">this</SPAN>.MyTextBox.Text = m, ex =&gt; <SPAN style="COLOR: #2b91af">MessageBox</SPAN>.Show( ex.Message ), <SPAN style="COLOR: blue">null</SPAN> );<BR>service.DoWork( observer ); </SPAN></P>
<P>Although the code is asynchronous, it now has a more synchronous feel to it. If the service is still initializing when <EM>DoWork</EM> gets called, the observer has no idea. The observer intrinsically expects the operation to be asynchronous and still functions as advertised, even if it gets privately deferred for later processing. This is particularly important and useful when a complex hierarchy of objects is being constructed from Unity or any other IoC container. </P>
<P>These examples are obviously simple and naïve; however, in practice this approach has worked very well in programming against a purely asynchronous model. Hopefully, I've demonstrated how this concept could be extended into your own work. </P>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/09/91/33/56/DeferredActionQueue.cs" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-91-33-56/DeferredActionQueue.cs">DeferredActionQueue.cs</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Why Not ICloneable&lt;T&gt;?</title>
      <link>https://docs.microsoft.com/archive/blogs/mrtechnocal/why-not-icloneablet</link>
      <pubDate>Sun, 18 Oct 2009 22:55:00 GMT</pubDate>
      <dc:creator><![CDATA[Chris.Martinez.77]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mrtechnocal/2009/10/18/why-not-icloneablet/</guid>
      <description><![CDATA[The ICloneable interface has been around since the .NET 1.0 days. A number of people have criticized...]]></description>
      <content:encoded><![CDATA[<P>The <SPAN style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9pt">ICloneable</SPAN> interface has been around since the .NET 1.0 days. A number of people have criticized this interface because there is no intrinsic ability to indicate whether the clone is a shallow or deep copy. While that debate is an entirely different discussion in and of itself, I tend to believe that it's the implementer's responsibility to decide the depth of the cloning process. A simple XML comment on the method implementation can indicate whether the cloning process is deep or shallow. </P>
<P>Once generics where introduced in .NET 2.0, I often wondered why there was never a generic implementation for <SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: #2b91af">ICloneable</SPAN>&lt;T&gt;</SPAN>. At first glance, it seems impossible because methods cannot vary by return type alone. However, if we use a constrained type argument on the <EM>Clone</EM> method that restriction can be overcome. </P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">public</SPAN> <SPAN style="COLOR: blue">interface</SPAN> <SPAN style="COLOR: #2b91af">ICloneable</SPAN>&lt;T&gt; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">TClone Clone&lt;TClone&gt;() <SPAN style="COLOR: blue">where</SPAN> TClone : T; </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">}</SPAN><BR></P>
<P>This contract allows a generic <EM>Clone</EM> implementation where the cloned return type is compatible with the original type. This provides the benefit of a strongly-typed return type. We can also now create a generic, cloneable base class. </P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">public</SPAN> <SPAN style="COLOR: blue">class</SPAN> <SPAN style="COLOR: #2b91af">Cloneable</SPAN>&lt;T&gt; : <SPAN style="COLOR: #2b91af">ICloneable</SPAN>&lt;T&gt;, <SPAN style="COLOR: #2b91af">ICloneable</SPAN> </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">public</SPAN> <SPAN style="COLOR: blue">virtual</SPAN> TClone Clone&lt;TClone&gt;() <SPAN style="COLOR: blue">where</SPAN> TClone : T </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">return</SPAN> (TClone) <SPAN style="COLOR: blue">this</SPAN>.MemberwiseClone(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">object</SPAN> <SPAN style="COLOR: #2b91af">ICloneable</SPAN>.Clone() </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">{ </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">var</SPAN> type = <SPAN style="COLOR: blue">this</SPAN>.GetType(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">var</SPAN> method = type.GetMethod( <SPAN style="COLOR: #a31515">"Clone"</SPAN> ).MakeGenericMethod( type ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">return</SPAN> method.Invoke( <SPAN style="COLOR: blue">this</SPAN>, <SPAN style="COLOR: blue">null</SPAN> ); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">} </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">}</SPAN> </P>
<P>This class provides a simple (and naïve) cloning strategy, but can be overridden and still retain the strongly-typed benefits. In addition, we can write a single implementation of <SPAN style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9pt">ICloneable</SPAN> that uses Reflection to always invoke the current generic implementation. When we put it all together, we get the following: </P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">public</SPAN> <SPAN style="COLOR: blue">class</SPAN> <SPAN style="COLOR: #2b91af">Person</SPAN> : <SPAN style="COLOR: #2b91af">Cloneable</SPAN>&lt;<SPAN style="COLOR: #2b91af">Person</SPAN>&gt; {}<BR><SPAN style="COLOR: blue">public</SPAN> <SPAN style="COLOR: blue">class</SPAN> <SPAN style="COLOR: #2b91af">User</SPAN> : <SPAN style="COLOR: #2b91af">Person</SPAN> {}<BR><BR><SPAN style="COLOR: blue">var</SPAN> user = <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">User</SPAN>();<BR><SPAN style="COLOR: blue">var</SPAN> clonedUser = user.Clone&lt;<SPAN style="COLOR: #2b91af">User</SPAN>&gt;();<BR><SPAN style="COLOR: blue">var</SPAN> clonedPerson = user.Clone&lt;<SPAN style="COLOR: #2b91af">Person</SPAN>&gt;();</SPAN> </P>
<P>Unfortunately, there is one scenario where this strategy fails; a clone of a super type cannot be created for a subtype. This limitation is probably why such an interface was never added to the BCL. For example, the following will compile, but fails at runtime: </P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">var</SPAN> person = <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">Person</SPAN>();<BR><SPAN style="COLOR: blue">var</SPAN> clone = person.Clone&lt;<SPAN style="COLOR: #2b91af">User</SPAN>&gt;(); <SPAN style="COLOR: green">// fails because Person cannot cast down to User</SPAN></SPAN> </P>
<P>In my opinion, this limitation is acceptable for two reasons. Although not guaranteed, it's unlikely that developers would write code in this manner. If you've written object-oriented code for any length of time, common sense tells you that a super type cannot be cast down to a subtype. Second, the runtime failure has same effect as writing code with an invalid cast. Consider the following: </P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">var</SPAN> person = <SPAN style="COLOR: blue">new</SPAN> <SPAN style="COLOR: #2b91af">Person</SPAN>(); </SPAN></P>
<P><SPAN style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><SPAN style="COLOR: blue">var</SPAN> user = (<SPAN style="COLOR: #2b91af">User</SPAN>) person;</SPAN> </P>
<P>This code also compiles, but will fail at runtime. Both of these scenarios have logic defects that cannot be guarded against by the compiler. The benefits of a strongly-typed <EM>Clone</EM> implementation outweigh this single shortcoming in my opinion. </P>
<P>While this implementation certainly doesn't address the need for every cloning scenario, it does provide a single non-generic implementation, virtualized generic implementation, and the benefits of strong-typing.</P>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/09/90/89/18/GenericCloneable.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-90-89-18/GenericCloneable.zip">GenericCloneable.zip</a></p>]]></content:encoded>
    </item>
  </channel>
</rss>