<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Kyle McClellan</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/kylemc/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/kylemc/feed.xml</link>
    <description>Making Software Easier</description>
    <lastBuildDate>Tue, 16 Apr 2019 05:17:17 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Unit Testing a WCF RIA DomainService: Part 3, The DomainServiceTestHost</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost</link>
      <pubDate>Thu, 18 Aug 2011 08:10:30 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost/</guid>
      <description><![CDATA[In this thrilling conclusion to my series on unit testing, I’ll show you how to use the...]]></description>
      <content:encoded><![CDATA[<p>In this thrilling conclusion to my series on unit testing, I’ll show you how to use the <strong>DomainServiceTestHost </strong>to test your DomainServices. In parts one and two I showed you how to extract external dependencies using the IDomainServiceFactory and how to use the Repository Pattern. Now that all the groundwork is out of the way, I’ll show you how to test your business logic.</p>  <h1>The DomainService</h1>  <p>The DomainService we’re testing looks like this.</p>  <pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">BookClubDomainService </span>: <span style="color: #2b91af">RepositoryDomainService
</span>  {
    <span style="color: blue">public </span>BookClubDomainService(
      <span style="color: #2b91af">IUnitOfWork </span>unitOfWork,
      <span style="color: #2b91af">IBookRepository </span>bookRepository,
      <span style="color: #2b91af">ILibraryService </span>libraryService,
      <span style="color: #2b91af">IApprovalSystem </span>approvalSystem) { ... }

    <span style="color: green">// Test 1: Operation should return all books
    // Test 2: Operation should return books with categories
    // Test 3: Operation should return books ordered by BookID
    </span><span style="color: blue">public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooks() { ... }

    <span style="color: green">// Test 1: Operation should return all books for category
    // Test 2: Operation should return books ordered by BookID
    </span><span style="color: blue">public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooksForCategory(<span style="color: blue">int </span>categoryId) { ... }

    <span style="color: green">// Test 1: Operation should insert book
    // Test 2: Operation should set the added date
    // Test 3: Operation should request approval for book with invalid ASINs
    // Test 4: Operation should request approval for book not yet published
    </span><span style="color: blue">public void </span>InsertBook(<span style="color: #2b91af">Book </span>book) { ... }

    <span style="color: green">// Test 1: Operation should update book
    // Test 2: Operation should return validation errors
    </span><span style="color: blue">public void </span>UpdateBook(<span style="color: #2b91af">Book </span>book) { ... }

    <span style="color: green">// Test 1: Operation should update book
    // Test 2: Operation should update the added date
    </span>[<span style="color: #2b91af">Update</span>(UsingCustomMethod = <span style="color: blue">true</span>)]
    <span style="color: blue">public void </span>AddNewEdition(<span style="color: #2b91af">Book </span>book) { ... }

    <span style="color: green">// Test 1: Operation should delete book
    // Test 2: Operation should require authentication
    </span>[<span style="color: #2b91af">RequiresAuthentication</span>]
    <span style="color: blue">public void </span>DeleteBook(<span style="color: #2b91af">Book </span>book) { ... }

    <span style="color: green">// Test 1: Operation should return the most recent added date
    </span><span style="color: blue">public </span><span style="color: #2b91af">DateTime </span>GetLatestActivity() { ... }
  }</pre>

<p>It has the standard Query, Insert, Update, and Delete operations in addition to custom Query, Update, and Invoke(/Service) operations. The constructor accepts a number of parameters; each representing an external dependency in the code. I’ve labeled each method with the tests that we’ll write against it so we don’t have to know the details of the implementation (they’re in the sample, I’m just skipping them in the post).</p>

<h1>The DomainServiceTestHost</h1>

<p>The <strong>DomainServiceTestHost </strong>is a new class in the <strong>Microsoft.ServiceModel.DomainServices.Server.UnitTesting </strong>assembly (now on <a href="https://nuget.org/List/Packages/RIAServices.UnitTesting">NuGet</a> and soon to be shipping with the Toolkit). It’s designed to help you test individual DomainService operations. The API falls closely in-line with DomainService conventions (and may help clarify them if you’re still a little hazy). For instance, the test host has a <strong>Query </strong>method for retrieving data, and <strong>Insert</strong>, <strong>Update</strong>, and <strong>Delete </strong>methods for modifying it.</p>

<p>In addition to standard operation support, the test host makes it simple to test validation and authorization. For each standard signature in the <strong>DomainServiceTestHost</strong>, there is a <strong>TryXx </strong>variant that makes it easy to capture validation errors. For instance, <strong>Query </strong>is paired with <strong>TryQuery </strong>and <strong>Insert </strong>with <strong>TryInsert</strong>. Also, each time you create a test host, you can pass an&#160; <strong>IPrincipal </strong>into the constructor that the operations should be run with. This makes it easy to cycle through a number of test users as you validate your authorization metadata. Finally, the test host can be created with a factory method that it uses to instantiate a DomainService. This allows you to initialize a DomainService with test-specific dependencies.</p>

<h1>Testing a DomainService</h1>

<p>Finally we’re getting to the good part. In this section, I’ll walk you through the steps necessary to unit test your business logic. First, we’ll initialize the local variables we’ll use with each test.</p>

<pre class="code">  [<span style="color: #2b91af">TestInitialize</span>]
<span style="color: blue">  public void </span>TestInitialize()
  {
    <span style="color: blue">this</span>._libraryService = <span style="color: blue">new </span><span style="color: #2b91af">MockLibraryService</span>();
    <span style="color: blue">this</span>._approvalSystem = <span style="color: blue">new </span><span style="color: #2b91af">FakeApprovalSystem</span>();
    <span style="color: blue">this</span>._unitOfWork = <span style="color: blue">new </span><span style="color: #2b91af">FakeUnitOfWork</span>();
    <span style="color: blue">this</span>._bookRepository = <span style="color: blue">new </span><span style="color: #2b91af">MockBookRepository</span>();

    <span style="color: blue">this</span>._domainServiceTestHost =<br />      <span style="color: blue">new </span><span style="color: #2b91af">DomainServiceTestHost</span>&lt;<span style="color: #2b91af">BookClubDomainService</span>&gt;(<br />        <span style="color: blue">this</span>.CreateDomainService);
  }

<span style="color: blue">  private </span><span style="color: #2b91af">BookClubDomainService </span>CreateDomainService()
  {
    <span style="color: blue">return new </span><span style="color: #2b91af">BookClubDomainService</span>(
             <span style="color: blue">this</span>._unitOfWork,
             <span style="color: blue">this</span>._bookRepository,
             <span style="color: blue">this</span>._libraryService,
             <span style="color: blue">this</span>._approvalSystem);
  }</pre>

<p>As you can see, I’ve written simple mock/fake/stub types for each dependency. I discussed the <strong>MockBookRepository </strong>a little in my previous post. For the context of the following tests, it’s important to point out that I’ve initialized the repository with an initial set of data. The other three are just simple test implementations. Also, I’ve provided a <strong>CreateDomainService</strong> method that I can pass to the test host that initializes my <strong>BookClubDomainService </strong>with the test dependencies. If you’re not familiar with the Visual Studio testing, the <strong>[TestInitialize]</strong> method will get called before the start of each test.</p>

<p>Starting with something simple, we’ll take a look at the test for the default query.</p>

<pre class="code">  [<span style="color: #2b91af">TestMethod</span>]
  [<span style="color: #2b91af">Description</span>(<span style="color: #a31515">&quot;Tests that the GetBooks query returns all the books&quot;</span>)]
<span style="color: blue">  public void </span>GetBooks_ReturnsAllBooks()
  {
    <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Book</span>&gt; books = <span style="color: blue">this</span>._domainServiceTestHost.<br />                                Query(ds =&gt; ds.GetBooks());

    <span style="color: #2b91af">Assert</span>.AreEqual(<br />      <span style="color: blue">this</span>._bookRepository.GetBooksWithCategories().Count(), books.Count(),
      <span style="color: #a31515">&quot;Operation should return all books&quot;</span>);
  }</pre>

<p>In this method, we’re asking the test host to return the results of the query. The ‘ds’ parameter in the lambda is the instance of the DomainService we’re testing. Since the IntelliSense for the query operation is a little verbose (as is anything where the Expression type shows up), I’ll give you another sample so you get the hang of it. This time we’re testing the custom query.</p>

<pre class="code">  [<span style="color: #2b91af">TestMethod</span>]
  [<span style="color: #2b91af">Description</span>(<br />     <span style="color: #a31515">&quot;Tests that the GetBooksForCategory query orders books by BookID&quot;</span>)]
<span style="color: blue">  public void </span>GetBooksForCategory_OrderedByBookID()
  {
    <span style="color: blue">int </span>categoryId = <span style="color: blue">this</span>._bookRepository.GetTable&lt;<span style="color: #2b91af">Category</span>&gt;().<br />                       First().CategoryID;

    <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Book</span>&gt; books = <span style="color: blue">this</span>._domainServiceTestHost.Query(<br />                                ds =&gt; ds.GetBooksForCategory(categoryId));

    <span style="color: #2b91af">Assert</span>.IsTrue(books.OrderBy(b =&gt; b.BookID).SequenceEqual(books),
      <span style="color: #a31515">&quot;Operation should return books ordered by BookID&quot;</span>);
  }</pre>

<p>In this snippet we’re passing a local variable to the query operation, but everything else is pretty much the same. We’ve gotten the returned collection and now we’re verifying that it is in sorted order.</p>

<p>Tests for Insert, Update, and Delete operations are just as easy to write. Just calling the method on the host will redirect to the corresponding operation in your DomainService.</p>

<pre class="code">  [<span style="color: #2b91af">TestMethod</span>]
  [<span style="color: #2b91af">Description</span>(<span style="color: #a31515">&quot;Tests that the InsertBook operation inserts a new book&quot;</span>)]
<span style="color: blue">  public void </span>InsertBook_InsertsNewBook()
  {
    <span style="color: blue">int </span>categoryId = <span style="color: blue">this</span>._bookRepository.GetTable&lt;<span style="color: #2b91af">Category</span>&gt;().<br />                       First().CategoryID;

    <span style="color: #2b91af">Book </span>book = <span style="color: blue">new </span><span style="color: #2b91af">Book
    </span>{
      ASIN = <span style="color: #a31515">&quot;1234567890&quot;</span>,
      Author = <span style="color: #a31515">&quot;Author&quot;</span>,
      CategoryID = categoryId,
      Description = <span style="color: #a31515">&quot;Description&quot;</span>,
      PublishDate = <span style="color: #2b91af">DateTime</span>.UtcNow.Subtract(<span style="color: #2b91af">TimeSpan</span>.FromDays(1)),
      Title = <span style="color: #a31515">&quot;Title&quot;</span>,
    };

    <span style="color: blue">this</span>._domainServiceTestHost.Insert(book);

    <span style="color: #2b91af">Assert</span>.IsTrue(book.BookID &gt; 0,
      <span style="color: #a31515">&quot;New book should have a valid BookID&quot;</span>);

    <span style="color: #2b91af">Book </span>addedBook = <span style="color: blue">this</span>._bookRepository.GetEntities().<br />                       Single(b =&gt; b.BookID == book.BookID);

    <span style="color: #2b91af">Assert</span>.IsNotNull(addedBook,
      <span style="color: #a31515">&quot;Operation should insert book&quot;</span>);
  }</pre>

<p>To rephrase what I said above, calling <strong>Insert </strong>on the test host with a <strong>Book </strong>calls into our DomainService operation, <strong>InsertBook</strong>. As you can see, at the end of this test our new book has been added to the repository.</p>

<p>In addition to Query, Insert, Update, and Delete methods, Named Updates and Invoke operations are also supported. In both cases, the syntax is very similar to testing a Query.</p>

<pre class="code"><span style="color: blue">  this</span>._domainServiceTestHost.Update(<br />    ds =&gt; ds.AddNewEdition(book), original);</pre>

<pre class="code"><span style="color: #2b91af">  DateTime </span>result = <span style="color: blue">this</span>._domainServiceTestHost.Invoke(<br />    ds =&gt; ds.GetLatestActivity());</pre>

<p><strong>AddNewEdition</strong> updates the book and runs custom business logic and <strong>GetLatestActivity </strong>returns a <strong>DateTime </strong>related to the newest book. Again, the ‘ds’ parameter in the lambda expression refers to the DomainService being tested.</p>

<h1>Testing Validation and Authorization</h1>

<p>Testing validation and authorization metadata for a DomainService operation can be just as important as testing the business logic. A unit test suite verifying authorization and validation would be a great tool to prevent service security regressions.</p>

<p>Validation is fairly straightforward to test. Instead of using the test host methods I’ve already described, you should use their <strong>TryXx </strong>variants.</p>

<pre class="code">  [<span style="color: #2b91af">TestMethod</span>]
  [<span style="color: #2b91af">Description</span>(<span style="color: #a31515">&quot;Tests that the UpdateBook operation returns <br />     validation errors when passed an invalid book&quot;</span>)]
<span style="color: blue">  public void </span>UpdateBook_SetsValidationErrors()
  {
    <span style="color: #2b91af">Book </span>original = <span style="color: blue">this</span>._bookRepository.GetEntities().First();
    <span style="color: #2b91af">Book </span>book = <span style="color: blue">new </span><span style="color: #2b91af">Book
    </span>{
      AddedDate = original.AddedDate,
      ASIN = <span style="color: #a31515">&quot;Invalid!&quot;</span>,
      Author = original.Author,
      BookID = original.BookID,
      Category = original.Category,
      CategoryID = original.CategoryID,
      Description = original.Description,
      PublishDate = original.PublishDate,
      Title = original.Title,
    };

    <span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">ValidationResult</span>&gt; validationErrors;
    <span style="color: blue">bool </span>success = <span style="color: blue">this</span>._domainServiceTestHost.TryUpdate(<br />                     book, original, <span style="color: blue">out </span>validationErrors);

    <span style="color: #2b91af">Assert</span>.IsFalse(success,
      <span style="color: #a31515">&quot;Operation should have validation errors&quot;</span>);
    <span style="color: #2b91af">Assert</span>.AreEqual(1, validationErrors.Count,
      <span style="color: #a31515">&quot;Operation should return validation errors&quot;</span>);
    <span style="color: #2b91af">Assert</span>.IsTrue(validationErrors[0].MemberNames.Single() == <span style="color: #a31515">&quot;ASIN&quot;</span>,
      <span style="color: #a31515">&quot;Operation should return a validation error for 'ASIN'&quot;</span>);
  }</pre>

<p>This test calls into <strong>UpdateBook </strong>with invalid data and then verifies the resulting validation errors are ones we expect.</p>

<p>Authorization tests follow a different approach. Instead of using a different test host method, they set a custom principal that will be used when calling the DomainService operation. While the test host defaults to an anonymous user, an alternate constructor allows you to specify the user that is interesting for your test case.</p>

<pre class="code"><span style="color: blue">  this</span>._domainServiceTestHost = <br />    <span style="color: blue">new </span><span style="color: #2b91af">DomainServiceTestHost</span>&lt;<span style="color: #2b91af">BookClubDomainService</span>&gt;(<br />      <span style="color: blue">this</span>.CreateDomainService,<br />      <span style="color: #2b91af">BookClubDomainServiceTest</span>.authenticatedUser);</pre>

<h1>Conclusion</h1>

<p>To sum it all up, the <strong>DomainServiceTestHost</strong> in combination with an <strong>IDomainServiceFactory</strong> and the Repository pattern makes it simple to unit test your DomainServices in an isolated and reliable fashion. Also, since the test host is just a .NET type, it should be compatible with any and all test tools and frameworks you feel like using it with. Hopefully this series gave you a good overview of DomainService unit testing. If you have any questions or feature requests, please send them my way. Thanks.</p>

<h4>[A Note on the DomainServiceTestHost]</h4>

<p>As of the initial release of this test host, there may still be a few edge cases for association and composition change sets that are not supported. If you find any, please let me know so I can put together a scenario for a subsequent release.</p>

<h3><a href="https://blogs.msdn.com/b/kylemc/archive/tags/testing/">Unit Testing Series</a></h3>

<ul>
  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory.aspx">Part 1: The IDomainServiceFactory</a></li>

  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern.aspx">Part 2: The Repository Pattern</a></li>

  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost.aspx">Part 3: The DomainServiceTestHost</a></li>

  <li><a href="https://code.msdn.microsoft.com/Unit-Testing-a-WCF-RIA-a39a700e">Unit Testing Sample Source</a></li>

  <li><a href="https://nuget.org/List/Packages/RIAServices.UnitTesting">NuGet: RIAServices.UnitTesting</a></li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Unit Testing a WCF RIA DomainService: Part 2, The Repository Pattern</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern</link>
      <pubDate>Thu, 18 Aug 2011 08:10:17 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern/</guid>
      <description><![CDATA[This is part two in a series I’m writing about how to unit test your DomainServices. In part one, I...]]></description>
      <content:encoded><![CDATA[<p>This is part two in a series I’m writing about how to unit test your DomainServices. In part one, I discuss how you could use an <strong>IDomainServiceFactory</strong> to factor external dependencies out of your code.&#160; Continuing along the same lines of thinking, I will use this post to discuss factoring out the database dependency as well. In general, factoring out external dependencies will increase both the isolation and consistency of your tests.</p>  <p>The pattern I’m using to factor out external dependencies is called the Repository Pattern. It’s well-known and comes in many variations. The variation I’ve chosen here is one that fits quite well with the way RIA consumes and Entity Framework <strong>ObjectContext</strong>. If you’re using a different data-access technology, feel free to modify this pattern until you get something that works for your scenario.</p>  <h1>A Repository Sample</h1>  <p>Before I jump into the Repository API or the DomainService setup, I’d like to show what introducing a repository might do to standard DomainService operations. Here are a few operations written directly against an <strong>ObjectContext</strong>.</p>  <pre class="code"><span style="color: green">  // Test 1: Operation should return all books
  // Test 2: Operation should return books with categories
  // Test 3: Operation should return books ordered by BookID
</span><span style="color: blue">  public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooks()
  {
    <span style="color: blue">return this</span>.ObjectContext.Books.Include(<span style="color: #a31515">&quot;Category&quot;</span>).<br />             OrderBy(b =&gt; b.BookID);
  }

<span style="color: green">  // Test 1: Operation should return all books for category
  // Test 2: Operation should return books ordered by BookID
</span><span style="color: blue">  public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooksForCategory(<span style="color: blue">int </span>categoryId)
  {
    <span style="color: blue">return this</span>.ObjectContext.Books.<br />             Where(b =&gt; b.CategoryID == categoryId).OrderBy(b =&gt; b.BookID);
  }

<span style="color: green">  // Test 1: Operation should update book
  // Test 2: Operation should return validation errors
</span><span style="color: blue">  public void </span>UpdateBook(<span style="color: #2b91af">Book </span>book)
  {
    <span style="color: blue">this</span>.ObjectContext.Books.AttachAsModified(<br />      book, <span style="color: blue">this</span>.ChangeSet.GetOriginal(book));
  }</pre>

<p>Upon introducing a repository into this code, the operations will be slightly different.</p>

<pre class="code"><span style="color: green">  // Test 1: Operation should return all books
  // Test 2: Operation should return books with categories
  // Test 3: Operation should return books ordered by BookID
</span><span style="color: blue">  public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooks()
  {
    <span style="color: blue">return this</span>._bookRepository.GetBooksWithCategories().<br />             OrderBy(b =&gt; b.BookID);
  }

<span style="color: green">  // Test 1: Operation should return all books for category
  // Test 2: Operation should return books ordered by BookID
</span><span style="color: blue">  public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooksForCategory(<span style="color: blue">int </span>categoryId)
  {
    <span style="color: blue">return this</span>._bookRepository.GetEntities().<br />             Where(b =&gt; b.CategoryID == categoryId).OrderBy(b =&gt; b.BookID);
  }

<span style="color: green">  // Test 1: Operation should update book
  // Test 2: Operation should return validation errors
</span><span style="color: blue">  public void </span>UpdateBook(<span style="color: #2b91af">Book </span>book)
  {
    <span style="color: blue">this</span>._bookRepository.Update(<br />      book, <span style="color: blue">this</span>.ChangeSet.GetOriginal(book));
  }</pre>

<p>By-and-large we’ve preserved the existing implementation. However, you can now see we don’t have a direct dependency on <strong>ObjectContext</strong>. Instead all interaction is funneled through the book repository. Doing this will allow us to introduce a mock repository implementation at test time which will allow us to test without any dependency on a database.</p>

<h1>The Repository API</h1>

<p>I’m going to abbreviate the API I show in this post. There are more interesting types and methods in the sample but I want to keep the conversation here focused. The first type we should look at is the <strong>IRepository&lt;T&gt;</strong> interface.</p>

<pre class="code"><span style="color: blue">  public interface </span><span style="color: #2b91af">IRepository</span>&lt;T&gt; : <span style="color: #2b91af">IRepository
</span>  {
    <span style="color: #2b91af">IQueryable</span>&lt;T&gt; GetEntities();
    <span style="color: blue">void </span>Insert(T entity);
    <span style="color: blue">void </span>Update(T entity, T original);
    <span style="color: blue">void </span>Delete(T entity);
  }</pre>

<p>A repository is a simple type that surfaces methods for the Query, Insert, Update, and Delete operations that commonly show up in DomainServices. Also, the repository interface has a per-type affinity. Specifically, you’d have a separate instance for each root entity type (as a side note, this felt a little verbose to me, but also worked nicely. I’ll let you make the final call as to whether it’s worth the extra typing).</p>

<p>Here’s a partial Repository implementation using Entity Framework.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">Repository</span>&lt;T&gt; : <span style="color: #2b91af">IRepository</span>&lt;T&gt; <span style="color: blue">where </span>T : <span style="color: #2b91af">EntityObject
</span>  {
    <span style="color: blue">public virtual </span><span style="color: #2b91af">IQueryable</span>&lt;T&gt; GetEntities()
    {
      <span style="color: blue">return this</span>.ObjectSet;
    }

    <span style="color: blue">public virtual void </span>Insert(T entity)
    {
      <span style="color: blue">if </span>(entity.EntityState != <span style="color: #2b91af">EntityState</span>.Detached)
      {
        <span style="color: blue">this</span>.ObjectContext.ObjectStateManager.<br />          ChangeObjectState(entity, <span style="color: #2b91af">EntityState</span>.Added);
      }
      <span style="color: blue">else
      </span>{
          <span style="color: blue">this</span>.ObjectSet.AddObject(entity);
      }
    }
  }</pre>

<p>As you can see, the repository contains the familiar code required to work against the EF <strong>ObjectContext </strong>and <strong>ObjectSet</strong>. </p>

<p>The next class to look at is a derived repository interface. As you may have noticed already, our book repository has a <strong>GetBooksWithCategories </strong>method that isn’t in the base interface.</p>

<pre class="code"><span style="color: blue">  public interface </span><span style="color: #2b91af">IBookRepository </span>: <span style="color: #2b91af">IRepository</span>&lt;<span style="color: #2b91af">Book</span>&gt;
  {
    <span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooksWithCategories();
  }</pre>

<p>The concrete implementation of this method will show us why it’s interesting.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">BookRepository </span>: <span style="color: #2b91af">Repository</span>&lt;<span style="color: #2b91af">Book</span>&gt;, <span style="color: #2b91af">IBookRepository
</span>  {
    <span style="color: blue">public </span>BookRepository(<span style="color: #2b91af">BookClubEntities </span>objectContext)
        : <span style="color: blue">base</span>(objectContext)
    {
    }

    <span style="color: blue">public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooksWithCategories()
    {
        <span style="color: blue">return this</span>.ObjectSet.Include(<span style="color: #a31515">&quot;Category&quot;</span>);
    }
  }</pre>

<p>Specifically, we’ve used the <strong>Include </strong>method on <strong>ObjectSet</strong>. Since the include method is specific to entity framework, I’ve placed it behind the repository interface.</p>

<h1>The UnitOfWork API</h1>

<p>Both DomainServices and Repositories work on the principal that you can make a lot of changes and then submit them all as a single unit-of-work. To facilitate this, our Repository pattern also provides an <strong>IUnitOfWork </strong>interface.</p>

<pre class="code"><span style="color: blue">  public interface </span><span style="color: #2b91af">IUnitOfWork
</span>  {
    <span style="color: blue">void </span>Save();
  }</pre>

<p>Simple. Now we just need to make sure it is called when our DomainService is ready to persist changes. Luckily, the <strong>DomainService </strong>base class provides a virtual protected method to allow us to do just that.</p>

<pre class="code"><span style="color: green">  // Test 1: Unit of work should be saved
</span><span style="color: blue">  protected override bool </span>PersistChangeSet()
  {
<span style="color: green">    </span><span style="color: blue">this</span>.UnitOfWork.Save();
    <span style="color: blue">return true</span>;
  }</pre>

<p>Finally, we need to make sure the unit-of-work can be used to persist the changes to our Entity Framework model. To do this, we can use a partial class to implement the interface on <strong>BookClubEntities</strong>.</p>

<pre class="code"><span style="color: blue">  public partial class </span><span style="color: #2b91af">BookClubEntities </span>: <span style="color: #2b91af">IUnitOfWork
</span>  {
    <span style="color: blue">public void </span>Save()
    {
      <span style="color: blue">this</span>.SaveChanges();
    }
  }</pre>

<p>Now we’ll need to take a look at how all these pieces are wired up.</p>

<h1>A DomainService Using a Repository</h1>

<p>Like I showed in my previous post, we’ll need to pass the repository to the DomainService’s constructor.</p>

<pre class="code"><span style="color: blue">  public </span>BookClubDomainService(
<span style="color: #2b91af">    IUnitOfWork </span>unitOfWork,<br />    <span style="color: #2b91af">IBookRepository </span>bookRepository,
    <span style="color: #2b91af">ILibraryService </span>libraryService,
    <span style="color: #2b91af">IApprovalSystem </span>approvalSystem)
    : <span style="color: blue">base</span>(unitOfWork, bookRepository) <br />  {
    <span style="color: blue">if </span>(bookRepository == <span style="color: blue">null</span>)
    {
      <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;bookRepository&quot;</span>);
    }
    <span style="color: blue">if </span>(libraryService == <span style="color: blue">null</span>)
    {
      <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;libraryService&quot;</span>);
    }
    <span style="color: blue">if </span>(approvalSystem == <span style="color: blue">null</span>)
    {
      <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;approvalSystem&quot;</span>);
    }

    <span style="color: blue">this</span>._bookRepository = bookRepository;
    <span style="color: blue">this</span>._libraryService = libraryService;
    <span style="color: blue">this</span>._approvalSystem = approvalSystem;
  }</pre>

<p>You can refer back to my previous post on how to create and bootstrap an <strong>IDomainServiceFactory</strong>. I won’t repeat the information here, but I’ll give you a quick look at the factory code that creates the DomainService.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">BookClubDomainServiceFactory </span>: <span style="color: #2b91af">IDomainServiceFactory
</span>  {
    <span style="color: blue">public </span><span style="color: #2b91af">DomainService </span>CreateDomainService(<br />      <span style="color: #2b91af">Type </span>domainServiceType, <span style="color: #2b91af">DomainServiceContext </span>context)
    {
      <span style="color: #2b91af">DomainService </span>domainService;
      <span style="color: blue">if </span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">BookClubDomainService</span>) == domainServiceType)
      {
        <span style="color: #2b91af">BookClubEntities </span>bookClubEntities = <span style="color: blue">new </span><span style="color: #2b91af">BookClubEntities</span>();
        domainService = <span style="color: blue">new </span><span style="color: #2b91af">BookClubDomainService</span>(
          bookClubEntities,
<span style="color: blue">          new </span><span style="color: #2b91af">BookRepository</span>(bookClubEntities), <br />          <span style="color: blue">new </span><span style="color: #2b91af">LibraryService</span>(),
          <span style="color: blue">new </span><span style="color: #2b91af">ApprovalSystem</span>());
      }
      <span style="color: blue">else
      </span>{
        domainService = (<span style="color: #2b91af">DomainService</span>)<br />          <span style="color: #2b91af">Activator</span>.CreateInstance(domainServiceType);
      }

      domainService.Initialize(context);
      <span style="color: blue">return </span>domainService;
    }
  }</pre>

<p>Finally, we need to set the <strong>BookClubDomainService</strong>&#160; to provide the correct metadata about the types it supports. Since we’re returning Entity Framework types, we’ll need to use the <strong>LinqToEntitiesDomainServiceDescriptionProviderAttribute</strong>.</p>

<pre class="code">  [<span style="color: #2b91af">LinqToEntitiesDomainServiceDescriptionProvider</span>(<br />     <span style="color: blue">typeof</span>(<span style="color: #2b91af">BookClubEntities</span>))]
<span style="color: blue">  public class </span><span style="color: #2b91af">BookClubDomainService </span>: <span style="color: #2b91af">RepositoryDomainService </span>{ ... }</pre>

<p>Also, you’ll notice I’ve created a <strong>RepositoryDomainService</strong> base class to encapsulate some of the common Repository concerns. With all these pieces together, it becomes a simple matter to write DomainService operations.</p>

<pre class="code"><span style="color: green">  // Test 1: Operation should return all books
  // Test 2: Operation should return books with categories
  // Test 3: Operation should return books ordered by BookID
</span><span style="color: blue">  public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooks()
  {
    <span style="color: blue">return this</span>._bookRepository.GetBooksWithCategories().<br />             OrderBy(b =&gt; b.BookID);
  }</pre>

<h1>Testing With a Repository</h1>

<p>Though I plan to save most of this for the next post, it’s worth looking at the <strong>MockRespository </strong>we’ll use for testing.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">MockRepository</span>&lt;T&gt; : <span style="color: #2b91af">IRepository</span>&lt;T&gt;
  {
    <span style="color: blue">private readonly </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IList</span>&gt; _entities =<br />      <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IList</span>&gt;();

    <span style="color: blue">public </span><span style="color: #2b91af">List</span>&lt;TEntity&gt; GetTable&lt;TEntity&gt;() { ... }

    <span style="color: blue">public virtual </span><span style="color: #2b91af">IQueryable</span>&lt;T&gt; GetEntities()
    {
      <span style="color: blue">return this</span>.GetTable&lt;T&gt;().AsQueryable();
    }

    <span style="color: blue">public virtual void </span>Insert(T entity)
    {
      <span style="color: blue">this</span>.GetTable&lt;T&gt;().Add(entity);
    }
  }</pre>

<p>The mock repository allows us to populate our table with default data before a test and check the updated contents of the table after the test.</p>

<pre class="code"><span style="color: blue">  private class </span><span style="color: #2b91af">MockBookRepository </span>: <span style="color: #2b91af">MockRepository</span>&lt;<span style="color: #2b91af">Book</span>&gt;, <span style="color: #2b91af">IBookRepository
</span>  {
    <span style="color: blue">public </span>MockBookRepository()
    {
      <span style="color: blue">this</span>.GetTable&lt;<span style="color: #2b91af">Book</span>&gt;().AddRange(<span style="color: blue">new </span>[]
      {
        <span style="color: blue">new </span><span style="color: #2b91af">Book
        </span>{
          AddedDate = <span style="color: #2b91af">DateTime</span>.UtcNow,
          ASIN = <span style="color: #a31515">&quot;1234567890&quot;</span>,
          Author = <span style="color: #a31515">&quot;Author&quot;</span>,
          BookID = 1,
          ...<br />        },<br />        ...
      });
    }
  }</pre>

<p>Now, when we create our DomainService in our tests, we can pass an instance of <strong>MockBookRepository</strong> in instead of our real implementation. Using a repository like this in our tests improves the isolation and consistency. In the last post in this series on testing, I will finally show how to write unit tests for your DomainServices.</p>

<h3><a href="https://blogs.msdn.com/b/kylemc/archive/tags/testing/">Unit Testing Series</a></h3>

<ul>
  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory.aspx">Part 1: The IDomainServiceFactory</a> </li>

  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern.aspx">Part 2: The Repository Pattern</a> </li>

  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost.aspx">Part 3: The DomainServiceTestHost</a> </li>

  <li><a href="https://code.msdn.microsoft.com/Unit-Testing-a-WCF-RIA-a39a700e">Unit Testing Sample Source</a> </li>

  <li><a href="https://nuget.org/List/Packages/RIAServices.UnitTesting">NuGet: RIAServices.UnitTesting</a></li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Unit Testing a WCF RIA DomainService: Part 1, The IDomainServiceFactory</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory</link>
      <pubDate>Thu, 18 Aug 2011 08:06:00 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory/</guid>
      <description><![CDATA[I’ve always been a proponent of driving product quality through unit testing. Regardless of the...]]></description>
      <content:encoded><![CDATA[<p>I’ve always been a proponent of driving product quality through unit testing. Regardless of the specific testing methodology, I enjoy the confidence a rich suite of tests can bring to product and application development. For WCF RIA developers, I wanted to start a three-part series on how to test the business logic that resides at the core of your application; your DomainService operations. During this series, I’ll identify patterns, practices, and tools that make testing your DomainServices simple (and maybe even fun?).</p>  <p>The first step to making your DomainService testable is to identify the external dependencies. </p>  <h1>A DomainService with Dependencies</h1>  <p>We’ll start by looking at a service that has both business logic and dependencies. I’ve authored it in a pretty straightforward manner so I can highlight specific changes that will improve testability.</p>  <pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">BookClubDomainService </span>:<br />    <span style="color: #2b91af">LinqToEntitiesDomainService</span>&lt;<span style="color: #2b91af">BookClubEntities</span>&gt;
  {
    <span style="color: blue">private readonly </span><span style="color: #2b91af">LibraryService </span>_libraryService = <span style="color: blue">new </span><span style="color: #2b91af">LibraryService</span>();
    <span style="color: blue">private readonly </span><span style="color: #2b91af">ApprovalSystem </span>_approvalSystem = <span style="color: blue">new </span><span style="color: #2b91af">ApprovalSystem</span>();

    <span style="color: green">// Test 1: Operation should return all books
    // Test 2: Operation should return books with categories
    // Test 3: Operation should return books ordered by BookID
    </span><span style="color: blue">public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooks()
    {
      <span style="color: blue">return this</span>.ObjectContext.Books.Include(<span style="color: #a31515">&quot;Category&quot;</span>).<br />               OrderBy(b =&gt; b.BookID);
    }

    <span style="color: green">// Test 1: Operation should insert book
    // Test 2: Operation should set the added date
    // Test 3: Operation should request approval for book with invalid ASINs
    // Test 4: Operation should request approval for book not yet published
    </span><span style="color: blue">public void </span>InsertBook(<span style="color: #2b91af">Book </span>book)
    {
      <span style="color: blue">if </span>((book.EntityState != <span style="color: #2b91af">EntityState</span>.Detached))
      {
        <span style="color: blue">this</span>.ObjectContext.ObjectStateManager.<br />          ChangeObjectState(book, <span style="color: #2b91af">EntityState</span>.Added);
      }
      <span style="color: blue">else
      </span>{
        <span style="color: blue">this</span>.ObjectContext.Books.AddObject(book);
      }

      book.AddedDate = <span style="color: #2b91af">DateTime</span>.UtcNow;

      <span style="color: blue">if </span>(!<span style="color: blue">this</span>._libraryService.IsAsinValid(book.ASIN))
      {
        <span style="color: blue">this</span>._approvalSystem.<br />          RequestApproval(book.Author, book.Title, book.PublishDate);
      }
      <span style="color: blue">else if </span>(book.PublishDate &gt; book.AddedDate)
      {
        <span style="color: blue">this</span>._approvalSystem.RequestApproval(book.ASIN);
      }
    }
  }</pre>

<p>A quick look at this service should reveal three concrete dependencies. First, we’re using an Entity Framework <strong>ObjectContext </strong>to talk to a database. We also have a dependency on an external service, <strong>LibraryService</strong>, and an internal subsystem, <strong>ApprovalSystem</strong>. The <strong>ObjectContext </strong>is a unique case which I’ll tackle in the next post, so for now let’s look at what we can do with the <strong>LibraryService </strong>and <strong>ApprovalSystem</strong>.</p>

<p>There are a few options available for testing code with external dependencies. The first is to actually test against the real components; perhaps with modified connection strings to test instances. For example, you could run your tests against a test instance of the database. The second is to use a mocking framework to provide mock implementations for the methods you are using. For example, you could write a quick implementation of <strong>LibraryService.IsAsinValid</strong> to use only with your tests. I’ve been using <a href="https://research.microsoft.com/en-us/projects/pex/">Moles</a> recently, but there are many good frameworks available. Finally, you can use a pattern called Dependency Injection to allow your service code to be passed references to external dependencies.</p>

<p>The rest of this post will cover how to use the <strong>IDomainServiceFactory</strong> interface to enable Dependency Injection. There’s plenty to be said about the other testing options I listed above, but I won’t do it here. A little research should be able to help you determine if and when either of the other options is right for you.</p>

<h1>Factoring External Dependencies</h1>

<p>Now that we’ve identified our external dependencies, we can change the design slightly to allow them to be pass in to the DomainService. Instead of using the concrete types, <strong>LibraryService </strong>and <strong>ApprovalSystem</strong>, we’ll replace them with interfaces.</p>

<pre class="code"><span style="color: blue">  public interface </span><span style="color: #2b91af">ILibraryService
</span>  {
    <span style="color: blue">bool </span>IsAsinValid(<span style="color: blue">string </span>asin);
  }</pre>

<pre class="code"><span style="color: blue">  public interface </span><span style="color: #2b91af">IApprovalSystem
</span>  {
    <span style="color: blue">void </span>RequestApproval(<span style="color: blue">string </span>author, <span style="color: blue">string </span>title, <span style="color: #2b91af">DateTime </span>publishDate);
    <span style="color: blue">void </span>RequestApproval(<span style="color: blue">string </span>asin);
  }</pre>

<p>Next, we’ll update the DomianService to use these interfaces. More importantly, we’ll update the service to require these dependencies be provided to the constructor.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">BookClubDomainService </span>:<br />    <span style="color: #2b91af">LinqToEntitiesDomainService</span>&lt;<span style="color: #2b91af">BookClubEntities</span>&gt;
  {
    <span style="color: blue">private readonly </span><span style="color: #2b91af">ILibraryService </span>_libraryService;
    <span style="color: blue">private readonly </span><span style="color: #2b91af">IApprovalSystem </span>_approvalSystem;

    <span style="color: blue">public </span>BookClubDomainService(<br />      <span style="color: #2b91af">ILibraryService </span>libraryService, <span style="color: #2b91af">IApprovalSystem </span>approvalSystem)
    {
      <span style="color: blue">if </span>(libraryService == <span style="color: blue">null</span>)
      {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;libraryService&quot;</span>);
      }
      <span style="color: blue">if </span>(approvalSystem == <span style="color: blue">null</span>)
      {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;approvalSystem&quot;</span>);
      }

      <span style="color: blue">this</span>._libraryService = libraryService;
      <span style="color: blue">this</span>._approvalSystem = approvalSystem;
    }

    <span style="color: green">// Test 1: Operation should return all books
    // Test 2: Operation should return books with categories
    // Test 3: Operation should return books ordered by BookID
    </span><span style="color: blue">public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Book</span>&gt; GetBooks()
    {
      <span style="color: blue">return this</span>.ObjectContext.Books.Include(<span style="color: #a31515">&quot;Category&quot;</span>).<br />               OrderBy(b =&gt; b.BookID);
    }

    <span style="color: green">// Test 1: Operation should insert book
    // Test 2: Operation should set the added date
    // Test 3: Operation should request approval for book with invalid ASINs
    // Test 4: Operation should request approval for book not yet published
    </span><span style="color: blue">public void </span>InsertBook(<span style="color: #2b91af">Book </span>book)
    {
      <span style="color: blue">if </span>((book.EntityState != <span style="color: #2b91af">EntityState</span>.Detached))
      {
        <span style="color: blue">this</span>.ObjectContext.ObjectStateManager.<br />          ChangeObjectState(book, <span style="color: #2b91af">EntityState</span>.Added);
      }
      <span style="color: blue">else
      </span>{
        <span style="color: blue">this</span>.ObjectContext.Books.AddObject(book);
      }

      book.AddedDate = <span style="color: #2b91af">DateTime</span>.UtcNow;

      <span style="color: blue">if </span>(!<span style="color: blue">this</span>._libraryService.IsAsinValid(book.ASIN))
      {
        <span style="color: blue">this</span>._approvalSystem.<br />          RequestApproval(book.Author, book.Title, book.PublishDate);
      }
      <span style="color: blue">else if </span>(book.PublishDate &gt; book.AddedDate)
      {
        <span style="color: blue">this</span>._approvalSystem.RequestApproval(book.ASIN);
      }
    }
  }</pre>

<p>If you tried to run this service now, you’d see it failing with an error along the lines of “No default constructor exists for the type BookClubDomainService”. To fix this error, we’ll need to understand a little more about how DomainServices are instantiated.</p>

<h1>IDomainServiceFactory</h1>

<p>Each time a client calls into the DomainService endpoint, the RIA hosting layer uses the singleton <strong>DomainService.Factory </strong>to create a new instance of the requested DomainService type. The default <strong>IDomainServiceFactory </strong>implementation expects a DomainService type to provide a parameter-less constructor. Since we’ve changed the constructor above to require two parameters, we now have to create a factory type that can handle our DomainService.</p>

<p>Factories are pretty straightforward to write and only expose a pair of Create/Release methods.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">BookClubDomainServiceFactory </span>: <span style="color: #2b91af">IDomainServiceFactory
</span>  {
    <span style="color: blue">public </span><span style="color: #2b91af">DomainService </span>CreateDomainService(<br />      <span style="color: #2b91af">Type </span>domainServiceType, <span style="color: #2b91af">DomainServiceContext </span>context)
    {
      <span style="color: #2b91af">DomainService </span>domainService;
      <span style="color: blue">if </span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">BookClubDomainService</span>) == domainServiceType)
      {
        domainService = <span style="color: blue">new </span><span style="color: #2b91af">BookClubDomainService</span>(<br />          <span style="color: blue">new </span><span style="color: #2b91af">LibraryService</span>(), <span style="color: blue">new </span><span style="color: #2b91af">ApprovalSystem</span>());
      }
      <span style="color: blue">else
      </span>{
        domainService = (<span style="color: #2b91af">DomainService</span>)<br />          <span style="color: #2b91af">Activator</span>.CreateInstance(domainServiceType);
      }

      domainService.Initialize(context);
      <span style="color: blue">return </span>domainService;
    }

    <span style="color: blue">public void </span>ReleaseDomainService(<span style="color: #2b91af">DomainService </span>domainService)
    {
      domainService.Dispose();
    }
  }</pre>

<p>Now that we have a custom factory, we’ll have to make sure it gets used to instantiate our DomainService. The easiest way to do this is to add a Global.asax file to our web site and bootstrap the factory there.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/37/63/metablogapi/3443.image_5543F4CF.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-37-63-metablogapi/3443.image_5F00_5543F4CF.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" align="left" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/37/63/metablogapi/6663.image_thumb_66B455A7.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-37-63-metablogapi/6663.image_5F00_thumb_5F00_66B455A7.png" width="244" height="28" /></a>&#160;&#160; <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/37/63/metablogapi/7356.image_3B6FBEA0.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-37-63-metablogapi/7356.image_5F00_3B6FBEA0.png"><img style="display: inline" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/37/63/metablogapi/5773.image_thumb_1435756B.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-37-63-metablogapi/5773.image_5F00_thumb_5F00_1435756B.png" width="218" height="43" /></a></p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">Global </span>: System.Web.<span style="color: #2b91af">HttpApplication
</span>  {
    <span style="color: blue">protected void </span>Application_Start(<span style="color: blue">object </span>sender, <span style="color: #2b91af">EventArgs </span>e)
    {
      <span style="color: #2b91af">DomainService</span>.Factory = <span style="color: blue">new </span><span style="color: #2b91af">BookClubDomainServiceFactory</span>();
    }
  }</pre>

<p>Now we can run our service successfully again. The update we made to the DomainService will allow us to pass in test-specific implementations of the external dependencies. This in-turn improves the isolation and consistency of our tests. In parts two and three, I will show how to treat your data access layer as an external dependency and how to actually write the tests.</p>

<h4>[A Note on Dependency Injection]</h4>

<p>Often Dependency Injection is done in a more generic fashion using Injection frameworks. If you find yourself creating a big switch in <strong>IDomainServiceFactory.CreateDomainService </strong>for each DomainService type in your custom factory, you may find it more maintainable to use a framework. There are plenty of them out there, so it shouldn’t be too hard to find one that works for you.</p>

<h1></h1>

<h4>[An Alternate Design]</h4>

<p>Now that you’ve patiently waded through this entire post, it’s worth noting that a custom <strong>IDomainServiceFactory </strong>is not strictly required to make your DomainService testable. For instance, you could provide two constructors for each DomainService; the parameterized constructor for testing and a default constructor that chooses a default value for each dependency. There are benefits to the factory approach (like Dependency Injection), but I’ll leave it up to you to pick the one that fits best.</p>

<h3><a href="https://blogs.msdn.com/b/kylemc/archive/tags/testing/">Unit Testing Series</a></h3>

<ul>
  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory.aspx">Part 1: The IDomainServiceFactory</a> </li>

  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern.aspx">Part 2: The Repository Pattern</a> </li>

  <li><a href="https://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost.aspx">Part 3: The DomainServiceTestHost</a> </li>

  <li><a href="https://code.msdn.microsoft.com/Unit-Testing-a-WCF-RIA-a39a700e">Unit Testing Sample Source</a> </li>

  <li><a href="https://nuget.org/List/Packages/RIAServices.UnitTesting">NuGet: RIAServices.UnitTesting</a></li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>WCF RIA Services in Windows Azure AppFabric June CTP</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/wcf-ria-services-in-windows-azure-appfabric-june-ctp</link>
      <pubDate>Fri, 24 Jun 2011 07:06:19 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/06/24/wcf-ria-services-in-windows-azure-appfabric-june-ctp/</guid>
      <description><![CDATA[If you’ve been using RIA in the cloud or are considering it, it is definitely worth your time to...]]></description>
      <content:encoded><![CDATA[<p>If you’ve been using RIA in the cloud or are considering it, it is definitely worth your time to take a look at the <a href="https://blogs.msdn.com/b/appfabric/archive/2011/06/20/announcing-the-windows-azure-appfabric-june-ctp.aspx">Windows Azure AppFabric June CTP</a>. The CTP is an early look at a platform that is positioned to simplify the development, deployment, and maintenance of applications in the cloud. We’ve made sure RIA works well in the AppFabric environment and that it’s just as easy to build a scalable application for the cloud as it is to build an on-premise web application.</p>  <h1></h1>  <h1>Links</h1>  <p>Since the CTP is large and encompasses a number of different technologies, I thought it’d be worth drawing your attention to RIA-specific links.</p>  <p><a href="https://msdn.microsoft.com/en-us/library/hh239692.aspx">Here’s an overview of RIA in AppFabric Applications</a></p>  <p><a href="https://msdn.microsoft.com/en-us/library/hh264595.aspx">Here’s an overview of the Silverlight Business Application Pattern for AppFabric</a></p>  <p><a href="https://www.microsoft.com/downloads/en/details.aspx?FamilyID=d89640fc-c552-446e-aead-b1e0d940f31b&amp;displaylang=en">You can download the AppFabric Samples for the June CTP here</a></p>  <p>Also, when you download the CTP, make sure you install the AppFabricVsToolsCtp.</p>  <h1>Take a Look</h1>  <p>I thought about adding some snapshots to this post, but all the RIA stuff is just the same as you’re used to. The goal was to make it easy for you to pick up the CTP and play around with the bits. So take a look and send me some feedback. Let me know how it handles and the kinds of things you want to see. Thanks.</p>]]></content:encoded>
    </item>
    <item>
      <title>Writing a Custom CollectionViewLoader for the DomainCollectionView and MVVM</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/writing-a-custom-collectionviewloader-for-the-domaincollectionview-and-mvvm</link>
      <pubDate>Fri, 13 May 2011 10:05:30 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/05/13/writing-a-custom-collectionviewloader-for-the-domaincollectionview-and-mvvm/</guid>
      <description><![CDATA[The question I’ve been fielding most lately is how to write a custom CollectionViewLoader. Once you...]]></description>
      <content:encoded><![CDATA[<p>The question I’ve been fielding most lately is how to write a custom <strong>CollectionViewLoader</strong>. Once you see it done, it’s a pretty simple task. Without an example it’s hard to know where to start. In a previous post, <a href="https://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx">I discussed how the view, loader, and source related to each other</a>. In this post, I’ll show how that translates to the code you write.</p>  <h1>The Loader as part of your View Model</h1>  <p>Out of the three parts of the <strong>DomainCollectionView (DCV) </strong>triad, the loader is the piece mostly closely aligned with your View Model. In fact, I wrote the default implementation (the <strong>DomainCollectionViewLoader</strong>) with callbacks so you could put all the code you cared about directly in your VM. That said, feel free to blur the lines between your VM and your <strong>CollectionViewLoader</strong> until you find the balance of functionality and reusability you feel comfortable with.</p>  <h1>The CollectionViewLoader</h1>  <p>A good place to start is to take a look at public surface area of the <strong>CollectionViewLoader </strong>type you’ll be extending.</p>  <pre class="code"><span style="color: blue">  public abstract class </span><span style="color: #2b91af">CollectionViewLoader
</span>  {
<span style="color: gray">    </span><span style="color: blue">public event </span><span style="color: #2b91af">EventHandler </span>CanLoadChanged;
<span style="color: gray">    </span><span style="color: blue">public event </span>AsyncCompletedEventHandler LoadCompleted;

<span style="color: blue">    public abstract bool </span>CanLoad { <span style="color: blue">get</span>; }

<span style="color: blue">    public abstract void </span>Load(<span style="color: blue">object </span>userState);
  }</pre>

<p>It’s a simple abstract class with one method, one property, and two events. The <strong>Load</strong> method is responsible for asynchronously loading data into the source collection of the collection view. Since the <strong>Load </strong>method is asynchronous, it needs to raise a <strong>LoadCompleted </strong>event when it completes. The <strong>CanLoad </strong>property tells the <strong>DCV </strong>whether it can safely invoke the <strong>Load </strong>method. There are a number of <strong>CanXx </strong>properties in the <strong>ICollectionView </strong>interface, and changes to the <strong>CanLoad </strong>property will propagate to all of them. For example, since re-sorting the <strong>DCV </strong>will result in a <strong>Load </strong>call, <strong>CanSort </strong>will be set to false when <strong>CanLoad </strong>is false.</p>

<h1>The Sample</h1>

<p>I’ve also had a number of questions lately about how to use the <strong>DCV </strong>with the <a href="https://blogs.msdn.com/b/kylemc/archive/2011/04/29/mvvm-pattern-for-ria-services.aspx">MVVM pattern I proposed in a recent post</a>. This will be a two-birds-with-one-stone sample where I’ll show how to write a custom <strong>CollectionViewLoader </strong>that works with the MVVM service pattern. It’s worth noting this sample is a variant of the one I published with <a href="https://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx">my original DCV post</a>.</p>

<p>I’ll start with the custom loader code and work back through the rest of the sample.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">SampleCollectionViewLoader</span>&lt;TEntity&gt;<br />    : <span style="color: #2b91af">CollectionViewLoader </span><span style="color: blue">where </span>TEntity : <span style="color: #2b91af">Entity
</span>  {
    <span style="color: blue">private </span><span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;TEntity&gt;&gt;, <span style="color: blue">object</span>&gt; _load;
    <span style="color: blue">private </span><span style="color: #2b91af">Action</span>&lt;<span style="color: blue">object</span>&gt; _cancelLoad;
    <span style="color: blue">private </span><span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;TEntity&gt;&gt; _onLoadCompleted;

    <span style="color: blue">private object </span>_currentUserState;

    <span style="color: blue">public </span>SampleCollectionViewLoader(
        <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;TEntity&gt;&gt;, <span style="color: blue">object</span>&gt; load,
        <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">object</span>&gt; cancelLoad,
        <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;TEntity&gt;&gt; onLoadCompleted)
    {
      <span style="color: blue">if </span>(load == <span style="color: blue">null</span>)
      {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;load&quot;</span>);
      }
      <span style="color: blue">if </span>(onLoadCompleted == <span style="color: blue">null</span>)
      {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;onLoadCompleted&quot;</span>);
      }

      <span style="color: blue">this</span>._load = load;
      <span style="color: blue">this</span>._cancelLoad = cancelLoad;
      <span style="color: blue">this</span>._onLoadCompleted = onLoadCompleted;
    }

    <span style="color: blue">public override bool </span>CanLoad
    {
      <span style="color: blue">get </span>{ <span style="color: blue">return true</span>; }
    }

    <span style="color: blue">private object </span>CurrentUserState
    {
      <span style="color: blue">get
      </span>{
        <span style="color: blue">return this</span>._currentUserState;
      }

      <span style="color: blue">set
      </span>{
        <span style="color: blue">if </span>(<span style="color: blue">this</span>._currentUserState != <span style="color: blue">value</span>)
        {
          <span style="color: blue">if </span>(<span style="color: blue">this</span>._cancelLoad != <span style="color: blue">null</span>)
          {
            <span style="color: blue">this</span>._cancelLoad(<span style="color: blue">this</span>._currentUserState);
          }
        }

        <span style="color: blue">this</span>._currentUserState = <span style="color: blue">value</span>;
      }
    }

    <span style="color: blue">public override void </span>Load(<span style="color: blue">object </span>userState)
    {
      <span style="color: blue">if </span>(!<span style="color: blue">this</span>.CanLoad)
      {
        <span style="color: blue">throw new </span><span style="color: #2b91af">InvalidOperationException</span>(<br />                    <span style="color: #a31515">&quot;Load cannot be called when CanLoad is false&quot;</span>);
      }
      <span style="color: blue">this</span>.CurrentUserState = userState;
      <span style="color: blue">this</span>._load(<span style="color: blue">this</span>.OnLoadCompleted, userState);
    }

    <span style="color: blue">private void </span>OnLoadCompleted(<span style="color: #2b91af">ServiceLoadResult</span>&lt;TEntity&gt; result)
    {
      <span style="color: blue">this</span>._onLoadCompleted(result);

      <span style="color: blue">if </span>(<span style="color: blue">this</span>.CurrentUserState == result.UserState)
      {
        <span style="color: blue">this</span>.CurrentUserState = <span style="color: blue">null</span>;
      }

      <span style="color: blue">base</span>.OnLoadCompleted(result);
    }
  }</pre>

<p>This custom <strong>CollectionViewLoader </strong>in this sample is pretty straightforward and follows the pattern used in the <strong>DomainCollectionViewLoader </strong>to call back into the view model. It has three callbacks; one for loading, one for canceling, and one for load completion. As you can see, the signature of the callbacks differs from the ones in the <strong>DomainCollectionViewLoader</strong>. This is necessary to work with the service layer in a natural way which I’ll explain more in the next section.</p>

<p>There are a couple more things to note about this implementation. First, I haven’t done anything with the <strong>CanLoad </strong>property. In the sample I include a <strong>IsGridEnabled </strong>flag in the <strong>SampleViewModel </strong>that serves roughly the same purpose (and behaves a little nicer from a UI perspective when using the standard Silverlight <strong>DataGrid</strong>). Second, the bulk of the code that’s not calling into the view model is related to cancellation. I’ll talk a little more about that at the end.</p>

<p>The next part of the sample to look at is the service interface. It’s pretty simple and encapsulates loading sample entities.</p>

<pre class="code"><span style="color: blue">  public interface </span><span style="color: #2b91af">ISampleService
</span>  {
    <span style="color: #2b91af">EntityContainer </span>EntityContainer { <span style="color: blue">get</span>; }

    <span style="color: blue">void </span>LoadSampleEntities(
      <span style="color: #2b91af">QueryBuilder</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; query,
      <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;&gt; callback,
      <span style="color: blue">object </span>state);
  }</pre>


<p>Next, we’ll take a look at the view model. It’s going to be the place where the <strong>SampleCollectionViewLoader</strong>, the <strong>SampleService</strong>, and all the callbacks are tied together.</p>

<pre class="code"><span style="color: blue">  public </span>SampleViewModel()
  {
    <span style="color: blue">this</span>._source = <span style="color: blue">new </span><span style="color: #2b91af">EntityList</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;(<br />      <span style="color: blue">this</span>._service.EntityContainer.GetEntitySet&lt;<span style="color: #2b91af">SampleEntity</span>&gt;());<br />
    <span style="color: blue">this</span>._loader = <span style="color: blue">new </span><span style="color: #2b91af">SampleCollectionViewLoader</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;(
      <span style="color: blue">this</span>.LoadSampleEntities,
      <span style="color: blue">this</span>.CancelLoadSampleEntities,
      <span style="color: blue">this</span>.OnLoadSampleEntitiesCompleted);<br />
    <span style="color: blue">this</span>._view = <span style="color: blue">new </span><span style="color: #2b91af">DomainCollectionView</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;(<br />      <span style="color: blue">this</span>._loader,<br />      <span style="color: blue">this</span>._source);

<span style="color: blue">    </span><span style="color: green">// Go back to the first page when the sorting changes
    </span><span style="color: #2b91af">INotifyCollectionChanged </span>notifyingSortDescriptions = 
      <span style="color: blue">this</span>.CollectionView.SortDescriptions;
    notifyingSortDescriptions.CollectionChanged +=
      (sender, e) =&gt; <span style="color: blue">this</span>._view.MoveToFirstPage();

    <span style="color: blue">using </span>(<span style="color: blue">this</span>.CollectionView.DeferRefresh())
    {
      <span style="color: blue">this</span>._view.PageSize = 10;
      <span style="color: blue">this</span>._view.MoveToFirstPage();
    }
  }</pre>


<p>The source is created using an <strong>EntitySet </strong>provided by the <strong>EntityContainer </strong>in the <strong>ISampleService</strong>. The loader now creates a <strong>SampleCollectionViewLoader </strong>and passes in three view model callbacks. We’ll take a look at two of those callbacks next.</p>

<pre class="code"><span style="color: blue">  private void </span>LoadSampleEntities(<br />    <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;&gt; onLoadCompleted,<br />    <span style="color: blue">object </span>userState)
  {
    <span style="color: blue">this</span>.IsGridEnabled = <span style="color: blue">false</span>;

    <span style="color: blue">this</span>._service.LoadSampleEntities(
      <span style="color: blue">new </span><span style="color: #2b91af">QueryBuilder</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;().SortAndPageBy(<span style="color: blue">this</span>._view),
      onLoadCompleted,
      userState);
  }

<span style="color: blue">  private void </span>OnLoadSampleEntitiesCompleted(<br />    <span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; result)
  {
    <span style="color: blue">this</span>.IsGridEnabled = <span style="color: blue">true</span>;

    <span style="color: blue">if </span>(result.Error != <span style="color: blue">null</span>)
    {
      <span style="color: green">// </span><span style="color: #00008b">TODO: handle errors
    </span>}
    <span style="color: blue">else if </span>(!result.Cancelled)
    {
      <span style="color: blue">this</span>._source.Source = result.Entities;

      <span style="color: blue">if </span>(result.TotalEntityCount != -1)
      {
        <span style="color: blue">this</span>._view.SetTotalItemCount(result.TotalEntityCount);
      }
    }
  }</pre>


<p>If you’ve followed my previous posts on the subject (linked prolifically above), these two implementations will look very familiar. The only significant difference is that the loader passes a completion callback and user state through to the <strong>LoadSampleEntities </strong>method for it to pass to the service layer. When the service load completes, it will tell the loader which will in-turn tell the view model.</p>

<h1>A Note on Cancellation</h1>

<p>Cancellation is a tricky subject on its own, but I’ll try to address how it fits into this pattern. Since a <strong>CollectionViewLoader </strong>is only dealing with one set of data, each subsequent load should cancel the previous one. In the sample for the MVVM pattern, I had cancellation in the service layer. It’s an approach that worked on the assumption you only invoke one current load per entity type. It’s pretty easy to see how this assumption fails to scale, though, so other approaches are necessary. If you find yourself using the same load method for multiple purposes, I’d recommend adding a cancel method to the service layer that looks like <strong>CancelLoadXx(object userState)</strong>. You can then invoke this from the cancel callback you pass to the loader.</p>

<h1>Summary</h1>

<p>Like I mentioned at the beginning of this post, I expect you to write custom <strong>CollectionViewLoaders </strong>that support the kinds of things you want to do in your view model. Hopefully this post gives you a template to start from. Feel free to customize it however you see fit.</p>

<p>Here’s the source for the sample. It shows a little more detail on things fit together. Let me know what you think and if you have questions.</p>

<p><a title="https://code.msdn.microsoft.com/Writing-a-Custom-e0769d37" href="https://code.msdn.microsoft.com/Writing-a-Custom-e0769d37">https://code.msdn.microsoft.com/Writing-a-Custom-e0769d37</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Survey: How Do You Use the DomainService Wizard?</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/survey-how-do-you-use-the-domainservice-wizard</link>
      <pubDate>Thu, 05 May 2011 08:27:20 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/05/05/survey-how-do-you-use-the-domainservice-wizard/</guid>
      <description><![CDATA[I need to ask a favor of all my regular readers out there (*crickets*). I often hear stories along...]]></description>
      <content:encoded><![CDATA[<p>I need to ask a favor of all my regular readers out there (*crickets*). I often hear stories along the lines of “I use the DomainService Wizard to generate my DomainService. Then I make tiny changes to the generated code or metadata and may move it or split it into separate files. Later, when I update my database, I re-run the DomainService Wizard to re-generate my DomainService and manually merge the newly generated service with the old one.”</p>  <p>So my question is this: “What problem are you solving?”</p>  <p>I think we can all admit any solution where one of the steps is “manually merge” is sub-optimal. This is something I want to fix. If you’ll oblige me, I’d love to hear what you’re doing and why you’re doing it (as a bonus, responding to this post makes it much more likely I’ll address your scenario).</p>  <p>Feel free to add a short comment with your thoughts or <a href="https://blogs.msdn.com/b/kylemc/contact.aspx">email me directly</a>. Thanks.</p>]]></content:encoded>
    </item>
    <item>
      <title>MVVM Pattern for RIA Services</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/mvvm-pattern-for-ria-services</link>
      <pubDate>Fri, 29 Apr 2011 09:06:06 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/04/29/mvvm-pattern-for-ria-services/</guid>
      <description><![CDATA[At the Silverlight Firestarter ‘10, John Papa did a great talk on MVVM Patterns for Silverlight and...]]></description>
      <content:encoded><![CDATA[<p>At the <a href="https://www.silverlight.net/news/events/firestarter/">Silverlight Firestarter ‘10</a>, John Papa did a great talk on <a href="https://channel9.msdn.com/Series/Silverlight-Firestarter/Silverlight-Firestarter-2010-Session-4-MVVM-Why-and-How-Tips-and-Patterns-using-MVVM-and-Service-Pat">MVVM Patterns for Silverlight and WP7</a> that featured WCF RIA Services as the data layer. For that talk, I helped him streamline the service layer abstraction to correctly work with the RIA client. However, there were a number of great RIA features like querying and change tracking that weren’t surfacing in the view model layer. It was such a shame that I wanted to take a second pass over the pattern to see if I could make it better. I was able to sort out things a little better leading up to <a href="https://jeffhandley.com/archive/2011/04/13/MIX11Releases.aspx">Mix ‘11</a> and the result is the new <strong>QueryBuilder</strong> type we shipped in the <a href="https://jeffhandley.com/archive/2011/04/13/MIX11Releases.aspx">RIA Toolkit</a>.</p>  <p>I’ve put together <a href="https://code.msdn.microsoft.com/MVVM-Sample-for-WCF-RIA-115b1f38">a reworked version of John’s BookShelf sample to highlight the changes</a>.</p>  <h1>The BookShelf Sample</h1>  <p>The primary type we’re interested in here is the <strong>IBookDataService</strong>. Also interesting are the types that implement and consume it. Thankfully this is a small list composed of the interface, the design-time implementation, the actual implementation, and the view model. I’ll make changes to each and try explain the rationale in this post. Typically the deciding factor is whether a type can be returned by a mock or design-time implementation (and to a lesser extent, whether the design is awesome).</p>  <p>In addition, I wrote up some result types that bring a lot of the value of the RIA Operation types to the view model layer. I’ll cover those in a section at the end.</p>  <h2>IBookDataService</h2>  <p>Since the changes to the service interface drive the changes elsewhere, we should start by looking at the <strong>IBookDataService</strong>.</p>  <pre class="code"><span style="color: blue">  public interface </span><span style="color: #2b91af">IBookDataService
</span>  {
    <span style="color: #2b91af">EntityContainer </span>EntityContainer { <span style="color: blue">get</span>; }

    <span style="color: blue">void </span>SubmitChanges(<br />           <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceSubmitChangesResult</span>&gt; callback,<br />           <span style="color: blue">object </span>state);

    <span style="color: blue">void </span>LoadBooksByCategory(<br />           <span style="color: blue">int </span>categoryId,<br />           <span style="color: #2b91af">QueryBuilder</span>&lt;<span style="color: #2b91af">Book</span>&gt; query,<br />           <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">Book</span>&gt;&gt; callback,<br />           <span style="color: blue">object </span>state);
    <span style="color: blue">void </span>LoadBooksOfTheDay(<br />           <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">BookOfDay</span>&gt;&gt; callback,<br />           <span style="color: blue">object </span>state);
    <span style="color: blue">void </span>LoadCategories(<br />           <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">Category</span>&gt;&gt; callback,<br />           <span style="color: blue">object </span>state);
    <span style="color: blue">void </span>LoadCheckouts(<br />           <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">Checkout</span>&gt;&gt; callback,<br />           <span style="color: blue">object </span>state);
  }</pre>

<p>There are a few things worth noting. First, the <strong>EntityContainer </strong>is available as part of the interface. If you aren’t familiar with it, the <strong>EntityContainer</strong> is the type the <strong>DomainContext </strong>uses to store <strong>EntitySets</strong>, implement change tracking, and compose change sets. Luckily, the <strong>EntityContainer</strong> is designed such that it can live as easily in a mock implementation as the real one. Adding it to the service layer provides a lot of power while still enabling both separation and testability.</p>

<p>Second, all the callbacks pass a service result type. These types contain a distilled version of their RIA counterparts (LoadOperation, etc.) and I’ll cover them at the end.</p>

<p>Finally, the <strong>LoadBooksByCategory </strong>method takes both the <strong>categoryId</strong> and a <strong>QueryBuilder </strong>as <sub></sub>arguments. This not only allows the service layer to filter the books by category, but it also allows the view model layer to put together custom queries that will be run on the server (sorting, paging, etc.).</p>

<h2>DesignBookDataService</h2>

<p>The design-time service implementation is simple and closely resembles the original version.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">DesignBookDataService </span>: <span style="color: #2b91af">IBookDataService
</span>  {
    <span style="color: blue">private readonly </span><span style="color: #2b91af">EntityContainer </span>_entityContainer =<br />      <span style="color: blue">new </span><span style="color: #2b91af">BookClubContext</span>.<span style="color: #2b91af">BookClubContextEntityContainer</span>();

    <span style="color: blue">public </span><span style="color: #2b91af">EntityContainer </span>EntityContainer
    {
      <span style="color: blue">get </span>{ <span style="color: blue">return this</span>._entityContainer; }
    }

    ...</pre>

<pre class="code">    <span style="color: blue">public void </span>LoadBooksByCategory(<br />                  <span style="color: blue">int </span>categoryId,<br />                  <span style="color: #2b91af">QueryBuilder</span>&lt;<span style="color: #2b91af">Book</span>&gt; query,<br />                  <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">Book</span>&gt;&gt; callback,<br />                  <span style="color: blue">object </span>state)
    {
      <span style="color: blue">this</span>.Load(query.ApplyTo(<span style="color: blue">new </span><span style="color: #2b91af">DesignBooks</span>()), callback, state);
    }

    ...</pre>

<pre class="code">    <span style="color: blue">private void </span>Load&lt;T&gt;(<br />                   <span style="color: #2b91af">IEnumerable</span>&lt;T&gt; entities,<br />                   <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;T&gt;&gt; callback,<br />                   <span style="color: blue">object </span>state)<br />                 <span style="color: blue">where </span>T : <span style="color: #2b91af">Entity
    </span>{
      <span style="color: blue">this</span>.EntityContainer.LoadEntities(entities);
      callback(<span style="color: blue">new </span><span style="color: #2b91af">ServiceLoadResult</span>&lt;T&gt;(entities, state));
    }
  }</pre>

<p>The <strong>EntityContainer </strong>is the same internal type as the one use in the <strong>BookClubContext</strong>, but could easily be mocked if the design-time service and generated proxies lived in different assemblies.</p>

<p>The <strong>LoadBooksByCategory </strong>method applies the query to a static data-set before invoking a generic <strong>Load </strong>method. The generic version makes sure the entities are contained in the <strong>EntityContainer </strong>and then asynchronously invokes the callback.</p>

<h2>BookDataService</h2>

<p>The actual service implementation is greatly simplified and is now much closer to the design-time version.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">BookDataService </span>: <span style="color: #2b91af">IBookDataService
</span>  {
    <span style="color: blue">private readonly </span><span style="color: #2b91af">BookClubContext </span>_context = <span style="color: blue">new </span><span style="color: #2b91af">BookClubContext</span>();

    ...

    <span style="color: blue">public </span><span style="color: #2b91af">EntityContainer </span>EntityContainer
    {
      <span style="color: blue">get </span>{ <span style="color: blue">return this</span>._context.EntityContainer; }
    }

    ...<span style="color: blue"></span></pre>

<pre class="code">    <span style="color: blue">public void </span>LoadBooksByCategory(<br />                  <span style="color: blue">int </span>categoryId,<br />                  <span style="color: #2b91af">QueryBuilder</span>&lt;<span style="color: #2b91af">Book</span>&gt; query,<br />                  <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">Book</span>&gt;&gt; callback,<br />                  <span style="color: blue">object </span>state)
    {
      <span style="color: blue">this</span>.Load(<br />        query.ApplyTo(<span style="color: blue">this</span>._context.GetBooksByCategoryQuery(categoryId)),<br />        lo =&gt;
        {
          callback(<span style="color: blue">this</span>.CreateResult(lo, <span style="color: blue">true</span>));
        }, state);
    }

    <span style="color: blue">...</span></pre>

<pre class="code"><pre class="code"><span style="color: blue">    private void </span>Load&lt;T&gt;(<br />                   <span style="color: #2b91af">EntityQuery</span>&lt;T&gt; query,<br />                   <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">LoadOperation</span>&lt;T&gt;&gt; callback,<br />                   <span style="color: blue">object </span>state)<br />                 <span style="color: blue">where </span>T : <span style="color: #2b91af">Entity
</span>    {
      ...</pre><pre class="code">      <span style="color: blue">this</span>._context.Load(query, lo =&gt;
        {
          ...<br />          callback(lo);
        }, state);
    }
</pre>    <span style="color: blue">private </span><span style="color: #2b91af">ServiceLoadResult</span>&lt;T&gt; CreateResult&lt;T&gt;(<br />                                   <span style="color: #2b91af">LoadOperation</span>&lt;T&gt; op,<br />                                   <span style="color: blue">bool </span>returnEditableCollection = <span style="color: blue">false</span>)<br />                                 <span style="color: blue">where </span>T : <span style="color: #2b91af">Entity
    </span>{
      <span style="color: blue">if </span>(op.HasError)
      {
        op.MarkErrorAsHandled();
      }
      <span style="color: blue">return new </span><span style="color: #2b91af">ServiceLoadResult</span>&lt;T&gt;(
        returnEditableCollection ?<br />          <span style="color: blue">new </span><span style="color: #2b91af">EntityList</span>&lt;T&gt;(<br />            <span style="color: blue">this</span>.EntityContainer.GetEntitySet&lt;T&gt;(),<br />            op.Entities) :<br />          op.Entities,
        op.TotalEntityCount,
        op.ValidationErrors,
        op.Error,
        op.IsCanceled,
        op.UserState);
    }
  }</pre>

<p>Again we can see the <strong>LoadBooksByCategory </strong>method applying the query; this time to an <strong>EntityQuery</strong>. It also creates a callback that it can pass through to the <strong>DomainContext.Load</strong> method.</p>

<p>It’s worth noting the <strong>CreateResult </strong>method has the option to return an editable collection or a read-only one. When we take a look at the view model, you’ll be able to see it working against both.</p>

<h2>BookViewModel</h2>

<p>The view model has changed a number of things to consume the new interface, but it’s all still pretty straightforward.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">BookViewModel </span>: <span style="color: #2b91af">ViewModel
</span>  {
    <span style="color: blue">private const int </span>_pageSize = 10;

    <span style="color: blue">private int </span>_pageIndex;

    <span style="color: blue">protected </span><span style="color: #2b91af">IPageConductor </span>PageConductor { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">protected </span><span style="color: #2b91af">IBookDataService </span>BookDataService { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

    ... <font color="#0000ff"><br /></font>
    <span style="color: blue">public </span>BookViewModel(
      <span style="color: #2b91af">IPageConductor </span>pageConductor,
      <span style="color: #2b91af">IBookDataService </span>bookDataService)
    {
      PageConductor = pageConductor;
      BookDataService = bookDataService;
      BookDataService.EntityContainer.PropertyChanged +=<br />        BookDataService_PropertyChanged;

      RegisterCommands();
      LoadData();
    }

    <span style="color: blue">private void </span>BookDataService_PropertyChanged(<br />                   <span style="color: blue">object </span>sender, <span style="color: #2b91af">PropertyChangedEventArgs </span>e)
    {
      <span style="color: blue">if </span>(e.PropertyName == <span style="color: #a31515">&quot;HasChanges&quot;</span>)
      {
        HasChanges = BookDataService.EntityContainer.HasChanges;
        SaveBooksCommand.RaiseCanExecuteChanged();
      }
    }

    ...</pre>

<pre class="code">    <span style="color: blue">public void </span>LoadBooksByCategory()
    {
      _pageIndex = 0;
      Books = <span style="color: blue">null</span>;
      <span style="color: blue">if </span>(SelectedCategory != <span style="color: blue">null</span>)
      {
        BookDataService.LoadBooksByCategory(
          SelectedCategory.CategoryID,
          <span style="color: blue">new </span><span style="color: #2b91af">QueryBuilder</span>&lt;<span style="color: #2b91af">Book</span>&gt;().Take(_pageSize),
          LoadBooksCallback,
          <span style="color: blue">null</span>);
      }
    }

    <span style="color: blue">private void </span>OnLoadMoreBooksByCategory()
    {
      <span style="color: blue">if </span>(SelectedCategory != <span style="color: blue">null</span>)
      {
        _pageIndex++;
        BookDataService.LoadBooksByCategory(
          SelectedCategory.CategoryID,
          <span style="color: blue">new </span><span style="color: #2b91af">QueryBuilder</span>&lt;<span style="color: #2b91af">Book</span>&gt;()<br />                .Skip(_pageIndex * _pageSize).Take(_pageSize),
          LoadBooksCallback,
          <span style="color: blue">null</span>);
      }
    }

    <span style="color: blue">public void </span>LoadBooksByTitle()
    {
      _pageIndex = 0;
      Books = <span style="color: blue">null</span>;
      <span style="color: blue">if </span>(SelectedCategory != <span style="color: blue">null</span>)
      {
        BookDataService.LoadBooksByCategory(
          SelectedCategory.CategoryID,
          <span style="color: blue">new </span><span style="color: #2b91af">QueryBuilder</span>&lt;<span style="color: #2b91af">Book</span>&gt;()<br />                .Where(b =&gt; b.Title.Contains(TitleFilter)),
          LoadBooksCallback,
          <span style="color: blue">null</span>);
      }
    }

    <span style="color: blue">private void </span>LoadBooksCallback(<span style="color: #2b91af">ServiceLoadResult</span>&lt;<span style="color: #2b91af">Book</span>&gt; result)
    {
      <span style="color: blue">if </span>(result.Error != <span style="color: blue">null</span>)
      {
        <span style="color: green">// handle error
      </span>}
      <span style="color: blue">else if </span>(!result.Cancelled)
      {
        <span style="color: blue">if </span>(Books == <span style="color: blue">null</span>)
        {
          Books = result.Entities <span style="color: blue">as </span><span style="color: #2b91af">ICollection</span>&lt;<span style="color: #2b91af">Book</span>&gt;;
        }
        <span style="color: blue">else
        </span>{
          <span style="color: blue">foreach </span>(<span style="color: blue">var </span>book <span style="color: blue">in </span>result.Entities)
          {
            Books.Add(book);
          }
        }

        SelectedBook = Books.FirstOrDefault();
      }
    }

    <span style="color: blue">private </span><span style="color: #2b91af">ICollection</span>&lt;<span style="color: #2b91af">Book</span>&gt; _books;
    <span style="color: blue">public </span><span style="color: #2b91af">ICollection</span>&lt;<span style="color: #2b91af">Book</span>&gt; Books
    {
      <span style="color: blue">get </span>{ <span style="color: blue">return </span>_books; }
      <span style="color: blue">set
      </span>{
        _books = <span style="color: blue">value</span>;
        RaisePropertyChanged(<span style="color: #a31515">&quot;Books&quot;</span>);
      }
    }

    ...<br />  }</pre>

<p>The first place to highlight is in the constructor where the view model subscribes to property change events on the <strong>EntityContainer</strong>. This allows the view model to listen directly for changes made to any of the entities it is working against.</p>

<p>The second point of interest is the three, similarly-implemented load methods. The significant difference between each implementation is the query it composes to pass to the <strong>IBookDataService</strong>. In all three cases, the composed query will be run on the server.</p>

<p>Finally, the <strong>LoadBooksCallback</strong> casts <strong>result.Entities</strong> to an <strong>ICollection&lt;Book&gt;</strong>. This is because <strong>Books </strong>is a collection that supports the adding and removing of entities. In this case, the collection is simply aggregating the results of multiple queries, but the same pattern could be used for the creation of new entities. The reason this pattern works is because the <strong>BookDataService </strong>is returning an <strong>EntityList </strong>from <strong>CreateResult (</strong>above), and <strong>EntityList </strong>knows how to correctly handle the addition and removal of entities.</p>

<h2>Service Result Types</h2>

<p>I added three result types to the sample (to the Ria.Common project), <strong>ServiceInvokeResult</strong>, <strong>ServiceLoadResult</strong>, and <strong>ServiceSubmitChangesResult</strong>. While the base operation types have some great features, they aren’t convenient to use in mock or design-time implementations. In addition, there is a lot of useful information in these types that is important to return from the service layer. Each of the result types has properties that closely parallel their operation types. For instance, the <strong>ServiceLoadResult </strong>has properties for the <strong>Error </strong>and <strong>Cancelled </strong>states as well as the enumerable <strong>Entities</strong>. As can be seen in the <strong>LoadBooksCallback</strong> above, the pattern for consuming the result type is very similar to the standard RIA pattern; check for errors, check for cancelation, and then process the entities.</p>

<h1>QueryBuilder and the DomainCollectionView</h1>

<p>Though it isn’t apparent in this sample, the <strong>QueryBuilder </strong>also acts as a bridge between the <strong>DomainCollectionView </strong>(<a href="https://blogs.msdn.com/b/kylemc/archive/2011/04/15/domaincollectionview-updates-for-mix-11.aspx">read about the DomainCollectionView</a>) and the service layer. Each of the query extensions provided for the <strong>DCV</strong> work against the <strong>QueryBuilder </strong>as well. For instance, <strong>SortAndPageBy </strong>could be applied to the query in the view model before passing the <strong>QueryBuilder </strong>to the service layer.</p>

<h1>Summary</h1>

<p>I covered a lot in this post and I wouldn’t be surprised if there are still questions to be answered. It’s not my desire to present a canonical MVVM pattern with this post, but the design here is well-worn and a good place to start. Hopefully types, ideas, and patterns in this post prove useful to you. Please let me know what think and if you have any questions.</p>

<h1></h1>

<h4>[Interesting Variations]</h4>

<p>Since writing this, there have been a few intrepid developers who’ve written variations on the pattern worth mentioning.</p>

<ul>
  <li>Remco combined the pattern with my <a href="https://blogs.msdn.com/b/kylemc/archive/2010/11/02/using-the-visual-studio-async-ctp-with-ria-services.aspx">guidance on using Tasks (from the VS Async CTP)</a> to create a <a href="https://code.msdn.microsoft.com/Task-based-MVVM-Sample-for-2eb86fab">Task Based MVVM Sample</a>.</li>

  <li>Colin riffed in a couple directions first <a href="https://bitly.com/bundles/colinblair/2">combining the pattern with MEF and then splitting it into a number of class libraries</a>.</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>DomainCollectionView Updates for Mix ‘11</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/domaincollectionview-updates-for-mix-11</link>
      <pubDate>Fri, 15 Apr 2011 08:30:12 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/04/15/domaincollectionview-updates-for-mix-11/</guid>
      <description><![CDATA[To correspond to the new RIA Services build we’ve released at Mix, I’ve made some updates to the...]]></description>
      <content:encoded><![CDATA[<p>To correspond to the new RIA Services build we’ve released at Mix, I’ve made some updates to the <strong>DomainCollectionView</strong>. I updated select API, fixed a few bugs, and updated the sample as well. If you’re not familiar with the <strong>DCV</strong>, here’s <a href="https://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx">my original post introducing it</a>. For the sake of brevity in this post, I’ll assume you’ve read it.</p>  <h1>Breaking Changes</h1>  <p>There are a few breaking changes to the API. Most notably, <strong>SortPageAndCount </strong>has been renamed. It’s a breaking change, but a simple find-replace should set things right again.</p>  <ul>   <li><strong>SortAndPageBy </strong>replaces <strong>SortPageAndCount</strong>       <ul>       <li><strong>SortAndPageBy </strong>calls <strong>SortBy </strong>and <strong>PageBy </strong>respectively </li>     </ul>   </li>    <li><strong>SortBy </strong>replaces <strong>Sort</strong>       <ul>       <li><strong>SortBy </strong>applies <strong>OrderBy </strong>and <strong>ThenBy </strong>clauses to the query </li>     </ul>   </li>    <li><strong>PageBy </strong>replaces <strong>Page</strong>       <ul>       <li><strong>PageBy </strong>applies <strong>Skip </strong>and <strong>Take </strong>clauses to the query and conditionally requests the <strong>TotalEntityCount</strong> </li>     </ul>   </li>    <li>(All the other query extensions have been removed)      <br /></li> </ul>  <h1>Bug Fixes</h1>  <p>There were a few bug fixes that went in to improve compatibility with third-party controls. I’ve tested the <strong>DCV </strong>against four suites of controls now, and it works well with all of them. As always, let me know when you find issues.</p>  <h1>Sample</h1>  <p>A common question in response to the first post was how to implement filtering. It turns out to be pretty easy, so I wanted to make it obvious with some updates to my sample.</p>  <p>I’ve updated the UI to include a search field.</p>  <pre class="code"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/37/63/metablogapi/1185.image_136148B1.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/1185.image_5F00_136148B1.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/37/63/metablogapi/0513.image_thumb_79F94576.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/0513.image_5F00_thumb_5F00_79F94576.png" width="400" height="189" /></a> </pre>

<p>The search button now invokes the search command which calls into the <strong>OnSearch </strong>method in my <strong>SampleViewModel</strong>.</p>

<pre class="code"><span style="color: blue">  private void </span>OnSearch()
  {
    <span style="color: green">// This makes sure we refresh even if we're already on the first page
    </span><span style="color: blue">using </span>(<span style="color: blue">this</span>._view.DeferRefresh())
    {
      <span style="color: green">// This will lead us to re-query for the total count
      </span><span style="color: blue">this</span>._view.SetTotalItemCount(-1);
      <span style="color: blue">this</span>._view.MoveToFirstPage();
    }
  }</pre>

<p>The <strong>OnSearch </strong>method resets the total item count and refreshes the view; leading us back into our load callback.</p>

<pre class="code"><span style="color: blue">  private </span><span style="color: #2b91af">LoadOperation</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; LoadSampleEntities()
  {
    <span style="color: blue">this</span>.CanLoad = <span style="color: blue">false</span>;

    <span style="color: #2b91af">EntityQuery</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; query = <span style="color: blue">this</span>._context.GetAllEntitiesQuery();
    <span style="color: blue">if </span>(!<span style="color: blue">string</span>.IsNullOrWhiteSpace(<span style="color: blue">this</span>.SearchText))
    {
      query = query.Where(e =&gt; e.String.Contains(<span style="color: blue">this</span>.SearchText));
    }

    <span style="color: blue">return this</span>._context.Load(query.SortAndPageBy(<span style="color: blue">this</span>._view));
  }</pre>

<p>To make sure the filter gets applied on the server, we conditionally add a <strong>Where </strong>clause to our query based on the content of the <strong>SearchText</strong>.</p>

<p>That covers the new additions to the <strong>DomainCollectionView</strong>. Once again we’ve put together a small sample running with server-side filtering, sorting, grouping, and paging. Here’re the sample bits. Let me know if you have any questions.</p>

<p><a title="https://code.msdn.microsoft.com/Server-Side-Filtering-737becda" href="https://code.msdn.microsoft.com/Server-Side-Filtering-737becda">https://code.msdn.microsoft.com/Server-Side-Filtering-737becda</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Using RIA Services with ComboBoxes and Enums</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/using-ria-services-with-comboboxes-and-enums</link>
      <pubDate>Thu, 06 Jan 2011 13:29:09 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2011/01/06/using-ria-services-with-comboboxes-and-enums/</guid>
      <description><![CDATA[The other day someone asked me how to get a ComboBox working with enums and validation. It turned...]]></description>
      <content:encoded><![CDATA[<p>The other day someone asked me how to get a <strong>ComboBox </strong>working with enums and validation. It turned out to be more tricky than I had anticipated (<a href="https://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx">there’s a common theme here…</a>) so I figured I’d put together a quick post on it.</p>  <h1>Stumbling Points</h1>  <p>This section describes two specific traps I fell into. It’s not necessarily important for you to understand the details, but I’ll include them just in case you’re interested. Feel free to skip straight to the solution.</p>  <p>My first error was related to sharing enums in RIA. Due to the way enums appear in assembly metadata, the RIA code generator can’t determine whether they exist on the client or not. If you put an enum in a <em>.shared.cs </em>or <em>.shared.vb </em>file, it will quickly result in a compile error. The solution to this issue is simple. Instead of sharing the enum between tiers, just define it on your server and let codegen take care of the rest.</p>  <p>The second error I ran into was using client-side projection properties. In the past I’ve preferred these to using an <strong>IValueConverter</strong> in my bindings, but this investigation (finally) helped me to realize this approach has adverse effects on RIA validation. When the property being validated is named something other than the property being set (for example, the MyString property would write through to the MyEnum property where validation would occur) the visual control state will not be updated to reflect the error (no fancy red adornment).</p>  <h1>The Solution</h1>  <p>I eventually ended up using an <strong>IValueConverter</strong>-based solution. I put a little extra work into it to make it <strong>DisplayAttribute</strong>-aware since metadata is a commonly-used RIA feature. I wrote a utility to encapsulate most of this, but I’ll go over that piece at the end once you’ve got a grip on how it all fits together. (Similar variants of this solution are available in a number of places, but I wanted to fill in some of the corners that often get ignored)</p>  <p>I applied these changes to the sample I used in this post (<a title="https://blogs.msdn.com/b/kylemc/archive/2010/11/12/silverlight-tv-52-ria-services-q-a.aspx" href="https://blogs.msdn.com/b/kylemc/archive/2010/11/12/silverlight-tv-52-ria-services-q-a.aspx">https://blogs.msdn.com/b/kylemc/archive/2010/11/12/silverlight-tv-52-ria-services-q-a.aspx</a>) if you want a place to try it out. These steps should work in any scenario, though.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/37/63/metablogapi/0385.image_6F0AC0AB.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/0385.image_5F00_6F0AC0AB.png"><img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/37/63/metablogapi/2860.image_thumb_3868DB9B.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/2860.image_5F00_thumb_5F00_3868DB9B.png" width="168" height="142" /></a></p>  <p>To create the look above, I defined a simple enum with <strong>DisplayAttributes</strong> on each of the values.</p>  <pre class="code"><span style="color: blue">  public enum </span><span style="color: #2b91af">MyEnum
</span>  {
    [<span style="color: #2b91af">Display</span>(Name = <span style="color: #a31515">&quot;(please pick a value)&quot;</span>)]
    None = 0,
    [<span style="color: #2b91af">Display</span>(Name = <span style="color: #a31515">&quot;Value 1&quot;</span>)]
    Value1 = 1,
    [<span style="color: #2b91af">Display</span>(Name = <span style="color: #a31515">&quot;Value 2&quot;</span>)]
    Value2 = 2,
    [<span style="color: #2b91af">Display</span>(Name = <span style="color: #a31515">&quot;Value 3&quot;</span>)]
    Value3 = 3,
  }</pre>

<p>Then I added a property to my entity that used custom validation to ensure a non-zero value is selected.</p>

<pre class="code">  [<span style="color: #2b91af">CustomValidation</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">Validation</span>), <span style="color: #a31515">&quot;ValidateMyEnum&quot;</span>)]
  [<span style="color: #2b91af">DataMember</span>]
<span style="color: blue">  public </span><span style="color: #2b91af">MyEnum </span>MyEnum { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>

<p>(My validation is in a shared file in the web project, <em>Validation.shared.cs</em>)</p>

<pre class="code"><span style="color: blue">  public static class </span><span style="color: #2b91af">Validation
</span>  {
    <span style="color: blue">public static </span><span style="color: #2b91af">ValidationResult </span>ValidateMyEnum(<br />      <span style="color: #2b91af">MyEnum </span>myEnum, <span style="color: #2b91af">ValidationContext </span>context)
    {
      <span style="color: blue">if </span>(myEnum == <span style="color: #2b91af">MyEnum</span>.None)
      {
        <span style="color: blue">return new </span><span style="color: #2b91af">ValidationResult</span>(<br />          <span style="color: #a31515">&quot;You must pick a value.&quot;</span>, <span style="color: blue">new</span>[] { context.MemberName });
      }
      <span style="color: blue">return </span><span style="color: #2b91af">ValidationResult</span>.Success;
    }
  }</pre>

<p>My next step was to define the <strong>ComboBox </strong>on the client.</p>

<pre class="code">  <span style="color: blue">&lt;</span><span style="color: #a31515">ComboBox </span><span style="color: red">ItemsSource</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">myEnumNames</span><span style="color: blue">}&quot;
            </span><span style="color: red">SelectedItem</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Path</span><span style="color: blue">=MyEnum</span><span style="color: blue">,<br />                                   </span><span style="color: red">Mode</span><span style="color: blue">=TwoWay,<br />                                   </span><span style="color: red">Converter</span><span style="color: blue">={</span><span style="color: #a31515">StaticResource </span><span style="color: red">enumToString</span><span style="color: blue">}}&quot;<br />  /&gt;
</span></pre>

<p>The <strong>SelectedItem </strong>binding references a converter I instantiate in my page resources.</p>

<pre class="code"><span style="color: blue">  &lt;</span><span style="color: #a31515">app</span><span style="color: blue">:</span><span style="color: #a31515">EnumToStringValueConverter </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Key</span><span style="color: blue">=&quot;enumToString&quot; /&gt;
</span></pre>

<p>The code for the converter is simple and leverages the <strong>EnumUtility</strong> I’ll describe a little later. It is also generic so a single instance can be shared between multiple types of enums.</p>

<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">EnumToStringValueConverter </span>: <span style="color: #2b91af">IValueConverter
</span>  {
    <span style="color: blue">public object </span>Convert(<span style="color: blue">object </span>value, <span style="color: #2b91af">Type </span>targetType,<br />      <span style="color: blue">object </span>parameter, <span style="color: #2b91af">CultureInfo </span>culture)
    {
      <span style="color: blue">return </span><span style="color: #2b91af">EnumUtility</span>.GetName(value.GetType(), value);
    }

    <span style="color: blue">public object </span>ConvertBack(<span style="color: blue">object </span>value, <span style="color: #2b91af">Type </span>targetType,<br />      <span style="color: blue">object </span>parameter, <span style="color: #2b91af">CultureInfo </span>culture)
    {
      <span style="color: blue">return </span><span style="color: #2b91af">EnumUtility</span>.GetValue(targetType, value.ToString());
    }
  }</pre>

<p>The <strong>ItemsSource </strong>in the <strong>ComboBox</strong> above uses a static resource I add in my page constructor before parsing the xaml (in <strong>InitializeComponent</strong>). I’ve used the <strong>EnumUtility </strong>again to get the names for my enum.</p>

<pre class="code"><span style="color: blue">  this</span>.Resources.Add(<span style="color: #a31515">&quot;myEnumNames&quot;</span>, <span style="color: #2b91af">EnumUtility</span>.GetNames(<span style="color: blue">typeof</span>(<span style="color: #2b91af">MyEnum</span>)));<br />  InitializeComponent();</pre>

<p>With all the pieces in place (an enum, a property to bind to, a converter, a list of names, and a <strong>ComboBox</strong>), I now have a <strong>ComboBox </strong>bound to an enum and validating input.</p>

<h1>An Enum Utility</h1>

<p>I wrote a utility class to handle most of the heavy lifting here. For each enum type, it iterates through all the values and figures out the names they should be mapped to. The <strong>GetName </strong>and <strong>GetValue </strong>methods map back and forth between the two. Here’s the source in case you’re interested.</p>

<pre class="code"><span style="color: blue">  public static class </span><span style="color: #2b91af">EnumUtility
</span>  {
    <span style="color: blue">private static readonly<br />      </span><span style="color: #2b91af">IDictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">string</span>&gt;&gt; names =<br />        <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">string</span>&gt;&gt;();
    <span style="color: blue">private static readonly<br />      </span><span style="color: #2b91af">IDictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">object</span>&gt;&gt; values =<br />        <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">object</span>&gt;&gt;();
    <span style="color: blue">private static readonly<br />     </span><span style="color: blue"> </span><span style="color: #2b91af">IDictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IDictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;&gt; namesToValues =<br />        <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IDictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;&gt;();
    <span style="color: blue">private static readonly<br />      </span><span style="color: #2b91af">IDictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IDictionary</span>&lt;<span style="color: blue">object</span>, <span style="color: blue">string</span>&gt;&gt; valuesToNames =<br />        <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">IDictionary</span>&lt;<span style="color: blue">object</span>, <span style="color: blue">string</span>&gt;&gt;();

    <span style="color: blue">public static void </span>Initialize(<span style="color: #2b91af">Type </span>type)
    {
      Initialize(type, GetDisplayAttributeName);
    }

    <span style="color: blue">public static void </span>Initialize(<br />      <span style="color: #2b91af">Type </span>type, <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">FieldInfo</span>, <span style="color: blue">string</span>&gt; getName)
    {
      <span style="color: blue">if </span>(type == <span style="color: blue">null</span>)
      {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;type&quot;</span>);
      }

      <span style="color: blue">if </span>(!type.IsEnum)
      {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentException</span>(<span style="color: #a31515">&quot;Type must be an enum.&quot;</span>, <span style="color: #a31515">&quot;type&quot;</span>);
      }

      <span style="color: blue">if </span>(getName == <span style="color: blue">null</span>)
      {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;getName&quot;</span>);
      }

      <span style="color: blue">if </span>(names.ContainsKey(type))
      {
        <span style="color: blue">return</span>;
      }
        
      <span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt; tempNames = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt;();
      <span style="color: #2b91af">List</span>&lt;<span style="color: blue">object</span>&gt; tempValues = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: blue">object</span>&gt;();
      <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; tempNamesToValues =<br />        <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;();
      <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">object</span>, <span style="color: blue">string</span>&gt; tempValuesToNames =<br />        <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">object</span>, <span style="color: blue">string</span>&gt;();

      <span style="color: blue">foreach </span>(<span style="color: #2b91af">FieldInfo </span>fi <span style="color: blue">in<br />        </span>type.GetFields(<span style="color: #2b91af">BindingFlags</span>.Public | <span style="color: #2b91af">BindingFlags</span>.Static))
      {
        <span style="color: blue">string </span>name = getName(fi);
        <span style="color: blue">object </span>value = fi.GetValue(<span style="color: blue">null</span>);

        tempNames.Add(name);
        tempValues.Add(value);
        tempNamesToValues[name] = value;
        tempValuesToNames[value] = name;
      }

      names[type] = tempNames;
      values[type] = tempValues;
      namesToValues[type] = tempNamesToValues;
      valuesToNames[type] = tempValuesToNames;
    }

    <span style="color: blue">private static string </span>GetDisplayAttributeName(<span style="color: #2b91af">FieldInfo </span>fi)
    {
      <span style="color: #2b91af">DisplayAttribute </span>displayAttribute = <br />       (<span style="color: #2b91af">DisplayAttribute</span>)fi.GetCustomAttributes(<br />         <span style="color: blue">typeof</span>(<span style="color: #2b91af">DisplayAttribute</span>), <span style="color: blue">false</span>).FirstOrDefault();

      <span style="color: blue">return </span>(displayAttribute == <span style="color: blue">null</span>) ? fi.Name : displayAttribute.Name;
    }

    <span style="color: blue">public static </span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">string</span>&gt; GetNames(<span style="color: #2b91af">Type </span>type)
    {
      Initialize(type);
      <span style="color: blue">return </span>names[type];
    }

    <span style="color: blue">public static </span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">object</span>&gt; GetValues(<span style="color: #2b91af">Type </span>type)
    {
      Initialize(type);
      <span style="color: blue">return </span>values[type];
    }

    <span style="color: blue">public static string </span>GetName(<span style="color: #2b91af">Type </span>type, <span style="color: blue">object </span>value)
    {
      Initialize(type);
      <span style="color: blue">return </span>valuesToNames[type][value];
    }

    <span style="color: blue">public static object </span>GetValue(<span style="color: #2b91af">Type </span>type, <span style="color: blue">string </span>name)
    {
      Initialize(type);
      <span style="color: blue">return </span>namesToValues[type][name];
    }
  }</pre>]]></content:encoded>
    </item>
    <item>
      <title>Collection Binding Options in WCF RIA Services SP1</title>
      <link>https://docs.microsoft.com/archive/blogs/kylemc/collection-binding-options-in-wcf-ria-services-sp1</link>
      <pubDate>Thu, 02 Dec 2010 09:05:43 GMT</pubDate>
      <dc:creator><![CDATA[kylemc]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/kylemc/2010/12/02/collection-binding-options-in-wcf-ria-services-sp1/</guid>
      <description><![CDATA[One of the most common tasks when developing a RIA Services application binding to a collection of...]]></description>
      <content:encoded><![CDATA[<p>One of the most common tasks when developing a RIA Services application binding to a collection of data. There are some declarative options that include binding directly to your <strong>DomainContext </strong>or <strong>DomainDataSource</strong>. These options are great for spinning up applications quickly, but don’t translate well to view model patterns. For that reason, I thought it’d be worth taking a moment to go through the options that make sense in an MVVM context.</p>  <h1>Bind to an EntitySet</h1>  <p>As of SP1, we <a href="https://blogs.msdn.com/b/kylemc/archive/2010/10/28/improved-binding-support-in-entityset-and-entitycollection.aspx">improved binding support for EntitySets</a>. <strong>EntitySets </strong>are aggregating, un-ordered collections. That means every time an entity is loaded by your <strong>DomainContext </strong>it will be added to its corresponding <strong>EntitySet</strong>. Binding to an <strong>EntitySet </strong>will give you a great view of every entity of a specific type your <strong>DomainContext </strong>knows about. Adding to or removing from an <strong>EntitySet </strong>will result in calls to the insert and delete operations being invoked when you submit changes to your <strong>DomainService</strong>.</p>  <p>Making an <strong>EntitySet </strong>available in your view model would look like this.</p>  <pre class="code"><span style="color: blue">  public </span><span style="color: #2b91af">EntitySet</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; EntitySet
  {
    <span style="color: blue">get </span>{ <span style="color: blue">return this</span>.Context.SampleEntities; }
  }</pre>

<h1>Bind to an EntityCollection</h1>

<p>In SP1, we also <a href="https://blogs.msdn.com/b/kylemc/archive/2010/10/28/improved-binding-support-in-entityset-and-entitycollection.aspx">improved binding support for EntityCollections</a>. <strong>EntityCollections </strong>are collections of entities associated with a specific <strong>Entity</strong>. In a manner similar to the <strong>EntitySet</strong>, an <strong>EntityCollection </strong>will be updated as new entities are loaded into your <strong>DomainContext</strong>. Each will be added to the <strong>EntityCollection </strong>of the <strong>Entity </strong>it is associated with. Adding and removing from an <strong>EntityCollection </strong>will only update the association. Most of the time, this results in an update operation being invoked when you submit changes.</p>

<p>Since <strong>EntityCollections</strong> are tied to specified <strong>Entities</strong>, having a property on your view model seems like an uncommon case. Nevertheless, making an <strong>EntityCollection </strong>available in your view model would look like this.</p>

<pre class="code"><span style="color: blue">  public </span><span style="color: #2b91af">EntityCollection</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; EntityCollection
  {
    <span style="color: blue">get </span>{ <span style="color: blue">return this</span>.CurrentEntity.AssociatedEntities; }
  }</pre>

<h1>Bind to an EntityList</h1>

<p><strong>EntityList </strong>is a type new to SP1 and can be found in <strong>Microsoft.Windows.Data.DomainServices</strong> in the Toolkit. An <strong>EntityList </strong>is an observable collection backed by an <strong>EntitySet</strong>. The <strong>Source </strong>property on the <strong>EntityList </strong>defines the entities it contains, and it will not update as new entities are loaded into your <strong>DomainContext</strong>. It will update if entities it contains are deleted from the <strong>EntitySet </strong>or when entities are added or removed from its <strong>Source </strong>collection. Adding to an <strong>EntityList </strong>will behave in one of two ways. If the entity already exists in the backing <strong>EntitySet</strong>, then it is just added to the list. If it does not exist, then it will be added to the <strong>EntitySet </strong>as well. Removing from the <strong>EntityList </strong>will always remove the entity from the backing <strong>EntitySet</strong>. Binding to an <strong>EntityList </strong>is a great option when you only want to see a subset of the entities your <strong>DomainContext </strong>knows about.</p>

<p>Making an <strong>EntityList </strong>available in your view model would look like this.</p>

<pre class="code"><span style="color: blue">  private </span><span style="color: #2b91af">EntityList</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; _entityList;
<span style="color: blue">  public </span><span style="color: #2b91af">EntityList</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; EntityList
  {
    <span style="color: blue">get
    </span>{
      <span style="color: blue">if </span>(<span style="color: blue">this</span>._entityList == <span style="color: blue">null</span>)
      {
        <span style="color: blue">this</span>._entityList = <span style="color: blue">new </span><span style="color: #2b91af">EntityList</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;(<br />          <span style="color: blue">this</span>.Context.SampleEntities);
      }
      <span style="color: blue">return this</span>._entityList;
    }
  }

<span style="color: blue">  private void </span>LoadSampleEntities()
  {
    <span style="color: blue">this</span>.EntityList.Source =
      <span style="color: blue">this</span>.Context.Load(<span style="color: blue">this</span>.Context.GetAllEntitiesQuery()).Entities;
  }</pre>

<h1>Bind to an ICollectionView</h1>

<p>In case you’re not familiar with the <strong>ICollectionView </strong>interface, it’s used by a number of components (<strong>DataGrid</strong>, <strong>DataForm</strong>, etc.) as a view over a source collection. For example, when you bind <strong>DataGrid.ItemsSource </strong>to a collection, it will create a collection view behind the scenes to interact with. Instead of just having the control instantiate a view behind the scenes, you have the option of making the <strong>ICollectionView</strong> available for binding directly from your view model.</p>

<p>It may not be readily apparent why you’d do this, but as you did into the interface, you’ll noticed it has a number of properties for defining how the view presents the source collection. You can control the sorting, grouping, and filtering as well as which item is selected; all from the <strong>ICollectionView</strong>.</p>

<p>In Silverlight, most collection view implementations are internal. Fortunately, there’s an easy way of letting the framework instantiate the correct view for the collection that uses the <strong>CollectionViewSource</strong>.</p>

<pre class="code"><span style="color: blue">  private static </span><span style="color: #2b91af">ICollectionView </span>CreateView(<span style="color: #2b91af">IEnumerable </span>source)
  {
    <span style="color: #2b91af">CollectionViewSource </span>cvs = <span style="color: blue">new </span><span style="color: #2b91af">CollectionViewSource</span>();
    cvs.Source = source;
    <span style="color: blue">return </span>cvs.View;
  }</pre>

<p>Making an <strong>ICollectionView </strong>available in your view model would look like this.</p>

<pre class="code"><span style="color: blue">  private </span><span style="color: #2b91af">ICollectionView </span>_collectionView;
<span style="color: blue">  public </span><span style="color: #2b91af">ICollectionView </span>CollectionView
  {
    <span style="color: blue">get
    </span>{
      <span style="color: blue">if </span>(<span style="color: blue">this</span>._collectionView == <span style="color: blue">null</span>)
      {
        <span style="color: blue">this</span>._collectionView = CreateView(<span style="color: blue">this</span>.Context.SampleEntities);
      }
      <span style="color: blue">return this</span>._collectionView;
    }
  }</pre>

<p>The downside of using this approach is that all the existing collection view implementations only operate over the in-memory collection. That means you have to pull all the data to Silverlight before you apply sorting or filtering.</p>

<h1>Bind to a DomainCollectionView</h1>

<p>To address the limitations of existing <strong>ICollectionView</strong> implementations we’ve added the <strong>DomainCollectionView </strong>in SP1 in <strong>Microsoft.Windows.Data.DomainServices</strong> in the Toolkit. It is designed to allow for asynchronous sorting, grouping, and paging, and works with all the controls that use the collection view interfaces. This enables you to page over data on your server using the core data controls.</p>

<p>The setup for a <strong>DomainCollectionView </strong>is slightly more complicated than some of these other options. This is because it requires load callbacks as well as a source collection. These callbacks can be implemented just like any other load operation in your view model.</p>

<pre class="code"><span style="color: blue">  private </span><span style="color: #2b91af">LoadOperation</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; LoadSampleEntities()
  {
    <span style="color: blue">return this</span>.Context.Load(
      <span style="color: blue">this</span>.Context.GetAllEntitiesQuery().SortPageAndCount(<br />        <span style="color: blue">this</span>.DomainCollectionView));
  }

<span style="color: blue">  private void </span>OnLoadSampleEntitiesCompleted(<span style="color: #2b91af">LoadOperation</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; op)
  {
    <span style="color: blue">if </span>(op.HasError)
    {
      <span style="color: green">// TODO: handle errors
      </span>op.MarkErrorAsHandled();
    }
    <span style="color: blue">else if </span>(!op.IsCanceled)
    {
      <span style="color: blue">this</span>.EntityList.Source = op.Entities;

      <span style="color: blue">if </span>(op.TotalEntityCount != -1)
      {
        <span style="color: blue">this</span>.DomainCollectionView.SetTotalItemCount(op.TotalEntityCount);
      }
    }
  }</pre>

<p>With callbacks defined, making a <strong>DomainCollectionView </strong>available in your view model would look like this.</p>

<pre class="code"><span style="color: blue">  private </span><span style="color: #2b91af">DomainCollectionView</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; _domainCollectionView;
<span style="color: blue">  public </span><span style="color: #2b91af">DomainCollectionView</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt; DomainCollectionView
  {
    <span style="color: blue">get
    </span>{
      <span style="color: blue">if </span>(<span style="color: blue">this</span>._domainCollectionView == <span style="color: blue">null</span>)
      {
        <span style="color: blue">this</span>._domainCollectionView =
          <span style="color: blue">new </span><span style="color: #2b91af">DomainCollectionView</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;(
            <span style="color: blue">new </span><span style="color: #2b91af">DomainCollectionViewLoader</span>&lt;<span style="color: #2b91af">SampleEntity</span>&gt;(
              <span style="color: blue">this</span>.LoadSampleEntities,
              <span style="color: blue">this</span>.OnLoadSampleEntitiesCompleted),
            <span style="color: blue">this</span>.EntityList);
      }
      <span style="color: blue">return this</span>._domainCollectionView;
    }
  }</pre>

<p>This is just enough to get you started with the <strong>DomainCollectionView</strong>, but it leaves out most of the details. In this next post, I go much more in-depth and explain the design and core API.</p>

<p><a title="https://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx" href="https://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx">https://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx</a></p>

<h1>Are there other options?</h1>

<p>There are always other options, but I’m not sure I’d recommend using them. One common alternative would be to make the property types of these collections their respective interfaces (for instance <strong>IEnumerable</strong> or <strong>ICollectionView</strong>). This can reduce coupling and give you more flexibility. Also, since most Silverlight controls that bind to collections are just looking for interfaces, the impact is negligible.</p>

<p>If you have other suggestions, I’d love to hear them. Hope this overview helps.</p>]]></content:encoded>
    </item>
  </channel>
</rss>