<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-US"><title type="html">Kyle McClellan</title><subtitle type="html">Making Software Easier</subtitle><id>http://blogs.msdn.com/b/kylemc/atom.aspx</id><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/" /><link rel="self" type="application/atom+xml" href="http://blogs.msdn.com/b/kylemc/atom.aspx" /><generator uri="http://telligent.com" version="5.6.583.17018">Telligent Community 5.6.583.17018 (Build: 5.6.583.17018)</generator><updated>2010-08-31T17:17:00Z</updated><entry><title>Unit Testing a WCF RIA DomainService: Part 3, The DomainServiceTestHost</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost.aspx</id><published>2011-08-18T15:10:30Z</published><updated>2011-08-18T15:10:30Z</updated><content type="html">&lt;p&gt;In this thrilling conclusion to my series on unit testing, I’ll show you how to use the &lt;strong&gt;DomainServiceTestHost &lt;/strong&gt;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.&lt;/p&gt;  &lt;h1&gt;The DomainService&lt;/h1&gt;  &lt;p&gt;The DomainService we’re testing looks like this.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;RepositoryDomainService
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;BookClubDomainService(
      &lt;span style="color: #2b91af"&gt;IUnitOfWork &lt;/span&gt;unitOfWork,
      &lt;span style="color: #2b91af"&gt;IBookRepository &lt;/span&gt;bookRepository,
      &lt;span style="color: #2b91af"&gt;ILibraryService &lt;/span&gt;libraryService,
      &lt;span style="color: #2b91af"&gt;IApprovalSystem &lt;/span&gt;approvalSystem) { ... }

    &lt;span style="color: green"&gt;// Test 1: Operation should return all books
    // Test 2: Operation should return books with categories
    // Test 3: Operation should return books ordered by BookID
    &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooks() { ... }

    &lt;span style="color: green"&gt;// Test 1: Operation should return all books for category
    // Test 2: Operation should return books ordered by BookID
    &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooksForCategory(&lt;span style="color: blue"&gt;int &lt;/span&gt;categoryId) { ... }

    &lt;span style="color: green"&gt;// 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
    &lt;/span&gt;&lt;span style="color: blue"&gt;public void &lt;/span&gt;InsertBook(&lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book) { ... }

    &lt;span style="color: green"&gt;// Test 1: Operation should update book
    // Test 2: Operation should return validation errors
    &lt;/span&gt;&lt;span style="color: blue"&gt;public void &lt;/span&gt;UpdateBook(&lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book) { ... }

    &lt;span style="color: green"&gt;// Test 1: Operation should update book
    // Test 2: Operation should update the added date
    &lt;/span&gt;[&lt;span style="color: #2b91af"&gt;Update&lt;/span&gt;(UsingCustomMethod = &lt;span style="color: blue"&gt;true&lt;/span&gt;)]
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AddNewEdition(&lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book) { ... }

    &lt;span style="color: green"&gt;// Test 1: Operation should delete book
    // Test 2: Operation should require authentication
    &lt;/span&gt;[&lt;span style="color: #2b91af"&gt;RequiresAuthentication&lt;/span&gt;]
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;DeleteBook(&lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book) { ... }

    &lt;span style="color: green"&gt;// Test 1: Operation should return the most recent added date
    &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DateTime &lt;/span&gt;GetLatestActivity() { ... }
  }&lt;/pre&gt;

&lt;p&gt;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).&lt;/p&gt;

&lt;h1&gt;The DomainServiceTestHost&lt;/h1&gt;

&lt;p&gt;The &lt;strong&gt;DomainServiceTestHost &lt;/strong&gt;is a new class in the &lt;strong&gt;Microsoft.ServiceModel.DomainServices.Server.UnitTesting &lt;/strong&gt;assembly (now on &lt;a href="http://nuget.org/List/Packages/RIAServices.UnitTesting"&gt;NuGet&lt;/a&gt; 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 &lt;strong&gt;Query &lt;/strong&gt;method for retrieving data, and &lt;strong&gt;Insert&lt;/strong&gt;, &lt;strong&gt;Update&lt;/strong&gt;, and &lt;strong&gt;Delete &lt;/strong&gt;methods for modifying it.&lt;/p&gt;

&lt;p&gt;In addition to standard operation support, the test host makes it simple to test validation and authorization. For each standard signature in the &lt;strong&gt;DomainServiceTestHost&lt;/strong&gt;, there is a &lt;strong&gt;TryXx &lt;/strong&gt;variant that makes it easy to capture validation errors. For instance, &lt;strong&gt;Query &lt;/strong&gt;is paired with &lt;strong&gt;TryQuery &lt;/strong&gt;and &lt;strong&gt;Insert &lt;/strong&gt;with &lt;strong&gt;TryInsert&lt;/strong&gt;. Also, each time you create a test host, you can pass an&amp;#160; &lt;strong&gt;IPrincipal &lt;/strong&gt;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.&lt;/p&gt;

&lt;h1&gt;Testing a DomainService&lt;/h1&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;TestInitialize&lt;/span&gt;]
&lt;span style="color: blue"&gt;  public void &lt;/span&gt;TestInitialize()
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._libraryService = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MockLibraryService&lt;/span&gt;();
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._approvalSystem = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FakeApprovalSystem&lt;/span&gt;();
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._unitOfWork = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FakeUnitOfWork&lt;/span&gt;();
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MockBookRepository&lt;/span&gt;();

    &lt;span style="color: blue"&gt;this&lt;/span&gt;._domainServiceTestHost =&lt;br /&gt;      &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainServiceTestHost&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;BookClubDomainService&lt;/span&gt;&amp;gt;(&lt;br /&gt;        &lt;span style="color: blue"&gt;this&lt;/span&gt;.CreateDomainService);
  }

&lt;span style="color: blue"&gt;  private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainService &lt;/span&gt;CreateDomainService()
  {
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainService&lt;/span&gt;(
             &lt;span style="color: blue"&gt;this&lt;/span&gt;._unitOfWork,
             &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository,
             &lt;span style="color: blue"&gt;this&lt;/span&gt;._libraryService,
             &lt;span style="color: blue"&gt;this&lt;/span&gt;._approvalSystem);
  }&lt;/pre&gt;

&lt;p&gt;As you can see, I’ve written simple mock/fake/stub types for each dependency. I discussed the &lt;strong&gt;MockBookRepository &lt;/strong&gt;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 &lt;strong&gt;CreateDomainService&lt;/strong&gt; method that I can pass to the test host that initializes my &lt;strong&gt;BookClubDomainService &lt;/strong&gt;with the test dependencies. If you’re not familiar with the Visual Studio testing, the &lt;strong&gt;[TestInitialize]&lt;/strong&gt; method will get called before the start of each test.&lt;/p&gt;

&lt;p&gt;Starting with something simple, we’ll take a look at the test for the default query.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
  [&lt;span style="color: #2b91af"&gt;Description&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Tests that the GetBooks query returns all the books&amp;quot;&lt;/span&gt;)]
&lt;span style="color: blue"&gt;  public void &lt;/span&gt;GetBooks_ReturnsAllBooks()
  {
    &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; books = &lt;span style="color: blue"&gt;this&lt;/span&gt;._domainServiceTestHost.&lt;br /&gt;                                Query(ds =&amp;gt; ds.GetBooks());

    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;br /&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository.GetBooksWithCategories().Count(), books.Count(),
      &lt;span style="color: #a31515"&gt;&amp;quot;Operation should return all books&amp;quot;&lt;/span&gt;);
  }&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
  [&lt;span style="color: #2b91af"&gt;Description&lt;/span&gt;(&lt;br /&gt;     &lt;span style="color: #a31515"&gt;&amp;quot;Tests that the GetBooksForCategory query orders books by BookID&amp;quot;&lt;/span&gt;)]
&lt;span style="color: blue"&gt;  public void &lt;/span&gt;GetBooksForCategory_OrderedByBookID()
  {
    &lt;span style="color: blue"&gt;int &lt;/span&gt;categoryId = &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository.GetTable&amp;lt;&lt;span style="color: #2b91af"&gt;Category&lt;/span&gt;&amp;gt;().&lt;br /&gt;                       First().CategoryID;

    &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; books = &lt;span style="color: blue"&gt;this&lt;/span&gt;._domainServiceTestHost.Query(&lt;br /&gt;                                ds =&amp;gt; ds.GetBooksForCategory(categoryId));

    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(books.OrderBy(b =&amp;gt; b.BookID).SequenceEqual(books),
      &lt;span style="color: #a31515"&gt;&amp;quot;Operation should return books ordered by BookID&amp;quot;&lt;/span&gt;);
  }&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
  [&lt;span style="color: #2b91af"&gt;Description&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Tests that the InsertBook operation inserts a new book&amp;quot;&lt;/span&gt;)]
&lt;span style="color: blue"&gt;  public void &lt;/span&gt;InsertBook_InsertsNewBook()
  {
    &lt;span style="color: blue"&gt;int &lt;/span&gt;categoryId = &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository.GetTable&amp;lt;&lt;span style="color: #2b91af"&gt;Category&lt;/span&gt;&amp;gt;().&lt;br /&gt;                       First().CategoryID;

    &lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Book
    &lt;/span&gt;{
      ASIN = &lt;span style="color: #a31515"&gt;&amp;quot;1234567890&amp;quot;&lt;/span&gt;,
      Author = &lt;span style="color: #a31515"&gt;&amp;quot;Author&amp;quot;&lt;/span&gt;,
      CategoryID = categoryId,
      Description = &lt;span style="color: #a31515"&gt;&amp;quot;Description&amp;quot;&lt;/span&gt;,
      PublishDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.UtcNow.Subtract(&lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt;.FromDays(1)),
      Title = &lt;span style="color: #a31515"&gt;&amp;quot;Title&amp;quot;&lt;/span&gt;,
    };

    &lt;span style="color: blue"&gt;this&lt;/span&gt;._domainServiceTestHost.Insert(book);

    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(book.BookID &amp;gt; 0,
      &lt;span style="color: #a31515"&gt;&amp;quot;New book should have a valid BookID&amp;quot;&lt;/span&gt;);

    &lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;addedBook = &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository.GetEntities().&lt;br /&gt;                       Single(b =&amp;gt; b.BookID == book.BookID);

    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsNotNull(addedBook,
      &lt;span style="color: #a31515"&gt;&amp;quot;Operation should insert book&amp;quot;&lt;/span&gt;);
  }&lt;/pre&gt;

&lt;p&gt;To rephrase what I said above, calling &lt;strong&gt;Insert &lt;/strong&gt;on the test host with a &lt;strong&gt;Book &lt;/strong&gt;calls into our DomainService operation, &lt;strong&gt;InsertBook&lt;/strong&gt;. As you can see, at the end of this test our new book has been added to the repository.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  this&lt;/span&gt;._domainServiceTestHost.Update(&lt;br /&gt;    ds =&amp;gt; ds.AddNewEdition(book), original);&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;  DateTime &lt;/span&gt;result = &lt;span style="color: blue"&gt;this&lt;/span&gt;._domainServiceTestHost.Invoke(&lt;br /&gt;    ds =&amp;gt; ds.GetLatestActivity());&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;AddNewEdition&lt;/strong&gt; updates the book and runs custom business logic and &lt;strong&gt;GetLatestActivity &lt;/strong&gt;returns a &lt;strong&gt;DateTime &lt;/strong&gt;related to the newest book. Again, the ‘ds’ parameter in the lambda expression refers to the DomainService being tested.&lt;/p&gt;

&lt;h1&gt;Testing Validation and Authorization&lt;/h1&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Validation is fairly straightforward to test. Instead of using the test host methods I’ve already described, you should use their &lt;strong&gt;TryXx &lt;/strong&gt;variants.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
  [&lt;span style="color: #2b91af"&gt;Description&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Tests that the UpdateBook operation returns &lt;br /&gt;     validation errors when passed an invalid book&amp;quot;&lt;/span&gt;)]
&lt;span style="color: blue"&gt;  public void &lt;/span&gt;UpdateBook_SetsValidationErrors()
  {
    &lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;original = &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository.GetEntities().First();
    &lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Book
    &lt;/span&gt;{
      AddedDate = original.AddedDate,
      ASIN = &lt;span style="color: #a31515"&gt;&amp;quot;Invalid!&amp;quot;&lt;/span&gt;,
      Author = original.Author,
      BookID = original.BookID,
      Category = original.Category,
      CategoryID = original.CategoryID,
      Description = original.Description,
      PublishDate = original.PublishDate,
      Title = original.Title,
    };

    &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ValidationResult&lt;/span&gt;&amp;gt; validationErrors;
    &lt;span style="color: blue"&gt;bool &lt;/span&gt;success = &lt;span style="color: blue"&gt;this&lt;/span&gt;._domainServiceTestHost.TryUpdate(&lt;br /&gt;                     book, original, &lt;span style="color: blue"&gt;out &lt;/span&gt;validationErrors);

    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsFalse(success,
      &lt;span style="color: #a31515"&gt;&amp;quot;Operation should have validation errors&amp;quot;&lt;/span&gt;);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(1, validationErrors.Count,
      &lt;span style="color: #a31515"&gt;&amp;quot;Operation should return validation errors&amp;quot;&lt;/span&gt;);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(validationErrors[0].MemberNames.Single() == &lt;span style="color: #a31515"&gt;&amp;quot;ASIN&amp;quot;&lt;/span&gt;,
      &lt;span style="color: #a31515"&gt;&amp;quot;Operation should return a validation error for 'ASIN'&amp;quot;&lt;/span&gt;);
  }&lt;/pre&gt;

&lt;p&gt;This test calls into &lt;strong&gt;UpdateBook &lt;/strong&gt;with invalid data and then verifies the resulting validation errors are ones we expect.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  this&lt;/span&gt;._domainServiceTestHost = &lt;br /&gt;    &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainServiceTestHost&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;BookClubDomainService&lt;/span&gt;&amp;gt;(&lt;br /&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;.CreateDomainService,&lt;br /&gt;      &lt;span style="color: #2b91af"&gt;BookClubDomainServiceTest&lt;/span&gt;.authenticatedUser);&lt;/pre&gt;

&lt;h1&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;To sum it all up, the &lt;strong&gt;DomainServiceTestHost&lt;/strong&gt; in combination with an &lt;strong&gt;IDomainServiceFactory&lt;/strong&gt; 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.&lt;/p&gt;

&lt;h4&gt;[A Note on the DomainServiceTestHost]&lt;/h4&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h3&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/tags/testing/"&gt;Unit Testing Series&lt;/a&gt;&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory.aspx"&gt;Part 1: The IDomainServiceFactory&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern.aspx"&gt;Part 2: The Repository Pattern&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost.aspx"&gt;Part 3: The DomainServiceTestHost&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/Unit-Testing-a-WCF-RIA-a39a700e"&gt;Unit Testing Sample Source&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://nuget.org/List/Packages/RIAServices.UnitTesting"&gt;NuGet: RIAServices.UnitTesting&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10197364" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Testing" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Testing/" /></entry><entry><title>Unit Testing a WCF RIA DomainService: Part 2, The Repository Pattern</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern.aspx</id><published>2011-08-18T15:10:17Z</published><updated>2011-08-18T15:10:17Z</updated><content type="html">&lt;p&gt;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 &lt;strong&gt;IDomainServiceFactory&lt;/strong&gt; to factor external dependencies out of your code.&amp;#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.&lt;/p&gt;  &lt;p&gt;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 &lt;strong&gt;ObjectContext&lt;/strong&gt;. If you’re using a different data-access technology, feel free to modify this pattern until you get something that works for your scenario.&lt;/p&gt;  &lt;h1&gt;A Repository Sample&lt;/h1&gt;  &lt;p&gt;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 &lt;strong&gt;ObjectContext&lt;/strong&gt;.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: green"&gt;  // Test 1: Operation should return all books
  // Test 2: Operation should return books with categories
  // Test 3: Operation should return books ordered by BookID
&lt;/span&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooks()
  {
    &lt;span style="color: blue"&gt;return this&lt;/span&gt;.ObjectContext.Books.Include(&lt;span style="color: #a31515"&gt;&amp;quot;Category&amp;quot;&lt;/span&gt;).&lt;br /&gt;             OrderBy(b =&amp;gt; b.BookID);
  }

&lt;span style="color: green"&gt;  // Test 1: Operation should return all books for category
  // Test 2: Operation should return books ordered by BookID
&lt;/span&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooksForCategory(&lt;span style="color: blue"&gt;int &lt;/span&gt;categoryId)
  {
    &lt;span style="color: blue"&gt;return this&lt;/span&gt;.ObjectContext.Books.&lt;br /&gt;             Where(b =&amp;gt; b.CategoryID == categoryId).OrderBy(b =&amp;gt; b.BookID);
  }

&lt;span style="color: green"&gt;  // Test 1: Operation should update book
  // Test 2: Operation should return validation errors
&lt;/span&gt;&lt;span style="color: blue"&gt;  public void &lt;/span&gt;UpdateBook(&lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book)
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.ObjectContext.Books.AttachAsModified(&lt;br /&gt;      book, &lt;span style="color: blue"&gt;this&lt;/span&gt;.ChangeSet.GetOriginal(book));
  }&lt;/pre&gt;

&lt;p&gt;Upon introducing a repository into this code, the operations will be slightly different.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;  // Test 1: Operation should return all books
  // Test 2: Operation should return books with categories
  // Test 3: Operation should return books ordered by BookID
&lt;/span&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooks()
  {
    &lt;span style="color: blue"&gt;return this&lt;/span&gt;._bookRepository.GetBooksWithCategories().&lt;br /&gt;             OrderBy(b =&amp;gt; b.BookID);
  }

&lt;span style="color: green"&gt;  // Test 1: Operation should return all books for category
  // Test 2: Operation should return books ordered by BookID
&lt;/span&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooksForCategory(&lt;span style="color: blue"&gt;int &lt;/span&gt;categoryId)
  {
    &lt;span style="color: blue"&gt;return this&lt;/span&gt;._bookRepository.GetEntities().&lt;br /&gt;             Where(b =&amp;gt; b.CategoryID == categoryId).OrderBy(b =&amp;gt; b.BookID);
  }

&lt;span style="color: green"&gt;  // Test 1: Operation should update book
  // Test 2: Operation should return validation errors
&lt;/span&gt;&lt;span style="color: blue"&gt;  public void &lt;/span&gt;UpdateBook(&lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book)
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository.Update(&lt;br /&gt;      book, &lt;span style="color: blue"&gt;this&lt;/span&gt;.ChangeSet.GetOriginal(book));
  }&lt;/pre&gt;

&lt;p&gt;By-and-large we’ve preserved the existing implementation. However, you can now see we don’t have a direct dependency on &lt;strong&gt;ObjectContext&lt;/strong&gt;. 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.&lt;/p&gt;

&lt;h1&gt;The Repository API&lt;/h1&gt;

&lt;p&gt;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 &lt;strong&gt;IRepository&amp;lt;T&amp;gt;&lt;/strong&gt; interface.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IRepository&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: #2b91af"&gt;IRepository
&lt;/span&gt;  {
    &lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;T&amp;gt; GetEntities();
    &lt;span style="color: blue"&gt;void &lt;/span&gt;Insert(T entity);
    &lt;span style="color: blue"&gt;void &lt;/span&gt;Update(T entity, T original);
    &lt;span style="color: blue"&gt;void &lt;/span&gt;Delete(T entity);
  }&lt;/pre&gt;

&lt;p&gt;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).&lt;/p&gt;

&lt;p&gt;Here’s a partial Repository implementation using Entity Framework.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Repository&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: #2b91af"&gt;IRepository&lt;/span&gt;&amp;lt;T&amp;gt; &lt;span style="color: blue"&gt;where &lt;/span&gt;T : &lt;span style="color: #2b91af"&gt;EntityObject
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public virtual &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;T&amp;gt; GetEntities()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.ObjectSet;
    }

    &lt;span style="color: blue"&gt;public virtual void &lt;/span&gt;Insert(T entity)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(entity.EntityState != &lt;span style="color: #2b91af"&gt;EntityState&lt;/span&gt;.Detached)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.ObjectContext.ObjectStateManager.&lt;br /&gt;          ChangeObjectState(entity, &lt;span style="color: #2b91af"&gt;EntityState&lt;/span&gt;.Added);
      }
      &lt;span style="color: blue"&gt;else
      &lt;/span&gt;{
          &lt;span style="color: blue"&gt;this&lt;/span&gt;.ObjectSet.AddObject(entity);
      }
    }
  }&lt;/pre&gt;

&lt;p&gt;As you can see, the repository contains the familiar code required to work against the EF &lt;strong&gt;ObjectContext &lt;/strong&gt;and &lt;strong&gt;ObjectSet&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;The next class to look at is a derived repository interface. As you may have noticed already, our book repository has a &lt;strong&gt;GetBooksWithCategories &lt;/strong&gt;method that isn’t in the base interface.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IBookRepository &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IRepository&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;
  {
    &lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooksWithCategories();
  }&lt;/pre&gt;

&lt;p&gt;The concrete implementation of this method will show us why it’s interesting.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookRepository &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;Repository&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;, &lt;span style="color: #2b91af"&gt;IBookRepository
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;BookRepository(&lt;span style="color: #2b91af"&gt;BookClubEntities &lt;/span&gt;objectContext)
        : &lt;span style="color: blue"&gt;base&lt;/span&gt;(objectContext)
    {
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooksWithCategories()
    {
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;.ObjectSet.Include(&lt;span style="color: #a31515"&gt;&amp;quot;Category&amp;quot;&lt;/span&gt;);
    }
  }&lt;/pre&gt;

&lt;p&gt;Specifically, we’ve used the &lt;strong&gt;Include &lt;/strong&gt;method on &lt;strong&gt;ObjectSet&lt;/strong&gt;. Since the include method is specific to entity framework, I’ve placed it behind the repository interface.&lt;/p&gt;

&lt;h1&gt;The UnitOfWork API&lt;/h1&gt;

&lt;p&gt;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 &lt;strong&gt;IUnitOfWork &lt;/strong&gt;interface.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IUnitOfWork
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;void &lt;/span&gt;Save();
  }&lt;/pre&gt;

&lt;p&gt;Simple. Now we just need to make sure it is called when our DomainService is ready to persist changes. Luckily, the &lt;strong&gt;DomainService &lt;/strong&gt;base class provides a virtual protected method to allow us to do just that.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;  // Test 1: Unit of work should be saved
&lt;/span&gt;&lt;span style="color: blue"&gt;  protected override bool &lt;/span&gt;PersistChangeSet()
  {
&lt;span style="color: green"&gt;    &lt;/span&gt;&lt;span style="color: blue"&gt;this&lt;/span&gt;.UnitOfWork.Save();
    &lt;span style="color: blue"&gt;return true&lt;/span&gt;;
  }&lt;/pre&gt;

&lt;p&gt;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 &lt;strong&gt;BookClubEntities&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public partial class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubEntities &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IUnitOfWork
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Save()
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.SaveChanges();
    }
  }&lt;/pre&gt;

&lt;p&gt;Now we’ll need to take a look at how all these pieces are wired up.&lt;/p&gt;

&lt;h1&gt;A DomainService Using a Repository&lt;/h1&gt;

&lt;p&gt;Like I showed in my previous post, we’ll need to pass the repository to the DomainService’s constructor.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;BookClubDomainService(
&lt;span style="color: #2b91af"&gt;    IUnitOfWork &lt;/span&gt;unitOfWork,&lt;br /&gt;    &lt;span style="color: #2b91af"&gt;IBookRepository &lt;/span&gt;bookRepository,
    &lt;span style="color: #2b91af"&gt;ILibraryService &lt;/span&gt;libraryService,
    &lt;span style="color: #2b91af"&gt;IApprovalSystem &lt;/span&gt;approvalSystem)
    : &lt;span style="color: blue"&gt;base&lt;/span&gt;(unitOfWork, bookRepository) &lt;br /&gt;  {
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(bookRepository == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
    {
      &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;bookRepository&amp;quot;&lt;/span&gt;);
    }
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(libraryService == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
    {
      &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;libraryService&amp;quot;&lt;/span&gt;);
    }
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(approvalSystem == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
    {
      &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;approvalSystem&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;this&lt;/span&gt;._bookRepository = bookRepository;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._libraryService = libraryService;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._approvalSystem = approvalSystem;
  }&lt;/pre&gt;

&lt;p&gt;You can refer back to my previous post on how to create and bootstrap an &lt;strong&gt;IDomainServiceFactory&lt;/strong&gt;. I won’t repeat the information here, but I’ll give you a quick look at the factory code that creates the DomainService.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainServiceFactory &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IDomainServiceFactory
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainService &lt;/span&gt;CreateDomainService(&lt;br /&gt;      &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;domainServiceType, &lt;span style="color: #2b91af"&gt;DomainServiceContext &lt;/span&gt;context)
    {
      &lt;span style="color: #2b91af"&gt;DomainService &lt;/span&gt;domainService;
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;BookClubDomainService&lt;/span&gt;) == domainServiceType)
      {
        &lt;span style="color: #2b91af"&gt;BookClubEntities &lt;/span&gt;bookClubEntities = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubEntities&lt;/span&gt;();
        domainService = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainService&lt;/span&gt;(
          bookClubEntities,
&lt;span style="color: blue"&gt;          new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookRepository&lt;/span&gt;(bookClubEntities), &lt;br /&gt;          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LibraryService&lt;/span&gt;(),
          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ApprovalSystem&lt;/span&gt;());
      }
      &lt;span style="color: blue"&gt;else
      &lt;/span&gt;{
        domainService = (&lt;span style="color: #2b91af"&gt;DomainService&lt;/span&gt;)&lt;br /&gt;          &lt;span style="color: #2b91af"&gt;Activator&lt;/span&gt;.CreateInstance(domainServiceType);
      }

      domainService.Initialize(context);
      &lt;span style="color: blue"&gt;return &lt;/span&gt;domainService;
    }
  }&lt;/pre&gt;

&lt;p&gt;Finally, we need to set the &lt;strong&gt;BookClubDomainService&lt;/strong&gt;&amp;#160; to provide the correct metadata about the types it supports. Since we’re returning Entity Framework types, we’ll need to use the &lt;strong&gt;LinqToEntitiesDomainServiceDescriptionProviderAttribute&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;LinqToEntitiesDomainServiceDescriptionProvider&lt;/span&gt;(&lt;br /&gt;     &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;BookClubEntities&lt;/span&gt;))]
&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;RepositoryDomainService &lt;/span&gt;{ ... }&lt;/pre&gt;

&lt;p&gt;Also, you’ll notice I’ve created a &lt;strong&gt;RepositoryDomainService&lt;/strong&gt; base class to encapsulate some of the common Repository concerns. With all these pieces together, it becomes a simple matter to write DomainService operations.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;  // Test 1: Operation should return all books
  // Test 2: Operation should return books with categories
  // Test 3: Operation should return books ordered by BookID
&lt;/span&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooks()
  {
    &lt;span style="color: blue"&gt;return this&lt;/span&gt;._bookRepository.GetBooksWithCategories().&lt;br /&gt;             OrderBy(b =&amp;gt; b.BookID);
  }&lt;/pre&gt;

&lt;h1&gt;Testing With a Repository&lt;/h1&gt;

&lt;p&gt;Though I plan to save most of this for the next post, it’s worth looking at the &lt;strong&gt;MockRespository &lt;/strong&gt;we’ll use for testing.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: #2b91af"&gt;IRepository&lt;/span&gt;&amp;lt;T&amp;gt;
  {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;gt; _entities =&lt;br /&gt;      &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;gt;();

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;TEntity&amp;gt; GetTable&amp;lt;TEntity&amp;gt;() { ... }

    &lt;span style="color: blue"&gt;public virtual &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;T&amp;gt; GetEntities()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.GetTable&amp;lt;T&amp;gt;().AsQueryable();
    }

    &lt;span style="color: blue"&gt;public virtual void &lt;/span&gt;Insert(T entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.GetTable&amp;lt;T&amp;gt;().Add(entity);
    }
  }&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MockBookRepository &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;, &lt;span style="color: #2b91af"&gt;IBookRepository
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;MockBookRepository()
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.GetTable&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;().AddRange(&lt;span style="color: blue"&gt;new &lt;/span&gt;[]
      {
        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Book
        &lt;/span&gt;{
          AddedDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.UtcNow,
          ASIN = &lt;span style="color: #a31515"&gt;&amp;quot;1234567890&amp;quot;&lt;/span&gt;,
          Author = &lt;span style="color: #a31515"&gt;&amp;quot;Author&amp;quot;&lt;/span&gt;,
          BookID = 1,
          ...&lt;br /&gt;        },&lt;br /&gt;        ...
      });
    }
  }&lt;/pre&gt;

&lt;p&gt;Now, when we create our DomainService in our tests, we can pass an instance of &lt;strong&gt;MockBookRepository&lt;/strong&gt; 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.&lt;/p&gt;

&lt;h3&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/tags/testing/"&gt;Unit Testing Series&lt;/a&gt;&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory.aspx"&gt;Part 1: The IDomainServiceFactory&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern.aspx"&gt;Part 2: The Repository Pattern&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost.aspx"&gt;Part 3: The DomainServiceTestHost&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/Unit-Testing-a-WCF-RIA-a39a700e"&gt;Unit Testing Sample Source&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://nuget.org/List/Packages/RIAServices.UnitTesting"&gt;NuGet: RIAServices.UnitTesting&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10197363" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Testing" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Testing/" /></entry><entry><title>Unit Testing a WCF RIA DomainService: Part 1, The IDomainServiceFactory</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory.aspx</id><published>2011-08-18T15:06:00Z</published><updated>2011-08-18T15:06:00Z</updated><content type="html">&lt;p&gt;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?).&lt;/p&gt;  &lt;p&gt;The first step to making your DomainService testable is to identify the external dependencies. &lt;/p&gt;  &lt;h1&gt;A DomainService with Dependencies&lt;/h1&gt;  &lt;p&gt;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.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainService &lt;/span&gt;:&lt;br /&gt;    &lt;span style="color: #2b91af"&gt;LinqToEntitiesDomainService&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;BookClubEntities&lt;/span&gt;&amp;gt;
  {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LibraryService &lt;/span&gt;_libraryService = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LibraryService&lt;/span&gt;();
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ApprovalSystem &lt;/span&gt;_approvalSystem = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ApprovalSystem&lt;/span&gt;();

    &lt;span style="color: green"&gt;// Test 1: Operation should return all books
    // Test 2: Operation should return books with categories
    // Test 3: Operation should return books ordered by BookID
    &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooks()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.ObjectContext.Books.Include(&lt;span style="color: #a31515"&gt;&amp;quot;Category&amp;quot;&lt;/span&gt;).&lt;br /&gt;               OrderBy(b =&amp;gt; b.BookID);
    }

    &lt;span style="color: green"&gt;// 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
    &lt;/span&gt;&lt;span style="color: blue"&gt;public void &lt;/span&gt;InsertBook(&lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;((book.EntityState != &lt;span style="color: #2b91af"&gt;EntityState&lt;/span&gt;.Detached))
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.ObjectContext.ObjectStateManager.&lt;br /&gt;          ChangeObjectState(book, &lt;span style="color: #2b91af"&gt;EntityState&lt;/span&gt;.Added);
      }
      &lt;span style="color: blue"&gt;else
      &lt;/span&gt;{
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.ObjectContext.Books.AddObject(book);
      }

      book.AddedDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.UtcNow;

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(!&lt;span style="color: blue"&gt;this&lt;/span&gt;._libraryService.IsAsinValid(book.ASIN))
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._approvalSystem.&lt;br /&gt;          RequestApproval(book.Author, book.Title, book.PublishDate);
      }
      &lt;span style="color: blue"&gt;else if &lt;/span&gt;(book.PublishDate &amp;gt; book.AddedDate)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._approvalSystem.RequestApproval(book.ASIN);
      }
    }
  }&lt;/pre&gt;

&lt;p&gt;A quick look at this service should reveal three concrete dependencies. First, we’re using an Entity Framework &lt;strong&gt;ObjectContext &lt;/strong&gt;to talk to a database. We also have a dependency on an external service, &lt;strong&gt;LibraryService&lt;/strong&gt;, and an internal subsystem, &lt;strong&gt;ApprovalSystem&lt;/strong&gt;. The &lt;strong&gt;ObjectContext &lt;/strong&gt;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 &lt;strong&gt;LibraryService &lt;/strong&gt;and &lt;strong&gt;ApprovalSystem&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;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 &lt;strong&gt;LibraryService.IsAsinValid&lt;/strong&gt; to use only with your tests. I’ve been using &lt;a href="http://research.microsoft.com/en-us/projects/pex/"&gt;Moles&lt;/a&gt; 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.&lt;/p&gt;

&lt;p&gt;The rest of this post will cover how to use the &lt;strong&gt;IDomainServiceFactory&lt;/strong&gt; 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.&lt;/p&gt;

&lt;h1&gt;Factoring External Dependencies&lt;/h1&gt;

&lt;p&gt;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, &lt;strong&gt;LibraryService &lt;/strong&gt;and &lt;strong&gt;ApprovalSystem&lt;/strong&gt;, we’ll replace them with interfaces.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ILibraryService
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;bool &lt;/span&gt;IsAsinValid(&lt;span style="color: blue"&gt;string &lt;/span&gt;asin);
  }&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IApprovalSystem
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;void &lt;/span&gt;RequestApproval(&lt;span style="color: blue"&gt;string &lt;/span&gt;author, &lt;span style="color: blue"&gt;string &lt;/span&gt;title, &lt;span style="color: #2b91af"&gt;DateTime &lt;/span&gt;publishDate);
    &lt;span style="color: blue"&gt;void &lt;/span&gt;RequestApproval(&lt;span style="color: blue"&gt;string &lt;/span&gt;asin);
  }&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainService &lt;/span&gt;:&lt;br /&gt;    &lt;span style="color: #2b91af"&gt;LinqToEntitiesDomainService&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;BookClubEntities&lt;/span&gt;&amp;gt;
  {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ILibraryService &lt;/span&gt;_libraryService;
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IApprovalSystem &lt;/span&gt;_approvalSystem;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;BookClubDomainService(&lt;br /&gt;      &lt;span style="color: #2b91af"&gt;ILibraryService &lt;/span&gt;libraryService, &lt;span style="color: #2b91af"&gt;IApprovalSystem &lt;/span&gt;approvalSystem)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(libraryService == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;libraryService&amp;quot;&lt;/span&gt;);
      }
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(approvalSystem == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;approvalSystem&amp;quot;&lt;/span&gt;);
      }

      &lt;span style="color: blue"&gt;this&lt;/span&gt;._libraryService = libraryService;
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._approvalSystem = approvalSystem;
    }

    &lt;span style="color: green"&gt;// Test 1: Operation should return all books
    // Test 2: Operation should return books with categories
    // Test 3: Operation should return books ordered by BookID
    &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; GetBooks()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.ObjectContext.Books.Include(&lt;span style="color: #a31515"&gt;&amp;quot;Category&amp;quot;&lt;/span&gt;).&lt;br /&gt;               OrderBy(b =&amp;gt; b.BookID);
    }

    &lt;span style="color: green"&gt;// 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
    &lt;/span&gt;&lt;span style="color: blue"&gt;public void &lt;/span&gt;InsertBook(&lt;span style="color: #2b91af"&gt;Book &lt;/span&gt;book)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;((book.EntityState != &lt;span style="color: #2b91af"&gt;EntityState&lt;/span&gt;.Detached))
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.ObjectContext.ObjectStateManager.&lt;br /&gt;          ChangeObjectState(book, &lt;span style="color: #2b91af"&gt;EntityState&lt;/span&gt;.Added);
      }
      &lt;span style="color: blue"&gt;else
      &lt;/span&gt;{
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.ObjectContext.Books.AddObject(book);
      }

      book.AddedDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.UtcNow;

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(!&lt;span style="color: blue"&gt;this&lt;/span&gt;._libraryService.IsAsinValid(book.ASIN))
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._approvalSystem.&lt;br /&gt;          RequestApproval(book.Author, book.Title, book.PublishDate);
      }
      &lt;span style="color: blue"&gt;else if &lt;/span&gt;(book.PublishDate &amp;gt; book.AddedDate)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._approvalSystem.RequestApproval(book.ASIN);
      }
    }
  }&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h1&gt;IDomainServiceFactory&lt;/h1&gt;

&lt;p&gt;Each time a client calls into the DomainService endpoint, the RIA hosting layer uses the singleton &lt;strong&gt;DomainService.Factory &lt;/strong&gt;to create a new instance of the requested DomainService type. The default &lt;strong&gt;IDomainServiceFactory &lt;/strong&gt;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.&lt;/p&gt;

&lt;p&gt;Factories are pretty straightforward to write and only expose a pair of Create/Release methods.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainServiceFactory &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IDomainServiceFactory
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainService &lt;/span&gt;CreateDomainService(&lt;br /&gt;      &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;domainServiceType, &lt;span style="color: #2b91af"&gt;DomainServiceContext &lt;/span&gt;context)
    {
      &lt;span style="color: #2b91af"&gt;DomainService &lt;/span&gt;domainService;
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;BookClubDomainService&lt;/span&gt;) == domainServiceType)
      {
        domainService = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainService&lt;/span&gt;(&lt;br /&gt;          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LibraryService&lt;/span&gt;(), &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ApprovalSystem&lt;/span&gt;());
      }
      &lt;span style="color: blue"&gt;else
      &lt;/span&gt;{
        domainService = (&lt;span style="color: #2b91af"&gt;DomainService&lt;/span&gt;)&lt;br /&gt;          &lt;span style="color: #2b91af"&gt;Activator&lt;/span&gt;.CreateInstance(domainServiceType);
      }

      domainService.Initialize(context);
      &lt;span style="color: blue"&gt;return &lt;/span&gt;domainService;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;ReleaseDomainService(&lt;span style="color: #2b91af"&gt;DomainService &lt;/span&gt;domainService)
    {
      domainService.Dispose();
    }
  }&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-37-63-metablogapi/3443.image_5F00_5543F4CF.png"&gt;&lt;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="http://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" /&gt;&lt;/a&gt;&amp;#160;&amp;#160; &lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-37-63-metablogapi/7356.image_5F00_3B6FBEA0.png"&gt;&lt;img style="display: inline" title="image" alt="image" src="http://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" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Global &lt;/span&gt;: System.Web.&lt;span style="color: #2b91af"&gt;HttpApplication
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;protected void &lt;/span&gt;Application_Start(&lt;span style="color: blue"&gt;object &lt;/span&gt;sender, &lt;span style="color: #2b91af"&gt;EventArgs &lt;/span&gt;e)
    {
      &lt;span style="color: #2b91af"&gt;DomainService&lt;/span&gt;.Factory = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubDomainServiceFactory&lt;/span&gt;();
    }
  }&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h4&gt;[A Note on Dependency Injection]&lt;/h4&gt;

&lt;p&gt;Often Dependency Injection is done in a more generic fashion using Injection frameworks. If you find yourself creating a big switch in &lt;strong&gt;IDomainServiceFactory.CreateDomainService &lt;/strong&gt;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.&lt;/p&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;h4&gt;[An Alternate Design]&lt;/h4&gt;

&lt;p&gt;Now that you’ve patiently waded through this entire post, it’s worth noting that a custom &lt;strong&gt;IDomainServiceFactory &lt;/strong&gt;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.&lt;/p&gt;

&lt;h3&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/tags/testing/"&gt;Unit Testing Series&lt;/a&gt;&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-1-the-idomainservicefactory.aspx"&gt;Part 1: The IDomainServiceFactory&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-2-the-repository-pattern.aspx"&gt;Part 2: The Repository Pattern&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/08/18/unit-testing-a-wcf-ria-domainservice-part-3-the-domainservicetesthost.aspx"&gt;Part 3: The DomainServiceTestHost&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/Unit-Testing-a-WCF-RIA-a39a700e"&gt;Unit Testing Sample Source&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://nuget.org/List/Packages/RIAServices.UnitTesting"&gt;NuGet: RIAServices.UnitTesting&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10197358" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Testing" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Testing/" /></entry><entry><title>WCF RIA Services in Windows Azure AppFabric June CTP</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/06/24/wcf-ria-services-in-windows-azure-appfabric-june-ctp.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/06/24/wcf-ria-services-in-windows-azure-appfabric-june-ctp.aspx</id><published>2011-06-24T14:06:19Z</published><updated>2011-06-24T14:06:19Z</updated><content type="html">&lt;p&gt;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 &lt;a href="http://blogs.msdn.com/b/appfabric/archive/2011/06/20/announcing-the-windows-azure-appfabric-june-ctp.aspx"&gt;Windows Azure AppFabric June CTP&lt;/a&gt;. 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.&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h1&gt;Links&lt;/h1&gt;  &lt;p&gt;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.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/hh239692.aspx"&gt;Here’s an overview of RIA in AppFabric Applications&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/hh264595.aspx"&gt;Here’s an overview of the Silverlight Business Application Pattern for AppFabric&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d89640fc-c552-446e-aead-b1e0d940f31b&amp;amp;displaylang=en"&gt;You can download the AppFabric Samples for the June CTP here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Also, when you download the CTP, make sure you install the AppFabricVsToolsCtp.&lt;/p&gt;  &lt;h1&gt;Take a Look&lt;/h1&gt;  &lt;p&gt;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.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10178684" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Azure" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Azure/" /><category term="AppFabric" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/AppFabric/" /></entry><entry><title>Writing a Custom CollectionViewLoader for the DomainCollectionView and MVVM</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/05/13/writing-a-custom-collectionviewloader-for-the-domaincollectionview-and-mvvm.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/05/13/writing-a-custom-collectionviewloader-for-the-domaincollectionview-and-mvvm.aspx</id><published>2011-05-13T17:05:30Z</published><updated>2011-05-13T17:05:30Z</updated><content type="html">&lt;p&gt;The question I’ve been fielding most lately is how to write a custom &lt;strong&gt;CollectionViewLoader&lt;/strong&gt;. 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, &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx"&gt;I discussed how the view, loader, and source related to each other&lt;/a&gt;. In this post, I’ll show how that translates to the code you write.&lt;/p&gt;  &lt;h1&gt;The Loader as part of your View Model&lt;/h1&gt;  &lt;p&gt;Out of the three parts of the &lt;strong&gt;DomainCollectionView (DCV) &lt;/strong&gt;triad, the loader is the piece mostly closely aligned with your View Model. In fact, I wrote the default implementation (the &lt;strong&gt;DomainCollectionViewLoader&lt;/strong&gt;) 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 &lt;strong&gt;CollectionViewLoader&lt;/strong&gt; until you find the balance of functionality and reusability you feel comfortable with.&lt;/p&gt;  &lt;h1&gt;The CollectionViewLoader&lt;/h1&gt;  &lt;p&gt;A good place to start is to take a look at public surface area of the &lt;strong&gt;CollectionViewLoader &lt;/strong&gt;type you’ll be extending.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public abstract class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CollectionViewLoader
&lt;/span&gt;  {
&lt;span style="color: gray"&gt;    &lt;/span&gt;&lt;span style="color: blue"&gt;public event &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EventHandler &lt;/span&gt;CanLoadChanged;
&lt;span style="color: gray"&gt;    &lt;/span&gt;&lt;span style="color: blue"&gt;public event &lt;/span&gt;AsyncCompletedEventHandler LoadCompleted;

&lt;span style="color: blue"&gt;    public abstract bool &lt;/span&gt;CanLoad { &lt;span style="color: blue"&gt;get&lt;/span&gt;; }

&lt;span style="color: blue"&gt;    public abstract void &lt;/span&gt;Load(&lt;span style="color: blue"&gt;object &lt;/span&gt;userState);
  }&lt;/pre&gt;

&lt;p&gt;It’s a simple abstract class with one method, one property, and two events. The &lt;strong&gt;Load&lt;/strong&gt; method is responsible for asynchronously loading data into the source collection of the collection view. Since the &lt;strong&gt;Load &lt;/strong&gt;method is asynchronous, it needs to raise a &lt;strong&gt;LoadCompleted &lt;/strong&gt;event when it completes. The &lt;strong&gt;CanLoad &lt;/strong&gt;property tells the &lt;strong&gt;DCV &lt;/strong&gt;whether it can safely invoke the &lt;strong&gt;Load &lt;/strong&gt;method. There are a number of &lt;strong&gt;CanXx &lt;/strong&gt;properties in the &lt;strong&gt;ICollectionView &lt;/strong&gt;interface, and changes to the &lt;strong&gt;CanLoad &lt;/strong&gt;property will propagate to all of them. For example, since re-sorting the &lt;strong&gt;DCV &lt;/strong&gt;will result in a &lt;strong&gt;Load &lt;/strong&gt;call, &lt;strong&gt;CanSort &lt;/strong&gt;will be set to false when &lt;strong&gt;CanLoad &lt;/strong&gt;is false.&lt;/p&gt;

&lt;h1&gt;The Sample&lt;/h1&gt;

&lt;p&gt;I’ve also had a number of questions lately about how to use the &lt;strong&gt;DCV &lt;/strong&gt;with the &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/04/29/mvvm-pattern-for-ria-services.aspx"&gt;MVVM pattern I proposed in a recent post&lt;/a&gt;. This will be a two-birds-with-one-stone sample where I’ll show how to write a custom &lt;strong&gt;CollectionViewLoader &lt;/strong&gt;that works with the MVVM service pattern. It’s worth noting this sample is a variant of the one I published with &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx"&gt;my original DCV post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I’ll start with the custom loader code and work back through the rest of the sample.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleCollectionViewLoader&lt;/span&gt;&amp;lt;TEntity&amp;gt;&lt;br /&gt;    : &lt;span style="color: #2b91af"&gt;CollectionViewLoader &lt;/span&gt;&lt;span style="color: blue"&gt;where &lt;/span&gt;TEntity : &lt;span style="color: #2b91af"&gt;Entity
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;TEntity&amp;gt;&amp;gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; _load;
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; _cancelLoad;
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;TEntity&amp;gt;&amp;gt; _onLoadCompleted;

    &lt;span style="color: blue"&gt;private object &lt;/span&gt;_currentUserState;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;SampleCollectionViewLoader(
        &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;TEntity&amp;gt;&amp;gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; load,
        &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; cancelLoad,
        &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;TEntity&amp;gt;&amp;gt; onLoadCompleted)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(load == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;load&amp;quot;&lt;/span&gt;);
      }
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(onLoadCompleted == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;onLoadCompleted&amp;quot;&lt;/span&gt;);
      }

      &lt;span style="color: blue"&gt;this&lt;/span&gt;._load = load;
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._cancelLoad = cancelLoad;
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._onLoadCompleted = onLoadCompleted;
    }

    &lt;span style="color: blue"&gt;public override bool &lt;/span&gt;CanLoad
    {
      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return true&lt;/span&gt;; }
    }

    &lt;span style="color: blue"&gt;private object &lt;/span&gt;CurrentUserState
    {
      &lt;span style="color: blue"&gt;get
      &lt;/span&gt;{
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;._currentUserState;
      }

      &lt;span style="color: blue"&gt;set
      &lt;/span&gt;{
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;._currentUserState != &lt;span style="color: blue"&gt;value&lt;/span&gt;)
        {
          &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;._cancelLoad != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
          {
            &lt;span style="color: blue"&gt;this&lt;/span&gt;._cancelLoad(&lt;span style="color: blue"&gt;this&lt;/span&gt;._currentUserState);
          }
        }

        &lt;span style="color: blue"&gt;this&lt;/span&gt;._currentUserState = &lt;span style="color: blue"&gt;value&lt;/span&gt;;
      }
    }

    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;Load(&lt;span style="color: blue"&gt;object &lt;/span&gt;userState)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(!&lt;span style="color: blue"&gt;this&lt;/span&gt;.CanLoad)
      {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;InvalidOperationException&lt;/span&gt;(&lt;br /&gt;                    &lt;span style="color: #a31515"&gt;&amp;quot;Load cannot be called when CanLoad is false&amp;quot;&lt;/span&gt;);
      }
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.CurrentUserState = userState;
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._load(&lt;span style="color: blue"&gt;this&lt;/span&gt;.OnLoadCompleted, userState);
    }

    &lt;span style="color: blue"&gt;private void &lt;/span&gt;OnLoadCompleted(&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;TEntity&amp;gt; result)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._onLoadCompleted(result);

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;.CurrentUserState == result.UserState)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.CurrentUserState = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
      }

      &lt;span style="color: blue"&gt;base&lt;/span&gt;.OnLoadCompleted(result);
    }
  }&lt;/pre&gt;

&lt;p&gt;This custom &lt;strong&gt;CollectionViewLoader &lt;/strong&gt;in this sample is pretty straightforward and follows the pattern used in the &lt;strong&gt;DomainCollectionViewLoader &lt;/strong&gt;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 &lt;strong&gt;DomainCollectionViewLoader&lt;/strong&gt;. This is necessary to work with the service layer in a natural way which I’ll explain more in the next section.&lt;/p&gt;

&lt;p&gt;There are a couple more things to note about this implementation. First, I haven’t done anything with the &lt;strong&gt;CanLoad &lt;/strong&gt;property. In the sample I include a &lt;strong&gt;IsGridEnabled &lt;/strong&gt;flag in the &lt;strong&gt;SampleViewModel &lt;/strong&gt;that serves roughly the same purpose (and behaves a little nicer from a UI perspective when using the standard Silverlight &lt;strong&gt;DataGrid&lt;/strong&gt;). 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.&lt;/p&gt;

&lt;p&gt;The next part of the sample to look at is the service interface. It’s pretty simple and encapsulates loading sample entities.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ISampleService
&lt;/span&gt;  {
    &lt;span style="color: #2b91af"&gt;EntityContainer &lt;/span&gt;EntityContainer { &lt;span style="color: blue"&gt;get&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;void &lt;/span&gt;LoadSampleEntities(
      &lt;span style="color: #2b91af"&gt;QueryBuilder&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; query,
      &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;&amp;gt; callback,
      &lt;span style="color: blue"&gt;object &lt;/span&gt;state);
  }&lt;/pre&gt;


&lt;p&gt;Next, we’ll take a look at the view model. It’s going to be the place where the &lt;strong&gt;SampleCollectionViewLoader&lt;/strong&gt;, the &lt;strong&gt;SampleService&lt;/strong&gt;, and all the callbacks are tied together.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;SampleViewModel()
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._source = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(&lt;br /&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;._service.EntityContainer.GetEntitySet&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;());&lt;br /&gt;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._loader = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleCollectionViewLoader&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.LoadSampleEntities,
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.CancelLoadSampleEntities,
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.OnLoadSampleEntitiesCompleted);&lt;br /&gt;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._view = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainCollectionView&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(&lt;br /&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;._loader,&lt;br /&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;._source);

&lt;span style="color: blue"&gt;    &lt;/span&gt;&lt;span style="color: green"&gt;// Go back to the first page when the sorting changes
    &lt;/span&gt;&lt;span style="color: #2b91af"&gt;INotifyCollectionChanged &lt;/span&gt;notifyingSortDescriptions = 
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.CollectionView.SortDescriptions;
    notifyingSortDescriptions.CollectionChanged +=
      (sender, e) =&amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.MoveToFirstPage();

    &lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;.CollectionView.DeferRefresh())
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.PageSize = 10;
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.MoveToFirstPage();
    }
  }&lt;/pre&gt;


&lt;p&gt;The source is created using an &lt;strong&gt;EntitySet &lt;/strong&gt;provided by the &lt;strong&gt;EntityContainer &lt;/strong&gt;in the &lt;strong&gt;ISampleService&lt;/strong&gt;. The loader now creates a &lt;strong&gt;SampleCollectionViewLoader &lt;/strong&gt;and passes in three view model callbacks. We’ll take a look at two of those callbacks next.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private void &lt;/span&gt;LoadSampleEntities(&lt;br /&gt;    &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;&amp;gt; onLoadCompleted,&lt;br /&gt;    &lt;span style="color: blue"&gt;object &lt;/span&gt;userState)
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.IsGridEnabled = &lt;span style="color: blue"&gt;false&lt;/span&gt;;

    &lt;span style="color: blue"&gt;this&lt;/span&gt;._service.LoadSampleEntities(
      &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;QueryBuilder&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;().SortAndPageBy(&lt;span style="color: blue"&gt;this&lt;/span&gt;._view),
      onLoadCompleted,
      userState);
  }

&lt;span style="color: blue"&gt;  private void &lt;/span&gt;OnLoadSampleEntitiesCompleted(&lt;br /&gt;    &lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; result)
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.IsGridEnabled = &lt;span style="color: blue"&gt;true&lt;/span&gt;;

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(result.Error != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
    {
      &lt;span style="color: green"&gt;// &lt;/span&gt;&lt;span style="color: #00008b"&gt;TODO: handle errors
    &lt;/span&gt;}
    &lt;span style="color: blue"&gt;else if &lt;/span&gt;(!result.Cancelled)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._source.Source = result.Entities;

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(result.TotalEntityCount != -1)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.SetTotalItemCount(result.TotalEntityCount);
      }
    }
  }&lt;/pre&gt;


&lt;p&gt;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 &lt;strong&gt;LoadSampleEntities &lt;/strong&gt;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.&lt;/p&gt;

&lt;h1&gt;A Note on Cancellation&lt;/h1&gt;

&lt;p&gt;Cancellation is a tricky subject on its own, but I’ll try to address how it fits into this pattern. Since a &lt;strong&gt;CollectionViewLoader &lt;/strong&gt;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 &lt;strong&gt;CancelLoadXx(object userState)&lt;/strong&gt;. You can then invoke this from the cancel callback you pass to the loader.&lt;/p&gt;

&lt;h1&gt;Summary&lt;/h1&gt;

&lt;p&gt;Like I mentioned at the beginning of this post, I expect you to write custom &lt;strong&gt;CollectionViewLoaders &lt;/strong&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;a title="http://code.msdn.microsoft.com/Writing-a-Custom-e0769d37" href="http://code.msdn.microsoft.com/Writing-a-Custom-e0769d37"&gt;http://code.msdn.microsoft.com/Writing-a-Custom-e0769d37&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10164286" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="MVVM" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/MVVM/" /><category term="CollectionView" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/CollectionView/" /></entry><entry><title>Survey: How Do You Use the DomainService Wizard?</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/05/05/survey-how-do-you-use-the-domainservice-wizard.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/05/05/survey-how-do-you-use-the-domainservice-wizard.aspx</id><published>2011-05-05T15:27:20Z</published><updated>2011-05-05T15:27:20Z</updated><content type="html">&lt;p&gt;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.”&lt;/p&gt;  &lt;p&gt;So my question is this: “What problem are you solving?”&lt;/p&gt;  &lt;p&gt;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).&lt;/p&gt;  &lt;p&gt;Feel free to add a short comment with your thoughts or &lt;a href="http://blogs.msdn.com/b/kylemc/contact.aspx"&gt;email me directly&lt;/a&gt;. Thanks.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10161411" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /></entry><entry><title>MVVM Pattern for RIA Services</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/04/29/mvvm-pattern-for-ria-services.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/04/29/mvvm-pattern-for-ria-services.aspx</id><published>2011-04-29T16:06:06Z</published><updated>2011-04-29T16:06:06Z</updated><content type="html">&lt;p&gt;At the &lt;a href="http://www.silverlight.net/news/events/firestarter/"&gt;Silverlight Firestarter ‘10&lt;/a&gt;, John Papa did a great talk on &lt;a href="http://channel9.msdn.com/Series/Silverlight-Firestarter/Silverlight-Firestarter-2010-Session-4-MVVM-Why-and-How-Tips-and-Patterns-using-MVVM-and-Service-Pat"&gt;MVVM Patterns for Silverlight and WP7&lt;/a&gt; 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 &lt;a href="http://jeffhandley.com/archive/2011/04/13/MIX11Releases.aspx"&gt;Mix ‘11&lt;/a&gt; and the result is the new &lt;strong&gt;QueryBuilder&lt;/strong&gt; type we shipped in the &lt;a href="http://jeffhandley.com/archive/2011/04/13/MIX11Releases.aspx"&gt;RIA Toolkit&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;I’ve put together &lt;a href="http://code.msdn.microsoft.com/MVVM-Sample-for-WCF-RIA-115b1f38"&gt;a reworked version of John’s BookShelf sample to highlight the changes&lt;/a&gt;.&lt;/p&gt;  &lt;h1&gt;The BookShelf Sample&lt;/h1&gt;  &lt;p&gt;The primary type we’re interested in here is the &lt;strong&gt;IBookDataService&lt;/strong&gt;. 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).&lt;/p&gt;  &lt;p&gt;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.&lt;/p&gt;  &lt;h2&gt;IBookDataService&lt;/h2&gt;  &lt;p&gt;Since the changes to the service interface drive the changes elsewhere, we should start by looking at the &lt;strong&gt;IBookDataService&lt;/strong&gt;.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IBookDataService
&lt;/span&gt;  {
    &lt;span style="color: #2b91af"&gt;EntityContainer &lt;/span&gt;EntityContainer { &lt;span style="color: blue"&gt;get&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;void &lt;/span&gt;SubmitChanges(&lt;br /&gt;           &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceSubmitChangesResult&lt;/span&gt;&amp;gt; callback,&lt;br /&gt;           &lt;span style="color: blue"&gt;object &lt;/span&gt;state);

    &lt;span style="color: blue"&gt;void &lt;/span&gt;LoadBooksByCategory(&lt;br /&gt;           &lt;span style="color: blue"&gt;int &lt;/span&gt;categoryId,&lt;br /&gt;           &lt;span style="color: #2b91af"&gt;QueryBuilder&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; query,&lt;br /&gt;           &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;&amp;gt; callback,&lt;br /&gt;           &lt;span style="color: blue"&gt;object &lt;/span&gt;state);
    &lt;span style="color: blue"&gt;void &lt;/span&gt;LoadBooksOfTheDay(&lt;br /&gt;           &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;BookOfDay&lt;/span&gt;&amp;gt;&amp;gt; callback,&lt;br /&gt;           &lt;span style="color: blue"&gt;object &lt;/span&gt;state);
    &lt;span style="color: blue"&gt;void &lt;/span&gt;LoadCategories(&lt;br /&gt;           &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Category&lt;/span&gt;&amp;gt;&amp;gt; callback,&lt;br /&gt;           &lt;span style="color: blue"&gt;object &lt;/span&gt;state);
    &lt;span style="color: blue"&gt;void &lt;/span&gt;LoadCheckouts(&lt;br /&gt;           &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Checkout&lt;/span&gt;&amp;gt;&amp;gt; callback,&lt;br /&gt;           &lt;span style="color: blue"&gt;object &lt;/span&gt;state);
  }&lt;/pre&gt;

&lt;p&gt;There are a few things worth noting. First, the &lt;strong&gt;EntityContainer &lt;/strong&gt;is available as part of the interface. If you aren’t familiar with it, the &lt;strong&gt;EntityContainer&lt;/strong&gt; is the type the &lt;strong&gt;DomainContext &lt;/strong&gt;uses to store &lt;strong&gt;EntitySets&lt;/strong&gt;, implement change tracking, and compose change sets. Luckily, the &lt;strong&gt;EntityContainer&lt;/strong&gt; 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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Finally, the &lt;strong&gt;LoadBooksByCategory &lt;/strong&gt;method takes both the &lt;strong&gt;categoryId&lt;/strong&gt; and a &lt;strong&gt;QueryBuilder &lt;/strong&gt;as &lt;sub&gt;&lt;/sub&gt;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.).&lt;/p&gt;

&lt;h2&gt;DesignBookDataService&lt;/h2&gt;

&lt;p&gt;The design-time service implementation is simple and closely resembles the original version.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DesignBookDataService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IBookDataService
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityContainer &lt;/span&gt;_entityContainer =&lt;br /&gt;      &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubContext&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;BookClubContextEntityContainer&lt;/span&gt;();

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityContainer &lt;/span&gt;EntityContainer
    {
      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return this&lt;/span&gt;._entityContainer; }
    }

    ...&lt;/pre&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;public void &lt;/span&gt;LoadBooksByCategory(&lt;br /&gt;                  &lt;span style="color: blue"&gt;int &lt;/span&gt;categoryId,&lt;br /&gt;                  &lt;span style="color: #2b91af"&gt;QueryBuilder&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; query,&lt;br /&gt;                  &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;&amp;gt; callback,&lt;br /&gt;                  &lt;span style="color: blue"&gt;object &lt;/span&gt;state)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.Load(query.ApplyTo(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DesignBooks&lt;/span&gt;()), callback, state);
    }

    ...&lt;/pre&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;private void &lt;/span&gt;Load&amp;lt;T&amp;gt;(&lt;br /&gt;                   &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; entities,&lt;br /&gt;                   &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; callback,&lt;br /&gt;                   &lt;span style="color: blue"&gt;object &lt;/span&gt;state)&lt;br /&gt;                 &lt;span style="color: blue"&gt;where &lt;/span&gt;T : &lt;span style="color: #2b91af"&gt;Entity
    &lt;/span&gt;{
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContainer.LoadEntities(entities);
      callback(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;T&amp;gt;(entities, state));
    }
  }&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;EntityContainer &lt;/strong&gt;is the same internal type as the one use in the &lt;strong&gt;BookClubContext&lt;/strong&gt;, but could easily be mocked if the design-time service and generated proxies lived in different assemblies.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;LoadBooksByCategory &lt;/strong&gt;method applies the query to a static data-set before invoking a generic &lt;strong&gt;Load &lt;/strong&gt;method. The generic version makes sure the entities are contained in the &lt;strong&gt;EntityContainer &lt;/strong&gt;and then asynchronously invokes the callback.&lt;/p&gt;

&lt;h2&gt;BookDataService&lt;/h2&gt;

&lt;p&gt;The actual service implementation is greatly simplified and is now much closer to the design-time version.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookDataService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IBookDataService
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubContext &lt;/span&gt;_context = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookClubContext&lt;/span&gt;();

    ...

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityContainer &lt;/span&gt;EntityContainer
    {
      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return this&lt;/span&gt;._context.EntityContainer; }
    }

    ...&lt;span style="color: blue"&gt;&lt;/span&gt;&lt;/pre&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;public void &lt;/span&gt;LoadBooksByCategory(&lt;br /&gt;                  &lt;span style="color: blue"&gt;int &lt;/span&gt;categoryId,&lt;br /&gt;                  &lt;span style="color: #2b91af"&gt;QueryBuilder&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; query,&lt;br /&gt;                  &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;&amp;gt; callback,&lt;br /&gt;                  &lt;span style="color: blue"&gt;object &lt;/span&gt;state)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.Load(&lt;br /&gt;        query.ApplyTo(&lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetBooksByCategoryQuery(categoryId)),&lt;br /&gt;        lo =&amp;gt;
        {
          callback(&lt;span style="color: blue"&gt;this&lt;/span&gt;.CreateResult(lo, &lt;span style="color: blue"&gt;true&lt;/span&gt;));
        }, state);
    }

    &lt;span style="color: blue"&gt;...&lt;/span&gt;&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;    private void &lt;/span&gt;Load&amp;lt;T&amp;gt;(&lt;br /&gt;                   &lt;span style="color: #2b91af"&gt;EntityQuery&lt;/span&gt;&amp;lt;T&amp;gt; query,&lt;br /&gt;                   &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;LoadOperation&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; callback,&lt;br /&gt;                   &lt;span style="color: blue"&gt;object &lt;/span&gt;state)&lt;br /&gt;                 &lt;span style="color: blue"&gt;where &lt;/span&gt;T : &lt;span style="color: #2b91af"&gt;Entity
&lt;/span&gt;    {
      ...&lt;/pre&gt;&lt;pre class="code"&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.Load(query, lo =&amp;gt;
        {
          ...&lt;br /&gt;          callback(lo);
        }, state);
    }
&lt;/pre&gt;    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;T&amp;gt; CreateResult&amp;lt;T&amp;gt;(&lt;br /&gt;                                   &lt;span style="color: #2b91af"&gt;LoadOperation&lt;/span&gt;&amp;lt;T&amp;gt; op,&lt;br /&gt;                                   &lt;span style="color: blue"&gt;bool &lt;/span&gt;returnEditableCollection = &lt;span style="color: blue"&gt;false&lt;/span&gt;)&lt;br /&gt;                                 &lt;span style="color: blue"&gt;where &lt;/span&gt;T : &lt;span style="color: #2b91af"&gt;Entity
    &lt;/span&gt;{
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(op.HasError)
      {
        op.MarkErrorAsHandled();
      }
      &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;T&amp;gt;(
        returnEditableCollection ?&lt;br /&gt;          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityList&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;br /&gt;            &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContainer.GetEntitySet&amp;lt;T&amp;gt;(),&lt;br /&gt;            op.Entities) :&lt;br /&gt;          op.Entities,
        op.TotalEntityCount,
        op.ValidationErrors,
        op.Error,
        op.IsCanceled,
        op.UserState);
    }
  }&lt;/pre&gt;

&lt;p&gt;Again we can see the &lt;strong&gt;LoadBooksByCategory &lt;/strong&gt;method applying the query; this time to an &lt;strong&gt;EntityQuery&lt;/strong&gt;. It also creates a callback that it can pass through to the &lt;strong&gt;DomainContext.Load&lt;/strong&gt; method.&lt;/p&gt;

&lt;p&gt;It’s worth noting the &lt;strong&gt;CreateResult &lt;/strong&gt;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.&lt;/p&gt;

&lt;h2&gt;BookViewModel&lt;/h2&gt;

&lt;p&gt;The view model has changed a number of things to consume the new interface, but it’s all still pretty straightforward.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BookViewModel &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ViewModel
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private const int &lt;/span&gt;_pageSize = 10;

    &lt;span style="color: blue"&gt;private int &lt;/span&gt;_pageIndex;

    &lt;span style="color: blue"&gt;protected &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IPageConductor &lt;/span&gt;PageConductor { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;protected &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IBookDataService &lt;/span&gt;BookDataService { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    ... &lt;font color="#0000ff"&gt;&lt;br /&gt;&lt;/font&gt;
    &lt;span style="color: blue"&gt;public &lt;/span&gt;BookViewModel(
      &lt;span style="color: #2b91af"&gt;IPageConductor &lt;/span&gt;pageConductor,
      &lt;span style="color: #2b91af"&gt;IBookDataService &lt;/span&gt;bookDataService)
    {
      PageConductor = pageConductor;
      BookDataService = bookDataService;
      BookDataService.EntityContainer.PropertyChanged +=&lt;br /&gt;        BookDataService_PropertyChanged;

      RegisterCommands();
      LoadData();
    }

    &lt;span style="color: blue"&gt;private void &lt;/span&gt;BookDataService_PropertyChanged(&lt;br /&gt;                   &lt;span style="color: blue"&gt;object &lt;/span&gt;sender, &lt;span style="color: #2b91af"&gt;PropertyChangedEventArgs &lt;/span&gt;e)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(e.PropertyName == &lt;span style="color: #a31515"&gt;&amp;quot;HasChanges&amp;quot;&lt;/span&gt;)
      {
        HasChanges = BookDataService.EntityContainer.HasChanges;
        SaveBooksCommand.RaiseCanExecuteChanged();
      }
    }

    ...&lt;/pre&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;public void &lt;/span&gt;LoadBooksByCategory()
    {
      _pageIndex = 0;
      Books = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(SelectedCategory != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        BookDataService.LoadBooksByCategory(
          SelectedCategory.CategoryID,
          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;QueryBuilder&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;().Take(_pageSize),
          LoadBooksCallback,
          &lt;span style="color: blue"&gt;null&lt;/span&gt;);
      }
    }

    &lt;span style="color: blue"&gt;private void &lt;/span&gt;OnLoadMoreBooksByCategory()
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(SelectedCategory != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        _pageIndex++;
        BookDataService.LoadBooksByCategory(
          SelectedCategory.CategoryID,
          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;QueryBuilder&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;()&lt;br /&gt;                .Skip(_pageIndex * _pageSize).Take(_pageSize),
          LoadBooksCallback,
          &lt;span style="color: blue"&gt;null&lt;/span&gt;);
      }
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;LoadBooksByTitle()
    {
      _pageIndex = 0;
      Books = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(SelectedCategory != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        BookDataService.LoadBooksByCategory(
          SelectedCategory.CategoryID,
          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;QueryBuilder&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;()&lt;br /&gt;                .Where(b =&amp;gt; b.Title.Contains(TitleFilter)),
          LoadBooksCallback,
          &lt;span style="color: blue"&gt;null&lt;/span&gt;);
      }
    }

    &lt;span style="color: blue"&gt;private void &lt;/span&gt;LoadBooksCallback(&lt;span style="color: #2b91af"&gt;ServiceLoadResult&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; result)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(result.Error != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: green"&gt;// handle error
      &lt;/span&gt;}
      &lt;span style="color: blue"&gt;else if &lt;/span&gt;(!result.Cancelled)
      {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(Books == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        {
          Books = result.Entities &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICollection&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt;;
        }
        &lt;span style="color: blue"&gt;else
        &lt;/span&gt;{
          &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;book &lt;span style="color: blue"&gt;in &lt;/span&gt;result.Entities)
          {
            Books.Add(book);
          }
        }

        SelectedBook = Books.FirstOrDefault();
      }
    }

    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICollection&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; _books;
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICollection&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Book&lt;/span&gt;&amp;gt; Books
    {
      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;_books; }
      &lt;span style="color: blue"&gt;set
      &lt;/span&gt;{
        _books = &lt;span style="color: blue"&gt;value&lt;/span&gt;;
        RaisePropertyChanged(&lt;span style="color: #a31515"&gt;&amp;quot;Books&amp;quot;&lt;/span&gt;);
      }
    }

    ...&lt;br /&gt;  }&lt;/pre&gt;

&lt;p&gt;The first place to highlight is in the constructor where the view model subscribes to property change events on the &lt;strong&gt;EntityContainer&lt;/strong&gt;. This allows the view model to listen directly for changes made to any of the entities it is working against.&lt;/p&gt;

&lt;p&gt;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 &lt;strong&gt;IBookDataService&lt;/strong&gt;. In all three cases, the composed query will be run on the server.&lt;/p&gt;

&lt;p&gt;Finally, the &lt;strong&gt;LoadBooksCallback&lt;/strong&gt; casts &lt;strong&gt;result.Entities&lt;/strong&gt; to an &lt;strong&gt;ICollection&amp;lt;Book&amp;gt;&lt;/strong&gt;. This is because &lt;strong&gt;Books &lt;/strong&gt;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 &lt;strong&gt;BookDataService &lt;/strong&gt;is returning an &lt;strong&gt;EntityList &lt;/strong&gt;from &lt;strong&gt;CreateResult (&lt;/strong&gt;above), and &lt;strong&gt;EntityList &lt;/strong&gt;knows how to correctly handle the addition and removal of entities.&lt;/p&gt;

&lt;h2&gt;Service Result Types&lt;/h2&gt;

&lt;p&gt;I added three result types to the sample (to the Ria.Common project), &lt;strong&gt;ServiceInvokeResult&lt;/strong&gt;, &lt;strong&gt;ServiceLoadResult&lt;/strong&gt;, and &lt;strong&gt;ServiceSubmitChangesResult&lt;/strong&gt;. 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 &lt;strong&gt;ServiceLoadResult &lt;/strong&gt;has properties for the &lt;strong&gt;Error &lt;/strong&gt;and &lt;strong&gt;Cancelled &lt;/strong&gt;states as well as the enumerable &lt;strong&gt;Entities&lt;/strong&gt;. As can be seen in the &lt;strong&gt;LoadBooksCallback&lt;/strong&gt; 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.&lt;/p&gt;

&lt;h1&gt;QueryBuilder and the DomainCollectionView&lt;/h1&gt;

&lt;p&gt;Though it isn’t apparent in this sample, the &lt;strong&gt;QueryBuilder &lt;/strong&gt;also acts as a bridge between the &lt;strong&gt;DomainCollectionView &lt;/strong&gt;(&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/04/15/domaincollectionview-updates-for-mix-11.aspx"&gt;read about the DomainCollectionView&lt;/a&gt;) and the service layer. Each of the query extensions provided for the &lt;strong&gt;DCV&lt;/strong&gt; work against the &lt;strong&gt;QueryBuilder &lt;/strong&gt;as well. For instance, &lt;strong&gt;SortAndPageBy &lt;/strong&gt;could be applied to the query in the view model before passing the &lt;strong&gt;QueryBuilder &lt;/strong&gt;to the service layer.&lt;/p&gt;

&lt;h1&gt;Summary&lt;/h1&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;h4&gt;[Interesting Variations]&lt;/h4&gt;

&lt;p&gt;Since writing this, there have been a few intrepid developers who’ve written variations on the pattern worth mentioning.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Remco combined the pattern with my &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/11/02/using-the-visual-studio-async-ctp-with-ria-services.aspx"&gt;guidance on using Tasks (from the VS Async CTP)&lt;/a&gt; to create a &lt;a href="http://code.msdn.microsoft.com/Task-based-MVVM-Sample-for-2eb86fab"&gt;Task Based MVVM Sample&lt;/a&gt;.&lt;/li&gt;

  &lt;li&gt;Colin riffed in a couple directions first &lt;a href="https://bitly.com/bundles/colinblair/2"&gt;combining the pattern with MEF and then splitting it into a number of class libraries&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10159553" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="MVVM" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/MVVM/" /><category term="CollectionView" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/CollectionView/" /></entry><entry><title>DomainCollectionView Updates for Mix ‘11</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/04/15/domaincollectionview-updates-for-mix-11.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/04/15/domaincollectionview-updates-for-mix-11.aspx</id><published>2011-04-15T15:30:12Z</published><updated>2011-04-15T15:30:12Z</updated><content type="html">&lt;p&gt;To correspond to the new RIA Services build we’ve released at Mix, I’ve made some updates to the &lt;strong&gt;DomainCollectionView&lt;/strong&gt;. I updated select API, fixed a few bugs, and updated the sample as well. If you’re not familiar with the &lt;strong&gt;DCV&lt;/strong&gt;, here’s &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx"&gt;my original post introducing it&lt;/a&gt;. For the sake of brevity in this post, I’ll assume you’ve read it.&lt;/p&gt;  &lt;h1&gt;Breaking Changes&lt;/h1&gt;  &lt;p&gt;There are a few breaking changes to the API. Most notably, &lt;strong&gt;SortPageAndCount &lt;/strong&gt;has been renamed. It’s a breaking change, but a simple find-replace should set things right again.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;SortAndPageBy &lt;/strong&gt;replaces &lt;strong&gt;SortPageAndCount&lt;/strong&gt;       &lt;ul&gt;       &lt;li&gt;&lt;strong&gt;SortAndPageBy &lt;/strong&gt;calls &lt;strong&gt;SortBy &lt;/strong&gt;and &lt;strong&gt;PageBy &lt;/strong&gt;respectively &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;SortBy &lt;/strong&gt;replaces &lt;strong&gt;Sort&lt;/strong&gt;       &lt;ul&gt;       &lt;li&gt;&lt;strong&gt;SortBy &lt;/strong&gt;applies &lt;strong&gt;OrderBy &lt;/strong&gt;and &lt;strong&gt;ThenBy &lt;/strong&gt;clauses to the query &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;PageBy &lt;/strong&gt;replaces &lt;strong&gt;Page&lt;/strong&gt;       &lt;ul&gt;       &lt;li&gt;&lt;strong&gt;PageBy &lt;/strong&gt;applies &lt;strong&gt;Skip &lt;/strong&gt;and &lt;strong&gt;Take &lt;/strong&gt;clauses to the query and conditionally requests the &lt;strong&gt;TotalEntityCount&lt;/strong&gt; &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;(All the other query extensions have been removed)      &lt;br /&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;h1&gt;Bug Fixes&lt;/h1&gt;  &lt;p&gt;There were a few bug fixes that went in to improve compatibility with third-party controls. I’ve tested the &lt;strong&gt;DCV &lt;/strong&gt;against four suites of controls now, and it works well with all of them. As always, let me know when you find issues.&lt;/p&gt;  &lt;h1&gt;Sample&lt;/h1&gt;  &lt;p&gt;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.&lt;/p&gt;  &lt;p&gt;I’ve updated the UI to include a search field.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/1185.image_5F00_136148B1.png"&gt;&lt;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="http://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" /&gt;&lt;/a&gt; &lt;/pre&gt;

&lt;p&gt;The search button now invokes the search command which calls into the &lt;strong&gt;OnSearch &lt;/strong&gt;method in my &lt;strong&gt;SampleViewModel&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private void &lt;/span&gt;OnSearch()
  {
    &lt;span style="color: green"&gt;// This makes sure we refresh even if we're already on the first page
    &lt;/span&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;._view.DeferRefresh())
    {
      &lt;span style="color: green"&gt;// This will lead us to re-query for the total count
      &lt;/span&gt;&lt;span style="color: blue"&gt;this&lt;/span&gt;._view.SetTotalItemCount(-1);
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.MoveToFirstPage();
    }
  }&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;OnSearch &lt;/strong&gt;method resets the total item count and refreshes the view; leading us back into our load callback.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LoadOperation&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; LoadSampleEntities()
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.CanLoad = &lt;span style="color: blue"&gt;false&lt;/span&gt;;

    &lt;span style="color: #2b91af"&gt;EntityQuery&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; query = &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetAllEntitiesQuery();
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(!&lt;span style="color: blue"&gt;string&lt;/span&gt;.IsNullOrWhiteSpace(&lt;span style="color: blue"&gt;this&lt;/span&gt;.SearchText))
    {
      query = query.Where(e =&amp;gt; e.String.Contains(&lt;span style="color: blue"&gt;this&lt;/span&gt;.SearchText));
    }

    &lt;span style="color: blue"&gt;return this&lt;/span&gt;._context.Load(query.SortAndPageBy(&lt;span style="color: blue"&gt;this&lt;/span&gt;._view));
  }&lt;/pre&gt;

&lt;p&gt;To make sure the filter gets applied on the server, we conditionally add a &lt;strong&gt;Where &lt;/strong&gt;clause to our query based on the content of the &lt;strong&gt;SearchText&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That covers the new additions to the &lt;strong&gt;DomainCollectionView&lt;/strong&gt;. 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.&lt;/p&gt;

&lt;p&gt;&lt;a title="http://code.msdn.microsoft.com/Server-Side-Filtering-737becda" href="http://code.msdn.microsoft.com/Server-Side-Filtering-737becda"&gt;http://code.msdn.microsoft.com/Server-Side-Filtering-737becda&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10154522" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="MVVM" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/MVVM/" /><category term="CollectionView" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/CollectionView/" /></entry><entry><title>Using RIA Services with ComboBoxes and Enums</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2011/01/06/using-ria-services-with-comboboxes-and-enums.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2011/01/06/using-ria-services-with-comboboxes-and-enums.aspx</id><published>2011-01-06T21:29:09Z</published><updated>2011-01-06T21:29:09Z</updated><content type="html">&lt;p&gt;The other day someone asked me how to get a &lt;strong&gt;ComboBox &lt;/strong&gt;working with enums and validation. It turned out to be more tricky than I had anticipated (&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx"&gt;there’s a common theme here…&lt;/a&gt;) so I figured I’d put together a quick post on it.&lt;/p&gt;  &lt;h1&gt;Stumbling Points&lt;/h1&gt;  &lt;p&gt;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.&lt;/p&gt;  &lt;p&gt;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 &lt;em&gt;.shared.cs &lt;/em&gt;or &lt;em&gt;.shared.vb &lt;/em&gt;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.&lt;/p&gt;  &lt;p&gt;The second error I ran into was using client-side projection properties. In the past I’ve preferred these to using an &lt;strong&gt;IValueConverter&lt;/strong&gt; 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).&lt;/p&gt;  &lt;h1&gt;The Solution&lt;/h1&gt;  &lt;p&gt;I eventually ended up using an &lt;strong&gt;IValueConverter&lt;/strong&gt;-based solution. I put a little extra work into it to make it &lt;strong&gt;DisplayAttribute&lt;/strong&gt;-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)&lt;/p&gt;  &lt;p&gt;I applied these changes to the sample I used in this post (&lt;a title="http://blogs.msdn.com/b/kylemc/archive/2010/11/12/silverlight-tv-52-ria-services-q-a.aspx" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/12/silverlight-tv-52-ria-services-q-a.aspx"&gt;http://blogs.msdn.com/b/kylemc/archive/2010/11/12/silverlight-tv-52-ria-services-q-a.aspx&lt;/a&gt;) if you want a place to try it out. These steps should work in any scenario, though.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/0385.image_5F00_6F0AC0AB.png"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="image" alt="image" src="http://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" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;To create the look above, I defined a simple enum with &lt;strong&gt;DisplayAttributes&lt;/strong&gt; on each of the values.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public enum &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyEnum
&lt;/span&gt;  {
    [&lt;span style="color: #2b91af"&gt;Display&lt;/span&gt;(Name = &lt;span style="color: #a31515"&gt;&amp;quot;(please pick a value)&amp;quot;&lt;/span&gt;)]
    None = 0,
    [&lt;span style="color: #2b91af"&gt;Display&lt;/span&gt;(Name = &lt;span style="color: #a31515"&gt;&amp;quot;Value 1&amp;quot;&lt;/span&gt;)]
    Value1 = 1,
    [&lt;span style="color: #2b91af"&gt;Display&lt;/span&gt;(Name = &lt;span style="color: #a31515"&gt;&amp;quot;Value 2&amp;quot;&lt;/span&gt;)]
    Value2 = 2,
    [&lt;span style="color: #2b91af"&gt;Display&lt;/span&gt;(Name = &lt;span style="color: #a31515"&gt;&amp;quot;Value 3&amp;quot;&lt;/span&gt;)]
    Value3 = 3,
  }&lt;/pre&gt;

&lt;p&gt;Then I added a property to my entity that used custom validation to ensure a non-zero value is selected.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;CustomValidation&lt;/span&gt;(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Validation&lt;/span&gt;), &lt;span style="color: #a31515"&gt;&amp;quot;ValidateMyEnum&amp;quot;&lt;/span&gt;)]
  [&lt;span style="color: #2b91af"&gt;DataMember&lt;/span&gt;]
&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyEnum &lt;/span&gt;MyEnum { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }&lt;/pre&gt;

&lt;p&gt;(My validation is in a shared file in the web project, &lt;em&gt;Validation.shared.cs&lt;/em&gt;)&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Validation
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ValidationResult &lt;/span&gt;ValidateMyEnum(&lt;br /&gt;      &lt;span style="color: #2b91af"&gt;MyEnum &lt;/span&gt;myEnum, &lt;span style="color: #2b91af"&gt;ValidationContext &lt;/span&gt;context)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(myEnum == &lt;span style="color: #2b91af"&gt;MyEnum&lt;/span&gt;.None)
      {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ValidationResult&lt;/span&gt;(&lt;br /&gt;          &lt;span style="color: #a31515"&gt;&amp;quot;You must pick a value.&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { context.MemberName });
      }
      &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ValidationResult&lt;/span&gt;.Success;
    }
  }&lt;/pre&gt;

&lt;p&gt;My next step was to define the &lt;strong&gt;ComboBox &lt;/strong&gt;on the client.&lt;/p&gt;

&lt;pre class="code"&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ComboBox &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;myEnumNames&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot;
            &lt;/span&gt;&lt;span style="color: red"&gt;SelectedItem&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=MyEnum&lt;/span&gt;&lt;span style="color: blue"&gt;,&lt;br /&gt;                                   &lt;/span&gt;&lt;span style="color: red"&gt;Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=TwoWay,&lt;br /&gt;                                   &lt;/span&gt;&lt;span style="color: red"&gt;Converter&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;enumToString&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;&lt;br /&gt;  /&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;SelectedItem &lt;/strong&gt;binding references a converter I instantiate in my page resources.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;app&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;EnumToStringValueConverter &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Key&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;enumToString&amp;quot; /&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The code for the converter is simple and leverages the &lt;strong&gt;EnumUtility&lt;/strong&gt; I’ll describe a little later. It is also generic so a single instance can be shared between multiple types of enums.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EnumToStringValueConverter &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IValueConverter
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public object &lt;/span&gt;Convert(&lt;span style="color: blue"&gt;object &lt;/span&gt;value, &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;targetType,&lt;br /&gt;      &lt;span style="color: blue"&gt;object &lt;/span&gt;parameter, &lt;span style="color: #2b91af"&gt;CultureInfo &lt;/span&gt;culture)
    {
      &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EnumUtility&lt;/span&gt;.GetName(value.GetType(), value);
    }

    &lt;span style="color: blue"&gt;public object &lt;/span&gt;ConvertBack(&lt;span style="color: blue"&gt;object &lt;/span&gt;value, &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;targetType,&lt;br /&gt;      &lt;span style="color: blue"&gt;object &lt;/span&gt;parameter, &lt;span style="color: #2b91af"&gt;CultureInfo &lt;/span&gt;culture)
    {
      &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EnumUtility&lt;/span&gt;.GetValue(targetType, value.ToString());
    }
  }&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;ItemsSource &lt;/strong&gt;in the &lt;strong&gt;ComboBox&lt;/strong&gt; above uses a static resource I add in my page constructor before parsing the xaml (in &lt;strong&gt;InitializeComponent&lt;/strong&gt;). I’ve used the &lt;strong&gt;EnumUtility &lt;/strong&gt;again to get the names for my enum.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  this&lt;/span&gt;.Resources.Add(&lt;span style="color: #a31515"&gt;&amp;quot;myEnumNames&amp;quot;&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;EnumUtility&lt;/span&gt;.GetNames(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;MyEnum&lt;/span&gt;)));&lt;br /&gt;  InitializeComponent();&lt;/pre&gt;

&lt;p&gt;With all the pieces in place (an enum, a property to bind to, a converter, a list of names, and a &lt;strong&gt;ComboBox&lt;/strong&gt;), I now have a &lt;strong&gt;ComboBox &lt;/strong&gt;bound to an enum and validating input.&lt;/p&gt;

&lt;h1&gt;An Enum Utility&lt;/h1&gt;

&lt;p&gt;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 &lt;strong&gt;GetName &lt;/strong&gt;and &lt;strong&gt;GetValue &lt;/strong&gt;methods map back and forth between the two. Here’s the source in case you’re interested.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EnumUtility
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private static readonly&lt;br /&gt;      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; names =&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;();
    &lt;span style="color: blue"&gt;private static readonly&lt;br /&gt;      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt; values =&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();
    &lt;span style="color: blue"&gt;private static readonly&lt;br /&gt;     &lt;/span&gt;&lt;span style="color: blue"&gt; &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt; namesToValues =&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();
    &lt;span style="color: blue"&gt;private static readonly&lt;br /&gt;      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; valuesToNames =&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;();

    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;Initialize(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type)
    {
      Initialize(type, GetDisplayAttributeName);
    }

    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;Initialize(&lt;br /&gt;      &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;FieldInfo&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; getName)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(type == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;type&amp;quot;&lt;/span&gt;);
      }

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(!type.IsEnum)
      {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Type must be an enum.&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;type&amp;quot;&lt;/span&gt;);
      }

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(getName == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;getName&amp;quot;&lt;/span&gt;);
      }

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(names.ContainsKey(type))
      {
        &lt;span style="color: blue"&gt;return&lt;/span&gt;;
      }
        
      &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; tempNames = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();
      &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; tempValues = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;();
      &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; tempNamesToValues =&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;();
      &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; tempValuesToNames =&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();

      &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;FieldInfo &lt;/span&gt;fi &lt;span style="color: blue"&gt;in&lt;br /&gt;        &lt;/span&gt;type.GetFields(&lt;span style="color: #2b91af"&gt;BindingFlags&lt;/span&gt;.Public | &lt;span style="color: #2b91af"&gt;BindingFlags&lt;/span&gt;.Static))
      {
        &lt;span style="color: blue"&gt;string &lt;/span&gt;name = getName(fi);
        &lt;span style="color: blue"&gt;object &lt;/span&gt;value = fi.GetValue(&lt;span style="color: blue"&gt;null&lt;/span&gt;);

        tempNames.Add(name);
        tempValues.Add(value);
        tempNamesToValues[name] = value;
        tempValuesToNames[value] = name;
      }

      names[type] = tempNames;
      values[type] = tempValues;
      namesToValues[type] = tempNamesToValues;
      valuesToNames[type] = tempValuesToNames;
    }

    &lt;span style="color: blue"&gt;private static string &lt;/span&gt;GetDisplayAttributeName(&lt;span style="color: #2b91af"&gt;FieldInfo &lt;/span&gt;fi)
    {
      &lt;span style="color: #2b91af"&gt;DisplayAttribute &lt;/span&gt;displayAttribute = &lt;br /&gt;       (&lt;span style="color: #2b91af"&gt;DisplayAttribute&lt;/span&gt;)fi.GetCustomAttributes(&lt;br /&gt;         &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;DisplayAttribute&lt;/span&gt;), &lt;span style="color: blue"&gt;false&lt;/span&gt;).FirstOrDefault();

      &lt;span style="color: blue"&gt;return &lt;/span&gt;(displayAttribute == &lt;span style="color: blue"&gt;null&lt;/span&gt;) ? fi.Name : displayAttribute.Name;
    }

    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; GetNames(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type)
    {
      Initialize(type);
      &lt;span style="color: blue"&gt;return &lt;/span&gt;names[type];
    }

    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt; GetValues(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type)
    {
      Initialize(type);
      &lt;span style="color: blue"&gt;return &lt;/span&gt;values[type];
    }

    &lt;span style="color: blue"&gt;public static string &lt;/span&gt;GetName(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type, &lt;span style="color: blue"&gt;object &lt;/span&gt;value)
    {
      Initialize(type);
      &lt;span style="color: blue"&gt;return &lt;/span&gt;valuesToNames[type][value];
    }

    &lt;span style="color: blue"&gt;public static object &lt;/span&gt;GetValue(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type, &lt;span style="color: blue"&gt;string &lt;/span&gt;name)
    {
      Initialize(type);
      &lt;span style="color: blue"&gt;return &lt;/span&gt;namesToValues[type][name];
    }
  }&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10112685" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="ComboBox" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/ComboBox/" /></entry><entry><title>Collection Binding Options in WCF RIA Services SP1</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/12/02/collection-binding-options-in-wcf-ria-services-sp1.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/12/02/collection-binding-options-in-wcf-ria-services-sp1.aspx</id><published>2010-12-02T17:05:43Z</published><updated>2010-12-02T17:05:43Z</updated><content type="html">&lt;p&gt;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 &lt;strong&gt;DomainContext &lt;/strong&gt;or &lt;strong&gt;DomainDataSource&lt;/strong&gt;. 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.&lt;/p&gt;  &lt;h1&gt;Bind to an EntitySet&lt;/h1&gt;  &lt;p&gt;As of SP1, we &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/10/28/improved-binding-support-in-entityset-and-entitycollection.aspx"&gt;improved binding support for EntitySets&lt;/a&gt;. &lt;strong&gt;EntitySets &lt;/strong&gt;are aggregating, un-ordered collections. That means every time an entity is loaded by your &lt;strong&gt;DomainContext &lt;/strong&gt;it will be added to its corresponding &lt;strong&gt;EntitySet&lt;/strong&gt;. Binding to an &lt;strong&gt;EntitySet &lt;/strong&gt;will give you a great view of every entity of a specific type your &lt;strong&gt;DomainContext &lt;/strong&gt;knows about. Adding to or removing from an &lt;strong&gt;EntitySet &lt;/strong&gt;will result in calls to the insert and delete operations being invoked when you submit changes to your &lt;strong&gt;DomainService&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;Making an &lt;strong&gt;EntitySet &lt;/strong&gt;available in your view model would look like this.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntitySet&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; EntitySet
  {
    &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return this&lt;/span&gt;.Context.SampleEntities; }
  }&lt;/pre&gt;

&lt;h1&gt;Bind to an EntityCollection&lt;/h1&gt;

&lt;p&gt;In SP1, we also &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/10/28/improved-binding-support-in-entityset-and-entitycollection.aspx"&gt;improved binding support for EntityCollections&lt;/a&gt;. &lt;strong&gt;EntityCollections &lt;/strong&gt;are collections of entities associated with a specific &lt;strong&gt;Entity&lt;/strong&gt;. In a manner similar to the &lt;strong&gt;EntitySet&lt;/strong&gt;, an &lt;strong&gt;EntityCollection &lt;/strong&gt;will be updated as new entities are loaded into your &lt;strong&gt;DomainContext&lt;/strong&gt;. Each will be added to the &lt;strong&gt;EntityCollection &lt;/strong&gt;of the &lt;strong&gt;Entity &lt;/strong&gt;it is associated with. Adding and removing from an &lt;strong&gt;EntityCollection &lt;/strong&gt;will only update the association. Most of the time, this results in an update operation being invoked when you submit changes.&lt;/p&gt;

&lt;p&gt;Since &lt;strong&gt;EntityCollections&lt;/strong&gt; are tied to specified &lt;strong&gt;Entities&lt;/strong&gt;, having a property on your view model seems like an uncommon case. Nevertheless, making an &lt;strong&gt;EntityCollection &lt;/strong&gt;available in your view model would look like this.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityCollection&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; EntityCollection
  {
    &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return this&lt;/span&gt;.CurrentEntity.AssociatedEntities; }
  }&lt;/pre&gt;

&lt;h1&gt;Bind to an EntityList&lt;/h1&gt;

&lt;p&gt;&lt;strong&gt;EntityList &lt;/strong&gt;is a type new to SP1 and can be found in &lt;strong&gt;Microsoft.Windows.Data.DomainServices&lt;/strong&gt; in the Toolkit. An &lt;strong&gt;EntityList &lt;/strong&gt;is an observable collection backed by an &lt;strong&gt;EntitySet&lt;/strong&gt;. The &lt;strong&gt;Source &lt;/strong&gt;property on the &lt;strong&gt;EntityList &lt;/strong&gt;defines the entities it contains, and it will not update as new entities are loaded into your &lt;strong&gt;DomainContext&lt;/strong&gt;. It will update if entities it contains are deleted from the &lt;strong&gt;EntitySet &lt;/strong&gt;or when entities are added or removed from its &lt;strong&gt;Source &lt;/strong&gt;collection. Adding to an &lt;strong&gt;EntityList &lt;/strong&gt;will behave in one of two ways. If the entity already exists in the backing &lt;strong&gt;EntitySet&lt;/strong&gt;, then it is just added to the list. If it does not exist, then it will be added to the &lt;strong&gt;EntitySet &lt;/strong&gt;as well. Removing from the &lt;strong&gt;EntityList &lt;/strong&gt;will always remove the entity from the backing &lt;strong&gt;EntitySet&lt;/strong&gt;. Binding to an &lt;strong&gt;EntityList &lt;/strong&gt;is a great option when you only want to see a subset of the entities your &lt;strong&gt;DomainContext &lt;/strong&gt;knows about.&lt;/p&gt;

&lt;p&gt;Making an &lt;strong&gt;EntityList &lt;/strong&gt;available in your view model would look like this.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; _entityList;
&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; EntityList
  {
    &lt;span style="color: blue"&gt;get
    &lt;/span&gt;{
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;._entityList == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._entityList = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(&lt;br /&gt;          &lt;span style="color: blue"&gt;this&lt;/span&gt;.Context.SampleEntities);
      }
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;._entityList;
    }
  }

&lt;span style="color: blue"&gt;  private void &lt;/span&gt;LoadSampleEntities()
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityList.Source =
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.Context.Load(&lt;span style="color: blue"&gt;this&lt;/span&gt;.Context.GetAllEntitiesQuery()).Entities;
  }&lt;/pre&gt;

&lt;h1&gt;Bind to an ICollectionView&lt;/h1&gt;

&lt;p&gt;In case you’re not familiar with the &lt;strong&gt;ICollectionView &lt;/strong&gt;interface, it’s used by a number of components (&lt;strong&gt;DataGrid&lt;/strong&gt;, &lt;strong&gt;DataForm&lt;/strong&gt;, etc.) as a view over a source collection. For example, when you bind &lt;strong&gt;DataGrid.ItemsSource &lt;/strong&gt;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 &lt;strong&gt;ICollectionView&lt;/strong&gt; available for binding directly from your view model.&lt;/p&gt;

&lt;p&gt;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 &lt;strong&gt;ICollectionView&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;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 &lt;strong&gt;CollectionViewSource&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICollectionView &lt;/span&gt;CreateView(&lt;span style="color: #2b91af"&gt;IEnumerable &lt;/span&gt;source)
  {
    &lt;span style="color: #2b91af"&gt;CollectionViewSource &lt;/span&gt;cvs = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CollectionViewSource&lt;/span&gt;();
    cvs.Source = source;
    &lt;span style="color: blue"&gt;return &lt;/span&gt;cvs.View;
  }&lt;/pre&gt;

&lt;p&gt;Making an &lt;strong&gt;ICollectionView &lt;/strong&gt;available in your view model would look like this.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICollectionView &lt;/span&gt;_collectionView;
&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICollectionView &lt;/span&gt;CollectionView
  {
    &lt;span style="color: blue"&gt;get
    &lt;/span&gt;{
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;._collectionView == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._collectionView = CreateView(&lt;span style="color: blue"&gt;this&lt;/span&gt;.Context.SampleEntities);
      }
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;._collectionView;
    }
  }&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h1&gt;Bind to a DomainCollectionView&lt;/h1&gt;

&lt;p&gt;To address the limitations of existing &lt;strong&gt;ICollectionView&lt;/strong&gt; implementations we’ve added the &lt;strong&gt;DomainCollectionView &lt;/strong&gt;in SP1 in &lt;strong&gt;Microsoft.Windows.Data.DomainServices&lt;/strong&gt; 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.&lt;/p&gt;

&lt;p&gt;The setup for a &lt;strong&gt;DomainCollectionView &lt;/strong&gt;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.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LoadOperation&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; LoadSampleEntities()
  {
    &lt;span style="color: blue"&gt;return this&lt;/span&gt;.Context.Load(
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.Context.GetAllEntitiesQuery().SortPageAndCount(&lt;br /&gt;        &lt;span style="color: blue"&gt;this&lt;/span&gt;.DomainCollectionView));
  }

&lt;span style="color: blue"&gt;  private void &lt;/span&gt;OnLoadSampleEntitiesCompleted(&lt;span style="color: #2b91af"&gt;LoadOperation&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; op)
  {
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(op.HasError)
    {
      &lt;span style="color: green"&gt;// TODO: handle errors
      &lt;/span&gt;op.MarkErrorAsHandled();
    }
    &lt;span style="color: blue"&gt;else if &lt;/span&gt;(!op.IsCanceled)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityList.Source = op.Entities;

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(op.TotalEntityCount != -1)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.DomainCollectionView.SetTotalItemCount(op.TotalEntityCount);
      }
    }
  }&lt;/pre&gt;

&lt;p&gt;With callbacks defined, making a &lt;strong&gt;DomainCollectionView &lt;/strong&gt;available in your view model would look like this.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainCollectionView&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; _domainCollectionView;
&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainCollectionView&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; DomainCollectionView
  {
    &lt;span style="color: blue"&gt;get
    &lt;/span&gt;{
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;._domainCollectionView == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._domainCollectionView =
          &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainCollectionView&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(
            &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainCollectionViewLoader&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(
              &lt;span style="color: blue"&gt;this&lt;/span&gt;.LoadSampleEntities,
              &lt;span style="color: blue"&gt;this&lt;/span&gt;.OnLoadSampleEntitiesCompleted),
            &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityList);
      }
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;._domainCollectionView;
    }
  }&lt;/pre&gt;

&lt;p&gt;This is just enough to get you started with the &lt;strong&gt;DomainCollectionView&lt;/strong&gt;, 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.&lt;/p&gt;

&lt;p&gt;&lt;a title="http://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx" href="http://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx"&gt;http://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;Are there other options?&lt;/h1&gt;

&lt;p&gt;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 &lt;strong&gt;IEnumerable&lt;/strong&gt; or &lt;strong&gt;ICollectionView&lt;/strong&gt;). 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.&lt;/p&gt;

&lt;p&gt;If you have other suggestions, I’d love to hear them. Hope this overview helps.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10099623" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="MVVM" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/MVVM/" /><category term="CollectionView" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/CollectionView/" /><category term="PDC10" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/PDC10/" /></entry><entry><title>Introducing An MVVM-Friendly DomainDataSource: The DomainCollectionView</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/12/02/introducing-an-mvvm-friendly-domaindatasource-the-domaincollectionview.aspx</id><published>2010-12-02T17:03:55Z</published><updated>2010-12-02T17:03:55Z</updated><content type="html">&lt;p&gt;&lt;strong&gt;&lt;font color="#ff0000"&gt;[This sample references out-of-date API. &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2011/04/15/domaincollectionview-updates-for-mix-11.aspx"&gt;This newer post&lt;/a&gt; discusses the updates made for the V1 SP2 Preview and shows how to implement filtering.]&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;There’ve been &lt;a href="http://dotnet.uservoice.com/forums/57026-wcf-ria-services"&gt;plenty of talk about an MVVM-friendly DomainDataSource&lt;/a&gt;. I’m pretty sure it means completely different things to different people. I even &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/09/17/my-thoughts-on-an-mvvm-friendly-domaindatasource.aspx"&gt;took a stab at defining it&lt;/a&gt; a while back. What we’ve included in the &lt;strong&gt;Microsoft.Windows.Data.DomainServices&lt;/strong&gt; assembly in the Toolkit closely follows that outline.&lt;/p&gt;  &lt;p&gt;Since this is the first look at this component, I feel compelled to tell you what we’ve provided is more like an engine than a car. There’s a lot of power and flexibility in the &lt;strong&gt;DomainCollectionView &lt;/strong&gt;design, but there are still a lot of ways to misuse it. We haven’t spent nearly as much time nailing down the use cases as we did on the &lt;strong&gt;DomainDataSource &lt;/strong&gt;(for good or for bad).&lt;/p&gt;  &lt;p&gt;Without further introduction, let’s dig in.&lt;/p&gt;  &lt;h1&gt;What is the DomainCollectionView?&lt;/h1&gt;  &lt;p&gt;The &lt;strong&gt;DomainCollectionView &lt;/strong&gt;(herein referred to as the &lt;strong&gt;DCV&lt;/strong&gt;) is a collection view implementation. The generic version of the class implements all the following interfaces. Most controls are designed to recognize and work against these interfaces.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;ICollectionView&lt;/strong&gt; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;IEditableCollectionView&lt;/strong&gt; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;IPagedCollectionView&lt;/strong&gt; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;IEnumerable&lt;/strong&gt; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;INotifyPropertyChanged&lt;/strong&gt; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;INotifyCollectionChanged&lt;/strong&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;For fear of pushing you to the brink of insanity, I’ll forego listing the full API. Instead, I’ll just say there are a lot of properties and methods for you to get acquainted with. Here’s a list of the ones you’ll commonly find yourself using.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;CurrentItem, CurrentPosition, and MoveCurrentToXx:&lt;/strong&gt; This is treated as the selected item in most list controls &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;GroupDescriptions:&lt;/strong&gt; This collection defines the way items are grouped and also affects server-side sorting &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;PageIndex, MoveToXxPage:&lt;/strong&gt; Calling &lt;strong&gt;MoveToPage&lt;/strong&gt; will prompt the view to load the page at the specified index &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;PageSize:&lt;/strong&gt; This defines the number of items to load on each page &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Refresh, DeferRefresh:&lt;/strong&gt; Calling &lt;strong&gt;Refresh&lt;/strong&gt; will prompt the view to load using the current view settings &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;SortDescriptions: &lt;/strong&gt;This collection defines the way items are sorted and affects server-side sorting &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;SourceCollection:&lt;/strong&gt; This is the collection that backs the view and only items in the collection will appear in the view &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;TotalItemCount, SetTotalItemCount:&lt;/strong&gt; This is used to calculate the total number of pages       &lt;br /&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;h1&gt;How Do I Use a DomainCollectionView?&lt;/h1&gt;  &lt;p&gt;The &lt;strong&gt;DCV &lt;/strong&gt;is designed using the following triad.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/5554.image_5F00_34728BDA.png"&gt;&lt;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="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/0247.image_5F00_thumb_5F00_1B0A88A0.png" width="350" height="248" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;In the design, the View component is the &lt;strong&gt;DCV&lt;/strong&gt;. It’s primary functions are to funnel interface calls to the Loader and to respond to changes in the Loader and Source components.&lt;/p&gt;  &lt;p&gt;The Loader component is the &lt;strong&gt;CollectionViewLoader&lt;/strong&gt;. It is responsible for handling an asynchronous &lt;strong&gt;Load &lt;/strong&gt;call and raising the &lt;strong&gt;LoadCompleted &lt;/strong&gt;event upon completion. The &lt;strong&gt;DomainCollectionViewLoader &lt;/strong&gt;is the default implementation and can be created with two callbacks allowing you to handle loading and load completion.&lt;/p&gt;  &lt;p&gt;The Source component can be any collection that implements &lt;strong&gt;IEnumerable&lt;/strong&gt;. However, observable collections tend to provide the best results. When the Loader gets data, it should update the source and the source should notify the view. &lt;strong&gt;EntityList&lt;/strong&gt; works well as the source, especially in paging scenarios.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/8270.image_5F00_45E2ECB2.png"&gt;&lt;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="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/5531.image_5F00_thumb_5F00_1E3C7088.png" width="410" height="290" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Your responsibilities fall mostly along the bottom of the triangle. When the view is refreshed (by a you or a control), it will ask you to load the appropriate data. This usually breaks down into the following steps.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Create an &lt;strong&gt;EntityQuery&lt;/strong&gt; and apply the view state to the query. There are a number of &lt;strong&gt;EntityQuery &lt;/strong&gt;extension methods, including &lt;strong&gt;Sort &lt;/strong&gt;and &lt;strong&gt;Page&lt;/strong&gt;, to make this easy on you. &lt;/li&gt;    &lt;li&gt;Load the query. &lt;/li&gt;    &lt;li&gt;In the completion callback, update the source collection with the new data. You may need to update the view as well if you queried for the &lt;strong&gt;TotalEntityCount&lt;/strong&gt; (used in paging).       &lt;br /&gt;&lt;/li&gt; &lt;/ol&gt;  &lt;h1&gt;Let’s See Some Code&lt;/h1&gt;  &lt;p&gt;At this point, it will probably be easiest to see the pieces working together in code. This sample shows a read-only &lt;strong&gt;DataGrid&lt;/strong&gt; where sorting and paging are both being done on the server. Here’s the &lt;strong&gt;DomainService &lt;/strong&gt;I’ll be working with. The only thing to note here is I had to override &lt;strong&gt;Count &lt;/strong&gt;to support paging since I’m deriving from the base &lt;strong&gt;DomainService&lt;/strong&gt;.&lt;/p&gt;  &lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;EnableClientAccess&lt;/span&gt;()]
&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleDomainService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;DomainService
&lt;/span&gt;  {
    &lt;span style="color: green"&gt;// Overridden to support paging over POCO entities.
    // If you're extending a derived DomainService
    // implementation this is already done for you.
    &lt;/span&gt;&lt;span style="color: blue"&gt;protected override int &lt;/span&gt;Count&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;T&amp;gt; query)
    {
      &lt;span style="color: blue"&gt;return &lt;/span&gt;query.Count();
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; GetAllEntities() {…}
  }&lt;/pre&gt;

&lt;p&gt;On the client, I’m using a stripped-down version of the MVVM pattern for simplicity. The view isn’t terribly interesting, but I’ll start there anyway. Both the &lt;strong&gt;DataGrid &lt;/strong&gt;and the &lt;strong&gt;DataPager &lt;/strong&gt;are bound to the view model.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl &lt;/span&gt;&lt;span style="color: red"&gt;...&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl.DataContext&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;vm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;SampleViewModel &lt;/span&gt;&lt;span style="color: blue"&gt;/&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl.DataContext&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    
    ...&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: blue"&gt;    &lt;br /&gt;    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Grid &lt;/span&gt;&lt;span style="color: red"&gt;...&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Border &lt;/span&gt;&lt;span style="color: red"&gt;...&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Grid&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
          ...&lt;/span&gt;&lt;span style="color: blue"&gt;
          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;dataGrid1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Row&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;0&amp;quot;
                        &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;CollectionView&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot;
                        &lt;/span&gt;&lt;span style="color: red"&gt;IsEnabled&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;IsGridEnabled&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot;
                        &lt;/span&gt;&lt;span style="color: red"&gt;IsReadOnly&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;True&amp;quot;/&amp;gt;
          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataPager &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;dataPager1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Row&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;1&amp;quot;
                         &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;CollectionView&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot;
                        &lt;/span&gt;&lt;span style="color: red"&gt;IsEnabled&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;IsGridEnabled&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot;/&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;Grid&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;Border&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;Grid&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/5554.image_5F00_72F7D980.png"&gt;&lt;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="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/0576.image_5F00_thumb_5F00_6BD89D08.png" width="410" height="173" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, we’ll get to the interesting piece, the view model. The two properties the view is bound to, &lt;strong&gt;CollectionView&lt;/strong&gt; and &lt;strong&gt;IsGridEnabled&lt;/strong&gt;, are the least interesting part so I’ll skip right past those to the constructor. This is where all the relationships get set up.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;SampleViewModel()
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._source = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(&lt;br /&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.SampleEntities);&lt;br /&gt;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._loader = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainCollectionViewLoader&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.LoadSampleEntities,
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.OnLoadSampleEntitiesCompleted);&lt;br /&gt;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._view = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainCollectionView&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(&lt;br /&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;._loader,&lt;br /&gt;      &lt;span style="color: blue"&gt;this&lt;/span&gt;._source);

    &lt;span style="color: green"&gt;// Swap out the loader for design-time scenarios
    &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;DesignerProperties&lt;/span&gt;.IsInDesignTool)
    {
      &lt;span style="color: #2b91af"&gt;DesignTimeLoader &lt;/span&gt;loader = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DesignTimeLoader&lt;/span&gt;();
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._view =&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainCollectionView&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt;(loader, loader.Source);
    }

&lt;span style="color: green"&gt;    // Go back to the first page when the sorting changes
    &lt;/span&gt;&lt;span style="color: #2b91af"&gt;INotifyCollectionChanged &lt;/span&gt;notifyingSortDescriptions =
      (&lt;span style="color: #2b91af"&gt;INotifyCollectionChanged&lt;/span&gt;)&lt;span style="color: blue"&gt;this&lt;/span&gt;.CollectionView.SortDescriptions;
    notifyingSortDescriptions.CollectionChanged +=
      (sender, e) =&amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.MoveToFirstPage();

    &lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;.CollectionView.DeferRefresh())
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.PageSize = 10;
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.MoveToFirstPage();
    }
  }&lt;/pre&gt;

&lt;p&gt;You can start to see things come together in the first couple of lines. The source is initialized with its backing &lt;strong&gt;EntitySet&lt;/strong&gt;, the loader is initialized with a couple of callbacks, and the view is initialized with references to the first two.&lt;/p&gt;

&lt;p&gt;The second things to notice is the block that adds design-time data. I’ve created a custom loader that returns a few sample entities and, at design time, construct a view using it instead. Not to get too sidetracked, but this snippet shows how easy it is to create a design-time loader.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DesignTimeLoader &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;CollectionViewLoader
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; source = &lt;span style="color: blue"&gt;new&lt;/span&gt;[] {…}

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; Source&lt;br /&gt;    {&lt;br /&gt;      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DesignTimeLoader&lt;/span&gt;.source; }&lt;br /&gt;    }

    &lt;span style="color: blue"&gt;public override bool &lt;/span&gt;CanLoad { &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return true&lt;/span&gt;; } }
    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;Load(&lt;span style="color: blue"&gt;object &lt;/span&gt;userState)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.OnLoadCompleted(&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AsyncCompletedEventArgs&lt;/span&gt;(&lt;span style="color: blue"&gt;null&lt;/span&gt;, &lt;span style="color: blue"&gt;false&lt;/span&gt;, userState));
    }
  }&lt;/pre&gt;

&lt;p&gt;Also, it’s worth noting there are plenty of other approaches to obtain sample data. I chose this one to highlight the simplicity of writing a custom loader and because it only required a few lines of code.&lt;/p&gt;

&lt;p&gt;Finally, there are two more things to look at near the end of the constructor. First, I’ve added an event handler to the &lt;strong&gt;SortDescriptions &lt;/strong&gt;collection. Now, every time the collection is updated with a new &lt;strong&gt;SortDescription&lt;/strong&gt;, I’ll make sure the table moves back to the first page. This isn’t a necessary addition, but I liked the behavior a little bit better. Once everything is set up, I make a couple updates to the view in a &lt;strong&gt;DeferRefresh &lt;/strong&gt;block. Any time you’re updating more than one view property and then reloading, it’s good practice to wrap it with a &lt;strong&gt;DeferRefresh&lt;/strong&gt;. This tells the view to forego all recalculations until you’ve finished your update. Upon exiting the using block, the &lt;strong&gt;Refresh&lt;/strong&gt; method will be invoked to update the view.&lt;/p&gt;

&lt;p&gt;The next piece we’ll look at are the two callbacks I passed into the constructor of the &lt;strong&gt;DomainCollectionViewLoader&lt;/strong&gt;. As far as RIA data loading goes, they’re both pretty standard.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LoadOperation&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; LoadSampleEntities()
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.IsGridEnabled = &lt;span style="color: blue"&gt;false&lt;/span&gt;;

    &lt;span style="color: blue"&gt;return this&lt;/span&gt;._context.Load(
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetAllEntitiesQuery().SortPageAndCount(&lt;span style="color: blue"&gt;this&lt;/span&gt;._view));
  }

&lt;span style="color: blue"&gt;  private void &lt;/span&gt;OnLoadSampleEntitiesCompleted(&lt;span style="color: #2b91af"&gt;LoadOperation&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; op)
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.IsGridEnabled = &lt;span style="color: blue"&gt;true&lt;/span&gt;;

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(op.HasError)
    {
      &lt;span style="color: green"&gt;// TODO: handle errors
      &lt;/span&gt;op.MarkErrorAsHandled();
    }
    &lt;span style="color: blue"&gt;else if &lt;/span&gt;(!op.IsCanceled)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._source.Source = op.Entities;

      &lt;span style="color: blue"&gt;if &lt;/span&gt;(op.TotalEntityCount != -1)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._view.SetTotalItemCount(op.TotalEntityCount);
      }
    }
  }&lt;/pre&gt;

&lt;p&gt;In the &lt;strong&gt;LoadSampleEntities &lt;/strong&gt;callback, the most interesting part is the &lt;strong&gt;SortPageAndCount &lt;/strong&gt;method. There are a number of &lt;strong&gt;EntityQuery&lt;/strong&gt; extensions included in the &lt;strong&gt;CollectionViewExtensions &lt;/strong&gt;class (&lt;strong&gt;Sort&lt;/strong&gt;, &lt;strong&gt;Page&lt;/strong&gt;, etc.) that understand how to apply the state of the view to the query. For instance, &lt;strong&gt;SortPageAndCount&lt;/strong&gt; orders according to the sort and group descriptions, skip/takes using the page index and count, and requests the total number of items if that has not already been determined.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;OnLoadSampleEntitiesCompleted&lt;/strong&gt; is also pretty simple. In the successful load block, the source is updated with the entities that were just loaded. Also, if the &lt;strong&gt;TotalEntityCount&lt;/strong&gt; was requested, it is used to update the view’s &lt;strong&gt;TotalItemCount (&lt;/strong&gt;which is used by the &lt;strong&gt;DataPager &lt;/strong&gt;to determine the total number of pages). Enabling and disabling the grid is not a required step, but I liked how it looked.&lt;/p&gt;

&lt;p&gt;Those are the significant bits of the sample. With a little setup and a couple callbacks, the &lt;strong&gt;DCV &lt;/strong&gt;makes server-side paging simple and obtainable. If you’re interested in seeing it run, here’s a link to the source.&lt;/p&gt;

&lt;h1&gt;&lt;iframe style="padding-bottom: 0px; background-color: #fcfcfc; padding-left: 0px; width: 98px; padding-right: 0px; height: 115px; padding-top: 0px" title="Preview" marginheight="0" src="http://cid-9da0e3aa6fc40e75.office.live.com/embedicon.aspx/.Public/DomainCollectionViewSample.sp1.zip" frameborder="0" marginwidth="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;/h1&gt;

&lt;h1&gt;Cool, I Want More&lt;/h1&gt;

&lt;p&gt;The &lt;strong&gt;DomainCollectionView &lt;/strong&gt;in &lt;strong&gt;Microsoft.Windows.Data.DomainServices &lt;/strong&gt;in the Toolkit supports the view functions of sorting, grouping, and paging. In addition, you can apply server-side filtering as part of your load callback (using a &lt;strong&gt;.Where&lt;/strong&gt; clause). These four pieces will be the core of nearly every query you put together on the client.&lt;/p&gt;

&lt;p&gt;Even with all that, there are a number of features that existed in the &lt;strong&gt;DomainDataSource &lt;/strong&gt;that could be pulled into the &lt;strong&gt;DCV&lt;/strong&gt;. I included an &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/09/17/my-thoughts-on-an-mvvm-friendly-domaindatasource.aspx"&gt;extensive list of features in this post&lt;/a&gt;. Let me know what’s missing and what you’d like added the most.&lt;/p&gt;

&lt;p&gt;As I mentioned earlier, this stuff is powerful and flexible to allows you to do cool stuff, but doesn’t work terribly hard to prevent you from doing things wrong. I’ve tried to provide some guidance with this post and the sample to keep things running smooth, but I’m sure you’ll take this in directions I haven’t anticipated. If you run into bugs or have questions about the best way to do things, send them my way (&lt;a href="http://blogs.msdn.com/b/kylemc/contact.aspx"&gt;Email Kyle&lt;/a&gt;).&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10099622" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="DomainDataSource" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/DomainDataSource/" /><category term="MVVM" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/MVVM/" /><category term="CollectionView" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/CollectionView/" /><category term="PDC10" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/PDC10/" /></entry><entry><title>Windows Azure Table Storage LINQ Support</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/22/windows-azure-table-storage-linq-support.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/11/22/windows-azure-table-storage-linq-support.aspx</id><published>2010-11-22T21:18:24Z</published><updated>2010-11-22T21:18:24Z</updated><content type="html">&lt;p&gt;Windows Azure Table storage has minimal support for LINQ queries. They support a few key operations, but a majority of the operators are unsupported. For RIA developers used to Entity Framework development, this is a significant difference. I wanted to put together this short post to draw your attention to &lt;a href="http://msdn.microsoft.com/en-us/library/dd135725.aspx"&gt;this link&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;When you use an unsupported operator, your application will fail at runtime. Typically the error is something along these lines.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;&lt;strong&gt;An error occurred while processing this request.          &lt;br /&gt;&lt;/strong&gt;at System.Data.Services.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)         &lt;br /&gt;at System.Data.Services.Client.DataServiceQuery`1.Execute()         &lt;br /&gt;at System.Data.Services.Client.DataServiceQuery`1.GetEnumerator()         &lt;br /&gt;at SampleCloudApplication.Web.MyDomainService.GetMyParentEntitiesWithChildren()         &lt;br /&gt;at …&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;with an &lt;strong&gt;InnerException&lt;/strong&gt; that looks like this.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; standalone=&amp;quot;yes&amp;quot;?&amp;gt;        &lt;br /&gt;&lt;/em&gt;&lt;em&gt;&amp;lt;error xmlns=&amp;quot;&lt;/em&gt;&lt;em&gt;http://schemas.microsoft.com/ado/2007/08/dataservices/metadata&amp;quot;&lt;/em&gt;&lt;em&gt;&amp;gt;        &lt;br /&gt;&amp;#160; &amp;lt;code&amp;gt;NotImplemented&amp;lt;/code&amp;gt;         &lt;br /&gt;&amp;#160; &amp;lt;message xml:lang=&amp;quot;en-US&amp;quot;&amp;gt;The requested operation is not implemented on the specified resource.&amp;lt;/message&amp;gt;         &lt;br /&gt;&amp;lt;/error&amp;gt;         &lt;br /&gt;&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;To solve this problem, you will need to bring the data to the mid-tier (where your &lt;strong&gt;DomainService&lt;/strong&gt; is running) using the &lt;strong&gt;.ToArray()&lt;/strong&gt; method. For example, “&lt;em&gt;return this.EntityContext.MyEntities.OrderBy(e =&amp;gt; e.MyProperty)&lt;/em&gt;” will fail but “&lt;em&gt;return this.EntityContext.MyEntities&lt;strong&gt;.ToArray()&lt;/strong&gt;.OrderBy(e =&amp;gt; e.MyProperty)&lt;/em&gt;” will succeed.&lt;/p&gt;  &lt;p&gt;The lack of support is an issue on the mid-tier, but has very little effect on the client. The base class, &lt;strong&gt;TableDomainService&lt;/strong&gt;, does a lot of work processing the query to correctly handle most things sent from the client. The one caveat to this is some &lt;strong&gt;.Where&lt;/strong&gt; filters are too complex to be processed. For example, most string operations like &lt;strong&gt;Contains &lt;/strong&gt;can’t be used and string equality is case sensitive (so be sure to set &lt;strong&gt;FilterDescriptor.IsCaseSensitive &lt;/strong&gt;to true when using &lt;strong&gt;DomainDataSource &lt;/strong&gt;filters). Just like the other unsupported operators, you can still implement this on the mid-tier using &lt;strong&gt;.ToArray() &lt;/strong&gt;before performing the complex &lt;strong&gt;.Where&lt;/strong&gt; query.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10095127" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Azure" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Azure/" /></entry><entry><title>Windows Azure Table PartitionKey Options for TableDomainServices</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/19/windows-azure-table-partitionkey-options-for-tabledomainservices.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/11/19/windows-azure-table-partitionkey-options-for-tabledomainservices.aspx</id><published>2010-11-19T16:48:36Z</published><updated>2010-11-19T16:48:36Z</updated><content type="html">&lt;p&gt;There are three primary strategies when it comes to partitioning entities across Windows Azure Table Storage. You can:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Put everything in the same partition &lt;/li&gt;    &lt;li&gt;Put everything in different partitions &lt;/li&gt;    &lt;li&gt;Put things in two or more specific partitions &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;A full discussion of these options can be found in the &lt;a href="http://go.microsoft.com/fwlink/?LinkId=153401"&gt;Table Storage whitepaper&lt;/a&gt;, but I’ll take some time in the post to show how each strategy can be implemented in your &lt;strong&gt;TableDomainService&lt;/strong&gt;. Each option hinges around the &lt;strong&gt;PartitionKey &lt;/strong&gt;value in your &lt;strong&gt;TableDomainService&lt;/strong&gt; and each of your entities.&lt;/p&gt;  &lt;h1&gt;The Single-PartitionKey Strategy&lt;/h1&gt;  &lt;p&gt;Using a single partition offers some attractive features like optimized querying and transactional updating. Since these fall most in line with existing domain service patterns, we chose to make this the default option in the &lt;strong&gt;TableDomainService&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;By default, &lt;strong&gt;TableDomainService.PartitionKey&lt;/strong&gt; returns the name of your domain service. This key is passed through to the &lt;strong&gt;EntityContext&lt;/strong&gt; which makes sure to put all your entities in the same partition. It also knows enough to only search for your entities in that partition by optimizing it’s query.&lt;/p&gt;  &lt;p&gt;In all three options, an entity’s &lt;strong&gt;PartitionKey &lt;/strong&gt;will not be set if you specify it before adding the entity to the &lt;strong&gt;EntityContext&lt;/strong&gt;. For this reason, it’s usually not a good idea to set the entity’s partition key explicitly when using this strategy.&lt;/p&gt;  &lt;h1&gt;The Unique-PartitionKey Strategy&lt;/h1&gt;  &lt;p&gt;Windows Azure will place entities with unique &lt;strong&gt;PartitionKeys &lt;/strong&gt;in separate partitions. Using this strategy will give you the maximum amount of scalability.&lt;/p&gt;  &lt;p&gt;To operate in this strategy, override &lt;strong&gt;TableDomainService.PartitionKey &lt;/strong&gt;and return null. This tells both your domain service and the &lt;strong&gt;EntityContext &lt;/strong&gt;they can’t assume a single key.&lt;/p&gt;  &lt;h1&gt;The Specific-PartitionKey Strategy&lt;/h1&gt;  &lt;p&gt;The final option allows you to balance the behaviors of the first two options in the way that best suits your application. You can improve scalability over using a single key while preserving transactional semantics over entities in the same partition.&lt;/p&gt;  &lt;p&gt;For this strategy, you’ll again need to override &lt;strong&gt;TableDomainService.PartitionKey &lt;/strong&gt;and return null. This time, however, you’ll also need to set every entity’s &lt;strong&gt;PartitionKey &lt;/strong&gt;explicitly. At this point, partitioning is fully under your control.&lt;/p&gt;  &lt;h1&gt;Which do I choose?&lt;/h1&gt;  &lt;p&gt;There’s no right or wrong strategy to use. The single-key strategy is the default because it should feel most familiar to developers. However, it doesn’t leverage the massive scaling potential of the cloud. It’s definitely a topic that deserves some up-front consideration before starting development. If nothing else, read through Section 3 of the &lt;a href="http://go.microsoft.com/fwlink/?LinkId=153401"&gt;whitepaper&lt;/a&gt; to familiarize yourself enough with partitioning to make an educated decision.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10093889" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Azure" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Azure/" /><category term="PDC10" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/PDC10/" /></entry><entry><title>Azure Table Storage Associations with RIA Services</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/19/azure-table-storage-associations-with-ria-services.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/11/19/azure-table-storage-associations-with-ria-services.aspx</id><published>2010-11-19T15:28:22Z</published><updated>2010-11-19T15:28:22Z</updated><content type="html">&lt;p&gt;For this post, I’ll assume you read my &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/11/01/ria-services-and-windows-azure-table-storage.aspx"&gt;intro to Windows Azure Table Storage&lt;/a&gt;. If not, take a second to read it. This time around I’m skipping past the contextualizing.&lt;/p&gt;  &lt;p&gt;In my first entry, I showed how to get a simple entity all the way from Table Storage to Silverlight. It was a necessary step, but you’ll need to know more to write an application. This time around, I want to walk through creating two related tables; one with a reference to the other. All the code here will be things you need to write for your Web Role project. This sample follows a three-step pattern you’ll find yourself using over and over as you write WCF RIA Services applications that use Windows Azure Table Storage.&lt;/p&gt;  &lt;h1&gt;Step 1: Define your Entities&lt;/h1&gt;  &lt;p&gt;We’ll stick to a couple simple entities with a parent-child relationship where the parent has a collection of children.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyParentEntity &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TableEntity
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;MyParentEntity()
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.Children = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyChildEntity&lt;/span&gt;&amp;gt;();
    }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;MyParentName { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    [&lt;span style="color: #2b91af"&gt;Include&lt;/span&gt;]
    [&lt;span style="color: #2b91af"&gt;Association&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Parent_Child&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;PartitionKey,RowKey&amp;quot;&lt;/span&gt;,&lt;br /&gt;      &lt;span style="color: #a31515"&gt;&amp;quot;ParentPartitionKey,ParentRowKey&amp;quot;&lt;/span&gt;)]
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyChildEntity&lt;/span&gt;&amp;gt; Children { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
  }

&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyChildEntity &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TableEntity
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;MyChildName { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    [&lt;span style="color: #2b91af"&gt;Association&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Parent_Child&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;ParentPartitionKey,ParentRowKey&amp;quot;&lt;/span&gt;,&lt;br /&gt;      &lt;span style="color: #a31515"&gt;&amp;quot;PartitionKey,RowKey&amp;quot;&lt;/span&gt;, IsForeignKey = &lt;span style="color: blue"&gt;true&lt;/span&gt;)]
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyParentEntity &lt;/span&gt;Parent { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;ParentPartitionKey { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;ParentRowKey { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
  }&lt;/pre&gt;

&lt;p&gt;In case you aren’t familiar with all the ins-and-outs of entity modeling, I’ll run down the details. As a point of reminder, all table storage entities are keyed by the &lt;strong&gt;PartitionKey &lt;/strong&gt;and &lt;strong&gt;RowKey &lt;/strong&gt;properties defined in the &lt;strong&gt;TableEntity &lt;/strong&gt;base class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MyParentEntity &lt;/strong&gt;has a collection of &lt;strong&gt;MyChildEntity &lt;/strong&gt;entities with two attributes; Include and Association. The &lt;strong&gt;IncludeAttribute&lt;/strong&gt; tells RIA Services that the collection of children can be included in serialization. It may feel like a redundant step, but it protects you from sending more data than you intend to. The &lt;strong&gt;AssociationAttribute &lt;/strong&gt;defines how the parent and child entities are related. On the parent, it is created using (1) the association name, (2) the key properties on the parent, and (3) the foreign-key properties on the child that point to the key properties on the parent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MyChildEntity &lt;/strong&gt;has three properties that it uses to reference the parent. The &lt;strong&gt;Parent &lt;/strong&gt;property contains the mirror image of the &lt;strong&gt;AssociationAttribute &lt;/strong&gt;found in &lt;strong&gt;MyParentEntity&lt;/strong&gt;. This time the association is created using (1) the association name, (2) the foreign-key properties on the child that point to the key properties on the parent, (3) the key properties on the parent, and (4) setting the &lt;strong&gt;IsForeignKey &lt;/strong&gt;property to true to identify the child entity as the one with the foreign-key properties.&lt;/p&gt;

&lt;p&gt;One important point to highlight with entity modeling is we can successfully use property types that are not supported by table storage. For example, since &lt;strong&gt;List&amp;lt;MyChildEntity&amp;gt; &lt;/strong&gt;on &lt;strong&gt;MyParentEntity &lt;/strong&gt;is not a supported type, the serializer will only send the &lt;strong&gt;PartitionKey&lt;/strong&gt;, &lt;strong&gt;RowKey&lt;/strong&gt;, &lt;strong&gt;Timestamp&lt;/strong&gt;, and &lt;strong&gt;MyParentName &lt;/strong&gt;to the database. The important inverse of this is that because the list is not stored in the database we will have to re-populate it when sending our parent entities to the client (more on that later).&lt;/p&gt;

&lt;h1&gt;Step 2: Define your EntityContext&lt;/h1&gt;

&lt;p&gt;This second step is fairly easy. We’ll need to create an entity context to use in our domain service. In this case we expose two properties; one for the parents and one for the children.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyEntityContext &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TableEntityContext
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;MyEntityContext() : 
      &lt;span style="color: blue"&gt;base&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;RoleEnvironment&lt;/span&gt;.&lt;br /&gt;             GetConfigurationSettingValue(&lt;span style="color: #a31515"&gt;&amp;quot;DataConnectionString&amp;quot;&lt;/span&gt;))
    {
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TableEntitySet&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyParentEntity&lt;/span&gt;&amp;gt; MyParentEntities
    {
      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return base&lt;/span&gt;.GetEntitySet&amp;lt;&lt;span style="color: #2b91af"&gt;MyParentEntity&lt;/span&gt;&amp;gt;(); }
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TableEntitySet&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyChildEntity&lt;/span&gt;&amp;gt; MyChildEntities
    {
      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return base&lt;/span&gt;.GetEntitySet&amp;lt;&lt;span style="color: #2b91af"&gt;MyChildEntity&lt;/span&gt;&amp;gt;(); }
    }
  }&lt;/pre&gt;

&lt;h1&gt;Step 3: Define your DomainService&lt;/h1&gt;

&lt;p&gt;In this last step we’ll create a domain service and add some logic to read and write to our tables.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;EnableClientAccess&lt;/span&gt;()]
&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyDomainService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TableDomainService&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyEntityContext&lt;/span&gt;&amp;gt;
  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyParentEntity&lt;/span&gt;&amp;gt; GetMyParentEntities()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.EntityContext.MyParentEntities;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyParentEntity&lt;/span&gt;&amp;gt; GetMyParentEntitiesWithChildren()
    {
      &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyParentEntity&lt;/span&gt;&amp;gt; parents =&lt;br /&gt;        &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyParentEntities;
      &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyChildEntity&lt;/span&gt;&amp;gt; children =&lt;br /&gt;        &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyChildEntities;

      &lt;span style="color: green"&gt;// Hook the association properties together
      &lt;/span&gt;&lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;MyParentEntity &lt;/span&gt;parent &lt;span style="color: blue"&gt;in &lt;/span&gt;parents)
      {
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;MyChildEntity &lt;/span&gt;child &lt;span style="color: blue"&gt;in &lt;/span&gt;children)
        {
          &lt;span style="color: blue"&gt;if &lt;/span&gt;((parent.PartitionKey == child.ParentPartitionKey) &amp;amp;&amp;amp;
              (parent.RowKey == child.ParentRowKey))
          {
            parent.Children.Add(child);
            child.Parent = parent;
          }
        }
      }

      &lt;span style="color: blue"&gt;return &lt;/span&gt;parents;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AddMyParentEntity(&lt;span style="color: #2b91af"&gt;MyParentEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyParentEntities.Add(entity);

      &lt;span style="color: green"&gt;// Make sure the child entities get the updated keys
      &lt;/span&gt;&lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;MyChildEntity &lt;/span&gt;child &lt;span style="color: blue"&gt;in &lt;/span&gt;entity.Children)
      {
        child.ParentPartitionKey = entity.PartitionKey;
        child.ParentRowKey = entity.RowKey;
      }
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;DeleteMyParentEntity(&lt;span style="color: #2b91af"&gt;MyParentEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyParentEntities.Delete(entity);

      &lt;span style="color: green"&gt;// Delete the child entities
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyChildEntity&lt;/span&gt;&amp;gt; children =&lt;br /&gt;        &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyChildEntities.Where(c =&amp;gt;&lt;br /&gt;          (c.ParentPartitionKey == entity.PartitionKey) &amp;amp;&amp;amp;&lt;br /&gt;          (c.ParentRowKey == entity.RowKey));

      &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;MyChildEntity &lt;/span&gt;child &lt;span style="color: blue"&gt;in &lt;/span&gt;children)
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyChildEntities.Delete(child);
      }
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;UpdateMyParentEntity(&lt;span style="color: #2b91af"&gt;MyParentEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyParentEntities.Update(entity);
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyChildEntity&lt;/span&gt;&amp;gt; GetMyChildEntities()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.EntityContext.MyChildEntities;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AddMyChildEntity(&lt;span style="color: #2b91af"&gt;MyChildEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyChildEntities.Add(entity);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;DeleteMyChildEntity(&lt;span style="color: #2b91af"&gt;MyChildEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyChildEntities.Delete(entity);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;UpdateMyChildEntity(&lt;span style="color: #2b91af"&gt;MyChildEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyChildEntities.Update(entity);
    }
  }&lt;/pre&gt;

&lt;p&gt;Starting with the simplest part, with this association we were able to use all the standard methods for reading, adding, updating, and deleting &lt;strong&gt;MyChildEntity&lt;/strong&gt;. Also, updating &lt;strong&gt;MyParentEntity&lt;/strong&gt; didn’t require any additional logic.&lt;/p&gt;

&lt;p&gt;In &lt;strong&gt;GetMyParentEntitiesWithChildren&lt;/strong&gt;, we’re filling in the relationship properties (like I alluded to earlier). We’re looking for parents and children where the association properties match and tying them together. After adding the parent to the entity set in &lt;strong&gt;AddMyParentEntity&lt;/strong&gt;, we’re iterating through all the children we’re adding as part of the same change set and updating their foreign-key properties. Finally, in &lt;strong&gt;DeleteMyParentEntity&lt;/strong&gt; we’re looking up all the children associated with the parent and deleting them.&lt;/p&gt;

&lt;p&gt;In this post I’ve shown the basics for creating related tables. Hopefully the samples highlight the kind of code required to work with table storage and gets you on your way to writing a cloud app.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10093838" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Azure" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Azure/" /><category term="PDC10" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/PDC10/" /></entry><entry><title>Silverlight TV: RIA Services Q &amp; A</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/12/silverlight-tv-52-ria-services-q-a.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/11/12/silverlight-tv-52-ria-services-q-a.aspx</id><published>2010-11-12T23:40:00Z</published><updated>2010-11-12T23:40:00Z</updated><content type="html">&lt;p&gt;John and I went through four questions we see frequently on the &lt;a href="http://forums.silverlight.net/forums/53.aspx"&gt;WCF RIA Services forum&lt;/a&gt;. Here’s our episode and some notes to go along with it.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://jpapa.me/sltv52"&gt;Silverlight TV: Episode 52&lt;/a&gt;&lt;/p&gt;  &lt;h1&gt;How do I investigate exceptions thrown from my DomainContext?&lt;/h1&gt;  &lt;p&gt;If you’ve been using RIA, you’ve undoubtedly seen this exception before.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;&lt;strong&gt;Load operation failed for query 'GetEmployees'. Exception of type 'System.ServiceModel.DomainServices.Client.DomainOperationException' was thrown.          &lt;br /&gt;&lt;/strong&gt;at System.ServiceModel.DomainServices.Client.WebDomainClient`1.EndQueryCore(IAsyncResult asyncResult)         &lt;br /&gt;at System.ServiceModel.DomainServices.Client.DomainClient.EndQuery(IAsyncResult asyncResult)         &lt;br /&gt;at System.ServiceModel.DomainServices.Client.DomainContext.CompleteLoad(IAsyncResult asyncResult)&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;A rough translation is “&lt;strong&gt;An exception was thrown in your DomainService while loading data.&lt;/strong&gt;” The problem is this exception is opaque and masks the real failure. What we need is some way to get the details about what is actually occurring.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 1: Temporarily set the customErrors mode to “Off”&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;In your web.config file, you can update the customErrors element.&lt;/p&gt;  &lt;pre class="code"&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;customErrors &lt;/span&gt;&lt;span style="color: red"&gt;mode&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;Off&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Option 2: Use fiddler to look at the response from the server&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There’s a lot to know about using fiddler, but I’ll keep this section sparse. I showed a little in the video and there are plenty of other examples.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.fiddler2.com/fiddler2/"&gt;Download Fiddler&lt;/a&gt; 

  &lt;br /&gt;&lt;a href="http://weblogs.asp.net/lorenh/archive/2008/01/10/tip-for-using-fiddler-on-localhost.aspx"&gt;Tips for using Fiddler on localhost&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Option 3: Override DomainService.OnError to inspect the error on the server&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are a number of reasons to override &lt;strong&gt;OnError &lt;/strong&gt;(logging, etc.) in your &lt;strong&gt;DomainServices&lt;/strong&gt;. One of the ways it can be useful is to give you a place to inspect errors before they’re sent back to the client.&lt;/p&gt;

&lt;p&gt;Using any of these method, we can get more useful information from the error.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;&lt;strong&gt;Load operation failed for query 'GetEmployees'. Object reference not set to an instance of an object. 
        &lt;br /&gt;&lt;/strong&gt;at SampleBusinessApplication.Web.EmployeeDomainService.GetEmployees() in …\EmployeeDomainService.cs:line 22 

      &lt;br /&gt;at GetEmployees(DomainService , Object[] ) 

      &lt;br /&gt;at System.ServiceModel.DomainServices.Server.ReflectionDomainServiceDescriptionProvider.ReflectionDomainOperationEntry.Invoke(DomainService domainService, Object[] parameters) 

      &lt;br /&gt;at System.ServiceModel.DomainServices.Server.DomainOperationEntry.Invoke(DomainService domainService, Object[] parameters, Int32&amp;amp; totalCount) 

      &lt;br /&gt;at System.ServiceModel.DomainServices.Server.DomainService.Query(QueryDescription queryDescription, IEnumerable`1&amp;amp; validationErrors, Int32&amp;amp; totalCount) 

      &lt;br /&gt;at System.ServiceModel.DomainServices.Hosting.QueryProcessor.Process[TEntity](DomainService domainService, DomainOperationEntry queryOperation, Object[] parameters, ServiceQuery serviceQuery, IEnumerable`1&amp;amp; validationErrors, Int32&amp;amp; totalCount) 

      &lt;br /&gt;at System.ServiceModel.DomainServices.Hosting.QueryOperationBehavior`1.QueryOperationInvoker.InvokeCore(Object instance, Object[] inputs, Object[]&amp;amp; outputs) &lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;How do I add a ComboBox to a DataGrid or DataForm?&lt;/h1&gt;

&lt;p&gt;I have a couple posts that cover these topics.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/11/02/silverlight-combobox-frequently-asked-questions.aspx"&gt;Silverlight ComboBox Frequently Asked Questions&lt;/a&gt; 

  &lt;br /&gt;&lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx"&gt;Silverlight ComboBox Sample for RIA Services&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;How do I change the default metadata added to an Entity when using the LinqToEntitiesDomainService?&lt;/h1&gt;

&lt;p&gt;It’s worth taking a second to provide context for this question. When you use the &lt;strong&gt;LinqToEntitiesDomainService&lt;/strong&gt;, RIA Services codegen will add some default metadata to your entity types. For instance, if we look at the generated code for our &lt;strong&gt;Employee&lt;/strong&gt; type, we can see the metadata on the &lt;strong&gt;FirstName &lt;/strong&gt;property.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;DataMember&lt;/span&gt;()]
  [&lt;span style="color: #2b91af"&gt;Required&lt;/span&gt;()]
  [&lt;span style="color: #2b91af"&gt;StringLength&lt;/span&gt;(10)]
&lt;span style="color: blue"&gt;  public string &lt;/span&gt;FirstName&lt;/pre&gt;

&lt;p&gt;It’s worth asking “Where do these value come from?” In short, the code generator is looking at the constraints you specified in your database and converting them into attributes. This helps reduce the number of exceptions you encounter when submitting your changes to the database.&lt;/p&gt;

&lt;p&gt;If you want to use something other than the default metadata you only need to specify it yourself. All the metadata you specify will override the codegen defaults. For instance, I can add some metadata to the &lt;strong&gt;Employee &lt;/strong&gt;type.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;  // The MetadataTypeAttribute identifies EmployeeMetadata as the class
  // that carries additional metadata for the Employee class.
&lt;/span&gt;  [&lt;span style="color: #2b91af"&gt;MetadataTypeAttribute&lt;/span&gt;(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Employee&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;EmployeeMetadata&lt;/span&gt;))]
&lt;span style="color: blue"&gt;  public partial class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Employee
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;internal sealed class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EmployeeMetadata
    &lt;/span&gt;{
      [&lt;span style="color: #2b91af"&gt;Required&lt;/span&gt;(AllowEmptyStrings = &lt;span style="color: blue"&gt;true&lt;/span&gt;,&lt;br /&gt;                ErrorMessage = &lt;span style="color: #a31515"&gt;&amp;quot;First name cannot be null.&amp;quot;&lt;/span&gt;)]
      &lt;span style="color: blue"&gt;public string &lt;/span&gt;FirstName { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    }
  }&lt;/pre&gt;

&lt;p&gt;When I do this, I can see the attribute I specified for the &lt;strong&gt;FirstName &lt;/strong&gt;property get generated in place of the default attribute.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;DataMember&lt;/span&gt;()]
  [&lt;span style="color: #2b91af"&gt;Required&lt;/span&gt;(AllowEmptyStrings=&lt;span style="color: blue"&gt;true&lt;/span&gt;,&lt;br /&gt;            ErrorMessage=&lt;span style="color: #a31515"&gt;&amp;quot;First name cannot be null.&amp;quot;&lt;/span&gt;)]
  [&lt;span style="color: #2b91af"&gt;StringLength&lt;/span&gt;(10)]
&lt;span style="color: blue"&gt;  public string &lt;/span&gt;FirstName&lt;/pre&gt;

&lt;h1&gt;How do I add cross-field validation to an Entity?&lt;/h1&gt;

&lt;p&gt;&lt;a href="http://jeffhandley.com/"&gt;Jeff&lt;/a&gt; has some great posts on validation. Here are the two that cover cross-field validation.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://jeffhandley.com/archive/2010/10/10/CrossFieldValidation.aspx"&gt;Cross-Field Validation&lt;/a&gt; 

  &lt;br /&gt;&lt;a href="http://jeffhandley.com/archive/2010/10/12/EntityLevelValidation.aspx"&gt;Entity-Level Validation&lt;/a&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Do you have the sample code?&lt;/h1&gt;

&lt;p&gt;Yep. Here it is.&lt;/p&gt;
&lt;iframe style="padding-bottom: 0px; background-color: #fcfcfc; padding-left: 0px; width: 98px; padding-right: 0px; height: 115px; padding-top: 0px" title="Preview" marginheight="0" src="http://cid-9da0e3aa6fc40e75.office.live.com/embedicon.aspx/.Public/SampleBusinessApplication.zip" frameborder="0" marginwidth="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10090418" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /></entry><entry><title>How to change the request timeout for WCF RIA Services</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/03/how-to-change-the-request-timeout-for-wcf-ria-services.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/11/03/how-to-change-the-request-timeout-for-wcf-ria-services.aspx</id><published>2010-11-03T23:52:12Z</published><updated>2010-11-03T23:52:12Z</updated><content type="html">&lt;p&gt;&lt;em&gt;My teammate, Jason Cooke, put together this great article on changing the timeout in RIA Services. Hope you find it helpful.&lt;/em&gt;&lt;/p&gt; &lt;h1&gt;Change Timeouts for WCF RIA Services&lt;/h1&gt; &lt;p&gt;WCF RIA Services specifies default timeouts for its endpoints, so you can be sure that all requests complete in a reasonable time, either with success, or a timeout error:  &lt;blockquote&gt; &lt;p&gt;The HTTP request to 'http://&amp;lt;&lt;i&gt;your URL&lt;/i&gt;&amp;gt;' has exceeded the allotted timeout. The time allotted to this operation may have been a portion of a longer timeout.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This error comes from the client's underlying WCF endpoint when a long-running request takes longer than the endpoint's SendTimeout, which is one minute by default.  &lt;p&gt;If you get this error, first consider restructuring the operation to enable it to finish sooner. For example, split the operation into multiple parts, or just kick off the operation and poll for completion.  &lt;p&gt;You don't need to change your design, though, because you can extend the client timeout values in RIA Services. The key is to get the endpoint for your domain service (as shown in &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/05/14/ria-services-authentication-out-of-browser.aspx"&gt;RIA Services Authentication Out-Of-Browser&lt;/a&gt;), and change the timeouts on the endpoint's binding.&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;  /// &amp;lt;summary&amp;gt;
  /// &lt;/span&gt;&lt;span style="color: green"&gt;Utility class for changing a domain context's WCF endpoint's&lt;br /&gt;  &lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;SendTimeout. &lt;/span&gt;
&lt;/span&gt;&lt;span style="color: gray"&gt;  /// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;  public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WcfTimeoutUtility
  {
    &lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color: green"&gt;Changes the WCF endpoint SendTimeout for the specified domain&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: green"&gt;&lt;span style="color: gray"&gt;/// &lt;/span&gt;&lt;span style="color: green"&gt;context. &lt;/span&gt;
    &lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="context"&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;The domain context to modify.&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="sendTimeout"&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;The new timeout value.&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
    &lt;/span&gt;&lt;span style="color: blue"&gt;public static void ChangeWcfSendTimeout(&lt;/span&gt;&lt;span style="color: #2b91af"&gt;DomainContext context, 
                                            TimeSpan sendTimeout)
    {
      PropertyInfo channelFactoryProperty =
        context.DomainClient.GetType().GetProperty(&lt;/span&gt;&lt;span style="color: #a31515"&gt;"ChannelFactory");
      &lt;/span&gt;&lt;span style="color: blue"&gt;if (channelFactoryProperty == null)
      {
        throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;InvalidOperationException(
          &lt;/span&gt;&lt;span style="color: #a31515"&gt;"There is no 'ChannelFactory' property on the DomainClient.");
      }

      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ChannelFactory factory = (ChannelFactory)
        channelFactoryProperty.GetValue(context.DomainClient, &lt;/span&gt;&lt;span style="color: blue"&gt;null);
      factory.Endpoint.Binding.SendTimeout = sendTimeout;
    }
  }&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Pass the domain context for the long-running operation and the new value for the send timeout to the ChangeWcfSendTimeout method, and you are good. You cannot change the binding after the endpoint is used, so the best place to call this method is in the domain context's partial OnCreated method, like this: &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;namespace SampleNamespace.Web.Services
{
  public partial class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyDomainContext
  {
    &lt;/span&gt;&lt;span style="color: blue"&gt;partial void OnCreated()
    {
      &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TimeSpan tenMinutes = &lt;/span&gt;&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TimeSpan(0, 10, 0);
      WcfTimeoutUtility.ChangeWcfSendTimeout(&lt;/span&gt;&lt;span style="color: blue"&gt;this, tenMinutes);
    }
  }
}&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;It’s important to make sure the namespaces match when implementing partial methods. The code in this sample should be included in your client project (here it has the name &lt;i&gt;SampleNamespace&lt;/i&gt;) and the domain service is &lt;i&gt;SampleNamespace.Web.Services.MyDomainService&lt;/i&gt;.&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10085794" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Timeouts" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Timeouts/" /></entry><entry><title>Using the Visual Studio Async CTP with RIA Services</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/02/using-the-visual-studio-async-ctp-with-ria-services.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/11/02/using-the-visual-studio-async-ctp-with-ria-services.aspx</id><published>2010-11-02T19:30:16Z</published><updated>2010-11-02T19:30:16Z</updated><content type="html">&lt;p&gt;I’ve been excited about this CTP for quite a while now and it’s great to finally have a chance to play with it. Way back in early RIA days we had a number of conversations with the TPL (Task Parallel Library) folks to see if we could use &lt;strong&gt;Task&amp;lt;T&amp;gt; &lt;/strong&gt;with RIA. We were never quite able to sort out the details so now that I’ve finally had a chance to use the two together I’m pretty excited.&lt;/p&gt;  &lt;h1&gt;Using Async on the Server&lt;/h1&gt;  &lt;p&gt;As soon as you &lt;a href="http://msdn.microsoft.com/en-us/vstudio/async.aspx"&gt;pick up the Async CTP&lt;/a&gt;, you get the idea it can be used everywhere. Asynchronous code becomes just as easy to write as synchronous code, and&amp;#160; the performance improvements it offers are tantalizing . It’s all still pretty new, but I’m guessing you’ll find reasons to use it in your &lt;strong&gt;DomainServices &lt;/strong&gt;pretty quickly.&lt;/p&gt;  &lt;p&gt;Right now, all &lt;strong&gt;DomainService&lt;/strong&gt; operations are synchronous, so it’s up to you to marry the two worlds. Luckily, &lt;strong&gt;Task&lt;/strong&gt; makes this pretty easy to accomplish. For instance, let’s say you want to use an asynchronous method that returns a &lt;strong&gt;Task&lt;/strong&gt;. To consume it synchronously, all you have to do is write a synchronous method that &lt;strong&gt;Waits &lt;/strong&gt;for the task to complete.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  using &lt;/span&gt;&lt;span style="color: #2b91af"&gt;RGB &lt;/span&gt;=&lt;br /&gt;    System.&lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleRedEntity&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;SampleGreenEntity&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;SampleBlueEntity&lt;/span&gt;&amp;gt;;

  [&lt;span style="color: #2b91af"&gt;EnableClientAccess&lt;/span&gt;()]
&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleDomainService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;DomainService
&lt;/span&gt;  {
&lt;span style="color: blue"&gt;    public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleRedEntity&lt;/span&gt;&amp;gt; GetRedEntities()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.GetEntitiesSync().Select(t =&amp;gt; t.Item1);
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleGreenEntity&lt;/span&gt;&amp;gt; GetGreenEntities()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.GetEntitiesSync().Select(t =&amp;gt; t.Item2);
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleBlueEntity&lt;/span&gt;&amp;gt; GetBlueEntities()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.GetEntitiesSync().Select(t =&amp;gt; t.Item3);
    }

    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;RGB&lt;/span&gt;[] GetEntitiesSync()
    {
      &lt;span style="color: #2b91af"&gt;Task&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RGB&lt;/span&gt;[]&amp;gt; task = &lt;span style="color: blue"&gt;this&lt;/span&gt;.GetEntitiesAsync();
      task.Wait();
&lt;pre class="code"&gt;      &lt;span style="color: blue"&gt;return &lt;/span&gt;task.Result;
    }

    &lt;span style="color: blue"&gt;private async &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Task&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;RGB&lt;/span&gt;[]&amp;gt; GetEntitiesAsync() {…}
  }&lt;/pre&gt;&lt;/pre&gt;

&lt;h1&gt;Using Async in Silverlight&lt;/h1&gt;

&lt;p&gt;In Silverlight, using Async becomes a little more interesting for two reasons; (1) You’re already forced to use async, and (2) RIA Services provides an async model similar to &lt;strong&gt;Task&amp;lt;T&amp;gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;My first step in integrating the CTP with RIA was to create a simple extension method to consume our RIA operations (&lt;strong&gt;LoadOperation&amp;lt;T&amp;gt;&lt;/strong&gt;, etc.) as &lt;strong&gt;Tasks&lt;/strong&gt;. I played around with different variations, but in the end it turned out to be quite simple.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OperationExtensions
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Task&lt;/span&gt;&amp;lt;T&amp;gt; AsTask&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T operation)&lt;br /&gt;      &lt;span style="color: blue"&gt;where &lt;/span&gt;T : &lt;span style="color: #2b91af"&gt;OperationBase
    &lt;/span&gt;{
      &lt;span style="color: #2b91af"&gt;TaskCompletionSource&lt;/span&gt;&amp;lt;T&amp;gt; tcs =&lt;br /&gt;        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskCompletionSource&lt;/span&gt;&amp;lt;T&amp;gt;(operation.UserState);

      operation.Completed += (sender, e) =&amp;gt;
      {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(operation.HasError &amp;amp;&amp;amp; !operation.IsErrorHandled)
        {
          tcs.TrySetException(operation.Error);
          operation.MarkErrorAsHandled();
        }
        &lt;span style="color: blue"&gt;else if &lt;/span&gt;(operation.IsCanceled)
        {
          tcs.TrySetCanceled();
        }
        &lt;span style="color: blue"&gt;else
        &lt;/span&gt;{
          tcs.TrySetResult(operation);
        }
      };

      &lt;span style="color: blue"&gt;return &lt;/span&gt;tcs.Task;
    }
  }&lt;/pre&gt;

&lt;p&gt;To give some context on the next part, here’s the UI I’m using. It’s just a few &lt;strong&gt;DataGrids&lt;/strong&gt; bound to the &lt;strong&gt;EntitySets &lt;/strong&gt;on my &lt;strong&gt;DomainContext&lt;/strong&gt;. I’ve also included a &lt;strong&gt;BusyIndicator &lt;/strong&gt;to spin while I’m loading everything.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl &lt;/span&gt;&lt;span style="color: red"&gt;…&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;web&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;SampleDomainContext &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Key&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;sampleDomainContext&amp;quot; /&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Grid &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;LayoutRoot&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Background&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;White&amp;quot;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;BusyIndicator &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;busyIndicator&amp;quot;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Reds&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;2&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Bold&amp;quot;/&amp;gt;

          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;redsDataGrid&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;IsReadOnly&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;True&amp;quot;
            &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;SampleRedEntities&lt;/span&gt;&lt;span style="color: blue"&gt;,&lt;br /&gt;                         &lt;/span&gt;&lt;span style="color: blue"&gt; &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;sampleDomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;/&amp;gt;

          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Greens&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;2&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Bold&amp;quot;/&amp;gt;

          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;greensDataGrid&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;IsReadOnly&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;True&amp;quot;
            &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;SampleGreenEntities&lt;/span&gt;&lt;span style="color: blue"&gt;,&lt;br /&gt;                         &lt;/span&gt;&lt;span style="color: blue"&gt; &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;sampleDomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;/&amp;gt;

          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Blues&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;2&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Bold&amp;quot;/&amp;gt;

          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;bluesDataGrid&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;IsReadOnly&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;True&amp;quot;
            &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;SampleBlueEntities&lt;/span&gt;&lt;span style="color: blue"&gt;,&lt;br /&gt;                          &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;sampleDomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;/&amp;gt;

        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;BusyIndicator&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;Grid&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Finally, here’s where I get to do all the neat stuff.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public partial class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MainPage &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;UserControl
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleDomainContext &lt;/span&gt;_context;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;MainPage()
    {
      InitializeComponent(); ;

      &lt;span style="color: blue"&gt;this&lt;/span&gt;._context =&lt;br /&gt;       (&lt;span style="color: #2b91af"&gt;SampleDomainContext&lt;/span&gt;)&lt;span style="color: blue"&gt;this&lt;/span&gt;.Resources[&lt;span style="color: #a31515"&gt;&amp;quot;sampleDomainContext&amp;quot;&lt;/span&gt;];

      &lt;span style="color: blue"&gt;this&lt;/span&gt;.InitializeData();
    }

    &lt;span style="color: blue"&gt;private async void &lt;/span&gt;InitializeData()
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.busyIndicator.IsBusy = &lt;span style="color: blue"&gt;true&lt;/span&gt;;

      &lt;span style="color: green"&gt;// Serial
      &lt;/span&gt;&lt;span style="color: blue"&gt;await this&lt;/span&gt;._context.Load(&lt;br /&gt;              &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetRedEntitiesQuery()).AsTask();
      &lt;span style="color: blue"&gt;await this&lt;/span&gt;._context.Load(&lt;br /&gt;              &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetGreenEntitiesQuery()).AsTask();
      &lt;span style="color: blue"&gt;await this&lt;/span&gt;._context.Load(&lt;br /&gt;              &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetBlueEntitiesQuery()).AsTask();

      &lt;span style="color: green"&gt;// Parallel
      &lt;/span&gt;&lt;span style="color: blue"&gt;await &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskEx&lt;/span&gt;.WhenAll(
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.Load(&lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetRedEntitiesQuery()).AsTask(),
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.Load(&lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetGreenEntitiesQuery()).AsTask(),
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.Load(&lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetBlueEntitiesQuery()).AsTask()
        );

      &lt;span style="color: blue"&gt;this&lt;/span&gt;.busyIndicator.IsBusy = &lt;span style="color: blue"&gt;false&lt;/span&gt;;
    }
  }&lt;/pre&gt;

&lt;p&gt;I’ve made the &lt;strong&gt;InitializeData &lt;/strong&gt;method async so it starts to run in the constructor, but finishes well after. As you can see, I set the busy indicator to busy before loading data and then ,when all the data is successfully loaded, I set it to idle again. Also, I’ve shown two approaches for invoking multiple queries. First, I show how &lt;strong&gt;Loads &lt;/strong&gt;can be invoked serially such that each is only started after the previous one completes. Next, I show how all the &lt;strong&gt;Loads&lt;/strong&gt; can be run in parallel. The &lt;strong&gt;WhenAll &lt;/strong&gt;method will ensure all the loads have completed successfully before I set my busy indicator to idle.&lt;/p&gt;

&lt;p&gt;This is just a small sample of the things you can do with the Async CTP, but I’m already a big fan. Hopefully you find this helpful, and please let me know if you have any questions.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10084983" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="PDC10" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/PDC10/" /></entry><entry><title>Silverlight ComboBox Frequently Asked Questions</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/02/silverlight-combobox-frequently-asked-questions.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/11/02/silverlight-combobox-frequently-asked-questions.aspx</id><published>2010-11-02T15:20:37Z</published><updated>2010-11-02T15:20:37Z</updated><content type="html">&lt;p&gt;I’ve wanted to do a follow up to &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx"&gt;my original ComboBox post&lt;/a&gt; for a while now. I answered a number of the questions throughout the comments, but I thought I’d gather all the answers up and add some nice code samples. Hope this helps.&lt;/p&gt;  &lt;h1&gt;How do I use a ComboBox in a DataForm?&lt;/h1&gt;  &lt;p&gt;For most of the scenarios where you’ll be using a &lt;strong&gt;ComboBox &lt;/strong&gt;in a &lt;strong&gt;DataForm&lt;/strong&gt; a static data source will be sufficient. In our case, let’s assume we’re pulling a list of options from the server. We’ll add a method to our &lt;strong&gt;DomainService &lt;/strong&gt;to get these items.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; GetCountryStrings()
  {
    &lt;span style="color: blue"&gt;return new&lt;/span&gt;[] { &lt;span style="color: #a31515"&gt;&amp;quot;UK&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;USA&amp;quot; &lt;/span&gt;};
  }&lt;/pre&gt;

&lt;p&gt;Our next step is to create a data source to call the method. We can add the following snippet to our Silverlight page.&lt;/p&gt;

&lt;pre class="code"&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;navigation&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Page.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;web&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;EmployeeDomainContext &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Key&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;employeeDomainContext&amp;quot;/&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ex&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;ComboBoxDataSource &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Key&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;countryDataSource&amp;quot;&lt;br /&gt;      &lt;/span&gt;&lt;span style="color: red"&gt;DomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;employeeDomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot;&lt;br /&gt;      &lt;/span&gt;&lt;span style="color: red"&gt;OperationName&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;GetCountryStrings&amp;quot; /&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;navigation&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Page.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;It’s worth noting that we’ve made both the &lt;strong&gt;DomainContext &lt;/strong&gt;and &lt;strong&gt;ComboBoxDataSource&lt;/strong&gt; resources. This will allow us to share the &lt;strong&gt;DomainContext&lt;/strong&gt; with the data source we use to load our data. Specifically, when we add a &lt;strong&gt;DomainDataSource&lt;/strong&gt; that loads the entities, we’ll make sure that is uses the &lt;strong&gt;DomainContext&lt;/strong&gt; declared in the resources.&lt;/p&gt;

&lt;pre class="code"&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;dds&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DomainDataSource &lt;/span&gt;&lt;span style="color: red"&gt;AutoLoad&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;True&amp;quot;&lt;br /&gt;    &lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;employeeDomainDataSource&amp;quot;&lt;/span&gt;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: red"&gt;DomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;employeeDomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: red"&gt;    QueryName&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;GetEmployeesQuery&amp;quot; /&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The final step in using a &lt;strong&gt;ComboBox &lt;/strong&gt;within a &lt;strong&gt;DataForm &lt;/strong&gt;is to hook everything together within a &lt;strong&gt;DataField&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataForm &lt;/span&gt;&lt;span style="color: red"&gt;AutoGenerateFields&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;False&amp;quot;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;ElementName&lt;/span&gt;&lt;span style="color: blue"&gt;=employeeDomainDataSource, &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Data}&amp;quot;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;employeeDataForm&amp;quot;&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataField &lt;/span&gt;&lt;span style="color: red"&gt;Label&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Title&amp;quot;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBox &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Title, &lt;/span&gt;&lt;span style="color: red"&gt;Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=TwoWay}&amp;quot; /&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataField&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataField &lt;/span&gt;&lt;span style="color: red"&gt;Label&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Country&amp;quot;&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ComboBox &lt;br /&gt;          &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;br /&gt;            &amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Data&lt;/span&gt;&lt;span style="color: blue"&gt;, &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;countryDataSource&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;
          &lt;/span&gt;&lt;span style="color: red"&gt;SelectedItem&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Country&lt;/span&gt;&lt;span style="color: blue"&gt;, &lt;/span&gt;&lt;span style="color: red"&gt;Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=TwoWay}&amp;quot;
          &lt;/span&gt;&lt;span style="color: red"&gt;ex&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ComboBox.Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;AsyncEager&amp;quot; /&amp;gt;                            
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataField&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;                    
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataForm&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;In this case, we’ve bound the &lt;strong&gt;ItemsSource &lt;/strong&gt;to our data source, two-way bound the &lt;strong&gt;SelectedItem &lt;/strong&gt;to a property on the entity, and set the &lt;strong&gt;ComboBox&lt;/strong&gt; mode to &lt;strong&gt;AsyncEager&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It’s also worth noting we’ve set the &lt;strong&gt;DataField &lt;/strong&gt;label to “Country”. If we were using the &lt;strong&gt;Display &lt;/strong&gt;or &lt;strong&gt;Required &lt;/strong&gt;attributes, we could set &lt;strong&gt;PropertyPath &lt;/strong&gt;instead to ensure the metadata was applied to the &lt;strong&gt;DataField &lt;/strong&gt;correctly.&lt;/p&gt;

&lt;p&gt;Another point to highlight is I’m not using &lt;strong&gt;ElementName &lt;/strong&gt;binding. It’s rarely explained, but &lt;strong&gt;ElementName &lt;/strong&gt;binding has some limitations when used in templates (there are good reasons for this, but I won’t go into them here). It’s best to consider templates as a barrier for &lt;strong&gt;ElementName &lt;/strong&gt;binding. Controls inside the template can bind to other controls inside the template. Controls outside the template can bind to other controls outside the template. However, controls inside the template cannot use &lt;strong&gt;ElementName &lt;/strong&gt;binding to bind to controls outside the template (and vice-versa). This is another reason we chose to make the data source a resource above.&lt;/p&gt;

&lt;h1&gt;How do I use a ComboBox in a DataGrid?&lt;/h1&gt;

&lt;p&gt;Using a &lt;strong&gt;ComboBox&lt;/strong&gt; in a &lt;strong&gt;DataGrid&lt;/strong&gt; follows nearly the same pattern as above. First, define an operation on your &lt;strong&gt;DomainService &lt;/strong&gt;to return the items&lt;strong&gt;. &lt;/strong&gt;Second, define a data source to load the items; sharing a &lt;strong&gt;DomainContext &lt;/strong&gt;as necessary. Finally, hook everything together within a &lt;strong&gt;DataGridTemplateColumn&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid &lt;/span&gt;&lt;span style="color: red"&gt;AutoGenerateColumns&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;False&amp;quot;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;ElementName&lt;/span&gt;&lt;span style="color: blue"&gt;=employeeDomainDataSource, &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Data}&amp;quot;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;employeeDataGrid&amp;quot;&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid.Columns&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGridTextColumn &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;titleColumn&amp;quot;&lt;br /&gt;        &lt;/span&gt;&lt;span style="color: red"&gt;Binding&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Title}&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Header&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Title&amp;quot; /&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGridTemplateColumn &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;countryColumn&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Header&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Country&amp;quot;&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGridTemplateColumn.CellEditingTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ComboBox&lt;br /&gt;              &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;br /&gt;                &amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Data&lt;/span&gt;&lt;span style="color: blue"&gt;, &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;countryDataSource&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;
              &lt;/span&gt;&lt;span style="color: red"&gt;SelectedItem&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Country&lt;/span&gt;&lt;span style="color: blue"&gt;, &lt;/span&gt;&lt;span style="color: red"&gt;Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=TwoWay}&amp;quot;
              &lt;/span&gt;&lt;span style="color: red"&gt;ex&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ComboBox.Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;AsyncEager&amp;quot; /&amp;gt;
          &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGridTemplateColumn.CellEditingTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGridTemplateColumn.CellTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Country}&amp;quot;&lt;/span&gt;&lt;span style="color: blue"&gt;/&amp;gt;
          &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGridTemplateColumn.CellTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGridTemplateColumn&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid.Columns&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;As above, we’ve bound the &lt;strong&gt;ItemsSource &lt;/strong&gt;to our data source, two-way bound the &lt;strong&gt;SelectedItem &lt;/strong&gt;to a property on the entity, and set the &lt;strong&gt;ComboBox&lt;/strong&gt; mode to &lt;strong&gt;AsyncEager&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Additionally, you might notice we’ve created two templates. We need to set up the &lt;strong&gt;CellEditingTemplate &lt;/strong&gt;to use a &lt;strong&gt;ComboBox&lt;/strong&gt;, but the &lt;strong&gt;CellTemplate &lt;/strong&gt;used for reading the value can have anything in it. In this case it was easiest to display the value using a &lt;strong&gt;TextBlock&lt;/strong&gt;.&lt;/p&gt;

&lt;h1&gt;What are the modes Async and AsyncEager and am I using them correctly?&lt;/h1&gt;

&lt;p&gt;There have been a number of questions along the lines of &lt;strong&gt;“I only see the selected item in my pick list. Why aren’t the items loading correctly?”&lt;/strong&gt; In nearly every case, the inquirer is using the &lt;strong&gt;AsyncEager &lt;/strong&gt;mode and it is masking the underlying failure (which tends to be the &lt;strong&gt;SelectedItem &lt;/strong&gt;isn’t available in the &lt;strong&gt;ItemsSource)&lt;/strong&gt;. I figured I’d take a second to explain the modes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Async &lt;/strong&gt;mode makes sure the &lt;strong&gt;ComboBox&lt;/strong&gt;’s &lt;strong&gt;SelectedItem&lt;/strong&gt; will be reselected any time the &lt;strong&gt;ItemsSource &lt;/strong&gt;changes. By default the control will stop binding any time the &lt;strong&gt;SelectedItem &lt;/strong&gt;is not in the &lt;strong&gt;Items&lt;/strong&gt;. This can be inconvenient in scenarios where you’re loading the &lt;strong&gt;ItemsSource &lt;/strong&gt;asynchronously as the burden of correctly ordering the load completion and then establishing the binding always falls on you. With the &lt;strong&gt;Async &lt;/strong&gt;mode, the &lt;strong&gt;ItemsSource &lt;/strong&gt;can be loaded before or after the binding is created and the &lt;strong&gt;ComboBox &lt;/strong&gt;will work fine regardless of the order. For this mode, the &lt;strong&gt;ComboBox &lt;/strong&gt;will remain blank with an empty pick list until the &lt;strong&gt;ItemsSource &lt;/strong&gt;is loaded.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AsyncEager &lt;/strong&gt;mode goes one step farther then &lt;strong&gt;Async &lt;/strong&gt;mode to improve the UI experience by addressing the selection ‘flicker’ that can occur when the &lt;strong&gt;ItemsSource &lt;/strong&gt;is loaded asynchronously. If the &lt;strong&gt;SelectedItem &lt;/strong&gt;is not in the &lt;strong&gt;ItemsSource&lt;/strong&gt;, the &lt;strong&gt;ItemsSource &lt;/strong&gt;will be replaced with a single-item list containing only the &lt;strong&gt;SelectedItem&lt;/strong&gt;. The assumption is that in the near future, the &lt;strong&gt;ItemsSource&lt;/strong&gt; will be updated with a list that &lt;u&gt;does&lt;/u&gt; contain the &lt;strong&gt;SelectedItem&lt;/strong&gt;. In this mode, the &lt;strong&gt;ComboBox &lt;/strong&gt;will have a single-item pick list containing only the &lt;strong&gt;SelectedItem &lt;/strong&gt;until the &lt;strong&gt;ItemsSource &lt;/strong&gt;is loaded.&lt;/p&gt;

&lt;p&gt;In both modes, it is important to note that equality is often based on referential comparison. Entities loaded in different &lt;strong&gt;DomainContext&lt;/strong&gt; instances are &lt;u&gt;not&lt;/u&gt; referentially equal. If you load the &lt;strong&gt;ItemsSource &lt;/strong&gt;in one context and the &lt;strong&gt;SelectedItem &lt;/strong&gt;in another, the entity will not be selected correctly in the &lt;strong&gt;ComboBox&lt;/strong&gt;. For this reason (among others) it is important to share the &lt;strong&gt;DomainContext &lt;/strong&gt;when loading the &lt;strong&gt;ItemsSource&lt;/strong&gt; (see &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx"&gt;my last post for an example&lt;/a&gt;).&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10084766" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="DomainDataSource" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/DomainDataSource/" /><category term="ComboBox" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/ComboBox/" /></entry><entry><title>RIA Services and Windows Azure Table Storage</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/11/01/ria-services-and-windows-azure-table-storage.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/11/01/ria-services-and-windows-azure-table-storage.aspx</id><published>2010-11-01T21:40:52Z</published><updated>2010-11-01T21:40:52Z</updated><content type="html">&lt;p&gt;We worked right up to the deadline, but I’m happy to say we got a preview of RIA support for Windows Azure Table Storage into the &lt;a href="http://www.silverlight.net/getstarted/riaservices/"&gt;October Toolkit release&lt;/a&gt; (that coincides with the &lt;a href="http://www.silverlight.net/getstarted/riaservices/"&gt;SP1 Beta release&lt;/a&gt;). You could integrate with table storage previously, but our goal was to make using it as simple as possible. With all the great new Azure features coming down the pipe (announced at &lt;a href="http://www.microsoftpdc.com"&gt;PDC10&lt;/a&gt;), we want to give you first-class experience using table storage with WCF RIA Services.&lt;/p&gt;  &lt;h1&gt;Where to Start?&lt;/h1&gt;  &lt;p&gt;If you’re new to Windows Azure (and to tell the truth, we all fall in that bucket) then you need to start with &lt;a href="http://blogs.msdn.com/jnak"&gt;Jim Nakashima’s blog&lt;/a&gt;. I always refer back to it, and it’s proved an invaluable resource. For an introduction to table storage, &lt;a href="http://blogs.msdn.com/b/jnak/archive/2010/01/06/walkthrough-windows-azure-table-storage-nov-2009-and-later.aspx"&gt;this post is a good start&lt;/a&gt;. The difference between Jim’s approach and what I’ll show here are the steps we take to integrate with existing &lt;strong&gt;DomainService &lt;/strong&gt;patterns. Without further introduction, I’ll jump into the things you need to know to get the most out of our &lt;strong&gt;Microsoft.ServiceModel.DomainServices.WindowsAzure &lt;/strong&gt;assembly preview.&lt;/p&gt;  &lt;h1&gt;Let’s Get a Project Set Up&lt;/h1&gt;  &lt;p&gt;We’ll use this section to go step-by-step and set up a clean Silverlight project ready for Azure. If you’re interested in starting with the Business Application Template instead, take a look at &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/06/09/ria-and-windows-azure.aspx"&gt;this introductory post&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;1) Make sure you have the latest Windows Azure SDK installed (&lt;a title="http://www.microsoft.com/windowsazure/" href="http://www.microsoft.com/windowsazure/"&gt;http://www.microsoft.com/windowsazure/&lt;/a&gt;)&lt;/p&gt;  &lt;p&gt;2) Open Visual Studio and create a new Silverlight project with WCF RIA Services enabled&lt;/p&gt;  &lt;p&gt;3) Add a Windows Azure Cloud Service project to your solution. When the New Cloud Service Wizard pops up, select ‘Ok’.&lt;/p&gt;  &lt;p&gt;4) In your Cloud Service project, Add a Web Role Project from your solution.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/4370.image_5F00_66EB68BF.png"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="image" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/8182.image_5F00_thumb_5F00_2DA4DBFD.png" width="400" height="148" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;In the Wizard, select your Web Application project.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/2728.image_5F00_1B5C153B.png"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="image" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/5556.image_5F00_thumb_5F00_422A2B7B.png" width="240" height="77" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;5) The next step is to add the RIA Services reference you need to your Web Application project. My favorite way to do this is to add an empty &lt;strong&gt;DomainService&lt;/strong&gt; using the wizard and then immediately delete it.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/0268.image_5F00_5406BF48.png"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="image" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/3005.image_5F00_thumb_5F00_7AD4D588.png" width="300" height="231" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;6) Finally, we need to make sure our application can be deployed by setting the RIA Services references to ‘Copy Local = True’.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/2248.image_5F00_0CB16956.png"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="image" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/1665.image_5F00_thumb_5F00_337F7F96.png" width="500" height="123" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;In your web project, make sure to update the reference to both &lt;strong&gt;System.ServiceModel.DomainServices.Hosting&lt;/strong&gt; and &lt;strong&gt;System.ServiceModel.DomainServices.Server&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;7) Now that we’re ready to go, let’s add the references we’ll need to work with Windows Azure. Add references to &lt;strong&gt;System.Data.Services.Client&lt;/strong&gt;, &lt;strong&gt;Microsoft.WindowsAzure.ServiceRuntime&lt;/strong&gt;, &lt;strong&gt;Microsoft.WindowsAzure.StorageClient&lt;/strong&gt;, and &lt;strong&gt;Microsoft.ServiceModel.DomainServices.WindowsAzure &lt;/strong&gt;to your Web Application project.&lt;/p&gt;  &lt;p&gt;You’ll also need to set Copy Local to True for both &lt;strong&gt;Microsoft.WindowsAzure.StorageClient&lt;/strong&gt; and &lt;strong&gt;Microsoft.ServiceModel.DomainServices.WindowsAzure&lt;/strong&gt;.&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h1&gt;A Windows Azure Entity&lt;/h1&gt;  &lt;p&gt;Now that we have a project set up, we can focus on using Windows Azure Table Storage. Windows Azure provides queryable structured storage. You can create an unlimited number of tables which in turn can have an unlimited number of entities. There are a few constraints to the structure, but it’s pretty flexible (for more information take a look at the &lt;a href="http://go.microsoft.com/fwlink/?LinkId=153401"&gt;Table Storage whitepaper&lt;/a&gt;). One hard rule is that every entity must have three properties, the &lt;strong&gt;PartitionKey&lt;/strong&gt;, the &lt;strong&gt;RowKey&lt;/strong&gt; and the &lt;strong&gt;Timestamp&lt;/strong&gt;. Together these form a unique key for an entity. Additionally, query results are returned sorted by &lt;strong&gt;PartitionKey&lt;/strong&gt; and then by &lt;strong&gt;RowKey&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;To make it as simple as possible to define entities, we’ve provided the base class &lt;strong&gt;TableEntity&lt;/strong&gt; that includes these properties. The first step to working with table storage is to define your entity. For this post, we’re starting from scratch and the properties on our entity will define the schema of our table.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyEntity &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TableEntity
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;MyName { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
  }&lt;/pre&gt;

&lt;p&gt;With this small snippet, I’ve defined an entity with four properties; &lt;strong&gt;PartitionKey&lt;/strong&gt;, &lt;strong&gt;RowKey&lt;/strong&gt;, &lt;strong&gt;Timestamp&lt;/strong&gt;, and &lt;strong&gt;MyName&lt;/strong&gt;. Now with an entity in hand, we’ll look at defining a context for working with table storage.&lt;/p&gt;

&lt;h1&gt;A Context for Table Storage&lt;/h1&gt;

&lt;p&gt;The second step for getting running with Windows Azure Table Storage is to create a context the &lt;strong&gt;DomainService &lt;/strong&gt;can use. We wanted to create a familiar feel for developers used to working with RIA, so we’ve provided you with two types &lt;strong&gt;TableEntitySet&lt;/strong&gt; and &lt;strong&gt;TableEntityContext&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyEntityContext &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TableEntityContext
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;MyEntityContext() : 
      &lt;span style="color: blue"&gt;base&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;RoleEnvironment&lt;/span&gt;.&lt;br /&gt;             GetConfigurationSettingValue(&lt;span style="color: #a31515"&gt;&amp;quot;DataConnectionString&amp;quot;&lt;/span&gt;))
    {
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TableEntitySet&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyEntity&lt;/span&gt;&amp;gt; MyEntities
    {
      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return base&lt;/span&gt;.GetEntitySet&amp;lt;&lt;span style="color: #2b91af"&gt;MyEntity&lt;/span&gt;&amp;gt;(); }
    }
  }&lt;/pre&gt;

&lt;p&gt;In the snippet above, we reference a connection string specified in the Web Role configuration. To add a connection string, open the Web Role properties.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/7026.image_5F00_7349661B.png"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="image" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/8105.image_5F00_thumb_5F00_0525F9E9.png" width="400" height="152" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/1346.image_5F00_72DD3326.png"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="image" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/0763.image_5F00_thumb_5F00_60946C64.png" width="450" height="124" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, with a small snippet of code, we’re ready to write our &lt;strong&gt;DomainService&lt;/strong&gt;.&lt;/p&gt;

&lt;h1&gt;A Table Storage Domain Service&lt;/h1&gt;

&lt;p&gt;With our entity defined and our context ready, we can begin to write a &lt;strong&gt;DomainService&lt;/strong&gt;. Once again, we’ve provided you with a base class to start with. The &lt;strong&gt;TableDomainService &lt;/strong&gt;takes care of a lot of the table-storage-specific concerns so you can concentrate on your business logic.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;EnableClientAccess&lt;/span&gt;]
&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyDomainService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TableDomainService&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyEntityContext&lt;/span&gt;&amp;gt;
  {
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyEntity&lt;/span&gt;&amp;gt; GetMyEntities()
    {
      &lt;span style="color: blue"&gt;return this&lt;/span&gt;.EntityContext.MyEntities;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AddMyEntity(&lt;span style="color: #2b91af"&gt;MyEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyEntities.Add(entity);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;DeleteMyEntity(&lt;span style="color: #2b91af"&gt;MyEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyEntities.Delete(entity);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;UpdateMyEntity(&lt;span style="color: #2b91af"&gt;MyEntity &lt;/span&gt;entity)
    {
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.EntityContext.MyEntities.Update(entity);
    }
  }&lt;/pre&gt;

&lt;p&gt;For this sample, I just stubbed out simple CRUD operations. This is only a start, but we’ve now completed everything that’s required to get you up and running with a &lt;strong&gt;DomainService&lt;/strong&gt; that reads and writes to table storage.&lt;/p&gt;

&lt;h1&gt;The Best Part&lt;/h1&gt;

&lt;p&gt;The best part is that once you have written your &lt;strong&gt;DomainService&lt;/strong&gt;, all the RIA things you’re familiar with just work. You get change tracking. You get validation. You get the works. For instance, this small snippet uses a &lt;strong&gt;DomainDataSource &lt;/strong&gt;to hook a &lt;strong&gt;DataGrid&lt;/strong&gt; up to your &lt;strong&gt;DomainService&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl &lt;/span&gt;&lt;span style="color: red"&gt;…&lt;/span&gt;&lt;span style="color: blue"&gt; &amp;gt;

    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;…&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        
&lt;/span&gt;&lt;span style="color: blue"&gt;      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;dds&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DomainDataSource &lt;span style="color: red"&gt;ElementName&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;myEntitiesDDS&amp;quot; &lt;/span&gt;&lt;/span&gt;&lt;span style="color: red"&gt;QueryName&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;GetMyEntitiesQuery&amp;quot;&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;dds&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DomainDataSource.DomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;web&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;MyDomainContext &lt;/span&gt;&lt;span style="color: blue"&gt;/&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;dds&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DomainDataSource.DomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;br /&gt;      &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;dds&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DomainDataSource&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;ElementName&lt;/span&gt;&lt;span style="color: blue"&gt;=myEntitiesDDS, &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Data}&amp;quot; &lt;/span&gt;&lt;span style="color: blue"&gt;/&amp;gt;&lt;br /&gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;This post was just a brief intro, but there was a lot of area to cover. In the next couple of weeks, I’ll try to flesh out some of the scenarios where things get a little more interesting. Also, if there are any Azure-related topics you’re curious about or want to see covered, just let me know and I’ll try to include them.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10084328" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Azure" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Azure/" /><category term="PDC10" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/PDC10/" /></entry><entry><title>Improved binding support in EntitySet and EntityCollection</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/10/28/improved-binding-support-in-entityset-and-entitycollection.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/10/28/improved-binding-support-in-entityset-and-entitycollection.aspx</id><published>2010-10-28T20:16:22Z</published><updated>2010-10-28T20:16:22Z</updated><content type="html">&lt;p&gt;For our WCF RIA Services V1.0 SP1 Beta release we were finally able to improve binding support for &lt;strong&gt;EntitySets&lt;/strong&gt; and &lt;strong&gt;EntityCollections&lt;/strong&gt;. In our V1 release, &lt;strong&gt;EntitySet&lt;/strong&gt; and &lt;strong&gt;EntityCollection&lt;/strong&gt; did not support adding and removing entities through the &lt;strong&gt;IEditableCollectionView &lt;/strong&gt;interface when used as the &lt;strong&gt;ItemsSource&lt;/strong&gt; in a &lt;strong&gt;DataGrid &lt;/strong&gt;or &lt;strong&gt;DataForm&lt;/strong&gt;. While the details of the problem will only be familiar to some, if you’ve had difficulty adding or removing in a master/details scenario, this is the likely cause.&lt;/p&gt;  &lt;h1&gt;A Master/Details Example&lt;/h1&gt;  &lt;p&gt;In this section, I’ll put together a short sample showing how this feature enables a simple master/details scenario. I want to focus mainly on the client side of things so we’ll keep the &lt;strong&gt;DomainService &lt;/strong&gt;simple.&lt;/p&gt;  &lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;EnableClientAccess&lt;/span&gt;]
&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleDomainService &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;DomainService
&lt;/span&gt;  {
  &lt;span style="color: blue"&gt;  public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; GetEntities() {…}

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;CreateEntity(&lt;span style="color: #2b91af"&gt;SampleEntity &lt;/span&gt;entity) {…}

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;UpdateEntity(&lt;span style="color: #2b91af"&gt;SampleEntity &lt;/span&gt;entity) {…}

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;DeleteEntity(&lt;span style="color: #2b91af"&gt;SampleEntity &lt;/span&gt;entity) {…}
  }

&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleEntity
&lt;/span&gt;  {
    [&lt;span style="color: #2b91af"&gt;Key&lt;/span&gt;]
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;Id { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Name { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
  }&lt;/pre&gt;

&lt;p&gt;When the RIA Services codegen runs, it will generate the &lt;strong&gt;SampleDomainContext &lt;/strong&gt;and &lt;strong&gt;SampleEntity &lt;/strong&gt;types on the client. I’ve omitted most of the generated code, but here are the two members we’ll use later in the sample.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleDomainContext &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;DomainContext
&lt;/span&gt;  {
&lt;span style="color: blue"&gt;    public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntitySet&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; SampleEntities
    {
      &lt;span style="color: blue"&gt;get {…}
&lt;/span&gt;    }
    
&lt;span style="color: blue"&gt;    public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EntityQuery&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;SampleEntity&lt;/span&gt;&amp;gt; GetEntitiesQuery() {…}
  }&lt;/pre&gt;


&lt;p&gt;My approach on the client side of the application is simple. I use a &lt;strong&gt;DataGrid&lt;/strong&gt; to show a list of the &lt;strong&gt;SampleEntities&lt;/strong&gt; and the &lt;strong&gt;DataForm&lt;/strong&gt; to add, remove, and edit. I’ve defined my &lt;strong&gt;SampleDomainContext &lt;/strong&gt;in the xaml to make the binding simple and explicit.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl &lt;/span&gt;&lt;span style="color: red"&gt;…&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;web&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;SampleDomainContext &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Key&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;myDomainContext&amp;quot;/&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;LayoutRoot&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Background&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;White&amp;quot;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;Orientation&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Horizontal&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;2&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sdk&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataGrid &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;myDataGrid&amp;quot;
          &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;SampleEntities&lt;/span&gt;&lt;span style="color: blue"&gt;,&lt;br /&gt;                        &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;myDomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot; 
          &lt;/span&gt;&lt;span style="color: red"&gt;IsReadOnly&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;True&amp;quot; /&amp;gt;

        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;toolkit&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataForm &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;myDataForm&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Width&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;200&amp;quot;
          &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;SampleEntities&lt;/span&gt;&lt;span style="color: blue"&gt;,&lt;br /&gt;                        &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;myDomainContext&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;
          &lt;/span&gt;&lt;span style="color: red"&gt;CurrentItem&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;SelectedItem&lt;/span&gt;&lt;span style="color: blue"&gt;,&lt;br /&gt;                       &lt;/span&gt;&lt;span style="color: blue"&gt; &lt;/span&gt;&lt;span style="color: red"&gt;ElementName&lt;/span&gt;&lt;span style="color: blue"&gt;=myDataGrid, &lt;/span&gt;&lt;span style="color: red"&gt;Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=TwoWay}&amp;quot;
          &lt;/span&gt;&lt;span style="color: red"&gt;CommandButtonsVisibility&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Add,Delete,Commit,Cancel&amp;quot; /&amp;gt;&lt;br /&gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        
&lt;br /&gt;      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Button &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Submit&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Content&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Submit Changes&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Click&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Submit_Click&amp;quot;&lt;br /&gt;        &lt;/span&gt;&lt;span style="color: red"&gt;HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Left&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;2&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;UserControl&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The code behind is just as simple. I pull the &lt;strong&gt;SampleDomainContext&lt;/strong&gt; from the resources (that I declared in xaml) and use it to load and save the &lt;strong&gt;SampleEntities&lt;/strong&gt;. The only complexity here is tracking the &lt;strong&gt;DataForm&lt;/strong&gt;’s Editing state to make sure the edit is committed and the validation errors are addressed before submitting changes.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public partial class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MainPage &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;UserControl
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SampleDomainContext &lt;/span&gt;_context;
    &lt;span style="color: blue"&gt;private bool &lt;/span&gt;_isDataFormEditing;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;MainPage()
    {
      InitializeComponent();

      &lt;span style="color: blue"&gt;this&lt;/span&gt;._context =&lt;br /&gt;        (&lt;span style="color: #2b91af"&gt;SampleDomainContext&lt;/span&gt;)&lt;span style="color: blue"&gt;this&lt;/span&gt;.Resources[&lt;span style="color: #a31515"&gt;&amp;quot;myDomainContext&amp;quot;&lt;/span&gt;];
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.Load(&lt;span style="color: blue"&gt;this&lt;/span&gt;._context.GetEntitiesQuery());

      &lt;span style="color: green"&gt;// This is an unfortunate workaround to track the&lt;br /&gt;      // DataForm Editing state
      &lt;/span&gt;&lt;span style="color: blue"&gt;this&lt;/span&gt;.myDataForm.AddingNewItem +=&lt;br /&gt;        (sender, e) =&amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;._isDataFormEditing = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.myDataForm.BeginningEdit +=&lt;br /&gt;        (sender, e) =&amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;._isDataFormEditing = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
      &lt;span style="color: blue"&gt;this&lt;/span&gt;.myDataForm.EditEnded += &lt;br /&gt;        (sender, e) =&amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;._isDataFormEditing = &lt;span style="color: blue"&gt;false&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;private void &lt;/span&gt;Submit_Click(&lt;span style="color: blue"&gt;object &lt;/span&gt;sender, &lt;span style="color: #2b91af"&gt;RoutedEventArgs &lt;/span&gt;e)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(!&lt;span style="color: blue"&gt;this&lt;/span&gt;._isDataFormEditing || &lt;span style="color: blue"&gt;this&lt;/span&gt;.myDataForm.CommitEdit())
      {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._context.SubmitChanges();
      }
    }
  }&lt;/pre&gt;

&lt;p&gt;In the end, I have a nice little Master/Details application.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/2781.image_5F00_4A770C27.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: ; 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="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/3264.image_5F00_thumb_5F00_6EBBF0A9.png" width="360" height="184" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;To Sum it Up&lt;/h1&gt;

&lt;p&gt;This sample is pretty simple. The point I really want to emphasize here is that you can now bind &lt;strong&gt;EntitySets &lt;/strong&gt;and &lt;strong&gt;EntityCollections &lt;/strong&gt;to Silverlight controls like the &lt;strong&gt;DataGrid &lt;/strong&gt;and &lt;strong&gt;DataForm&lt;/strong&gt; and have them work like you would expect them to. On top of that, these types will show improved compatibility in features like drag-and-drop and as well as in third party controls.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10082391" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="CollectionView" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/CollectionView/" /><category term="PDC10" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/PDC10/" /></entry><entry><title>WCF RIA Services V1.0 SP1 Beta Released</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/10/28/wcf-ria-services-v1-0-sp1-beta-released.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/10/28/wcf-ria-services-v1-0-sp1-beta-released.aspx</id><published>2010-10-28T14:12:52Z</published><updated>2010-10-28T14:12:52Z</updated><content type="html">&lt;p&gt;WCF RIA Services V1.0 SP1 Beta along with WCF RIA Services October toolkit are now both available and ready to go live. You can download them from &lt;a href="http://silverlight.net/riaservices"&gt;http://silverlight.net/riaservices&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Check out these blogs for all the details.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://blogs.msdn.com/b/deepm/archive/tags/pdc10/"&gt;Deepesh’s Blog&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://tomasz.janczuk.org/search/label/PDC10"&gt;Tomek’s Blog&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://jeffhandley.com/tags/pdc10/"&gt;Jeff’s Blog&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Later this week I will be looking deeper into two new features; EntitySet and EntityCollection binding support and Windows Azure Table Storage integration. Stay tuned because this new stuff is awesome.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10082138" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="PDC10" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/PDC10/" /></entry><entry><title>My Thoughts on an MVVM-friendly DomainDataSource</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/09/17/my-thoughts-on-an-mvvm-friendly-domaindatasource.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/09/17/my-thoughts-on-an-mvvm-friendly-domaindatasource.aspx</id><published>2010-09-17T16:08:04Z</published><updated>2010-09-17T16:08:04Z</updated><content type="html">&lt;p&gt;The &lt;strong&gt;DomainDataSource (DDS)&lt;/strong&gt; could be a great example of an &lt;a href="http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321545613/ref=dp_ob_title_bk"&gt;aggregate component&lt;/a&gt;. It has a simple public API and does a lot of awesome things at the flip of a switch. The only problem with the thought is there’s little-to-no aggregation going on. All the composition that occurs is hidden behind a wall of internal API. This is especially frustrating for MVVM development where a lot of what the &lt;strong&gt;DDS &lt;/strong&gt;does is not as useful.&lt;/p&gt;  &lt;p&gt;In creating an MVVM-friendly &lt;strong&gt;DDS&lt;/strong&gt; we have to figure out the primary components and how they work together. Here’s a rough sketch of where I imagine this design will go. This pattern is so well-worn, I’d almost feel guilty deviating from it.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/8446.image_5F00_1B6ED908.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: ; 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="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/7382.image_5F00_thumb_5F00_033B48E0.png" width="350" height="244" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Even with something so familiar as the base, there are a ton of features to pack in. Here are the set I considered with a few ‘cut’ lines drawn through for priority. High-priority features are the bare essentials for an MVVM-friendly &lt;strong&gt;DDS&lt;/strong&gt;. Medium-priority features are great, but not critical. Low-priority features are things I’ll consider but will probably never get to. Please let me know if you think something needs to be added, removed, or moved to a different priority level.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160; ===== High Priority =====&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Source: EntitySet – &lt;/strong&gt;Using an &lt;strong&gt;EntitySet &lt;/strong&gt;with the rest of the features.     &lt;br /&gt;&lt;strong&gt;Source: EntityCollection – &lt;/strong&gt;Using an &lt;strong&gt;EntityCollection &lt;/strong&gt;with the rest of the features.     &lt;br /&gt;&lt;strong&gt;Source: Read-Only Collection –&lt;/strong&gt; Using a read-only collection with the rest of the features.     &lt;br /&gt;&lt;strong&gt;Source: Mutable Collection – &lt;/strong&gt;Using a mutable collection with the rest of the features.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Server: Sorting – &lt;/strong&gt;Applying sorting to the data on the server.     &lt;br /&gt;&lt;strong&gt;Server: Grouping – &lt;/strong&gt;Applying grouping to the data on the server.     &lt;br /&gt;&lt;strong&gt;Server: Paging – &lt;/strong&gt;Applying paging to the data on the server.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Editing: Adding – &lt;/strong&gt;Adding a new &lt;strong&gt;Entity&lt;/strong&gt; to the source collection.     &lt;br /&gt;&lt;strong&gt;Editing: Removing – &lt;/strong&gt;Removing an &lt;strong&gt;Entity&lt;/strong&gt; from the source collection.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Testing: Component Base Classes – &lt;/strong&gt;Abstract base classes for individual components.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Designer: View – &lt;/strong&gt;Any view property can be set in xaml using a designer.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Quality: Toolkit – &lt;/strong&gt;High-quality, partially-supported features.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160; ===== Medium Priority =====&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Client: Filtering – &lt;/strong&gt;Applying a filter to the source collection on the client.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Server: Filtering – &lt;/strong&gt;Applying a filter to the data on the server.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Query: Dynamic ‘And’ &lt;/strong&gt;– Creating an &lt;strong&gt;EntityQuery &lt;/strong&gt;using ‘And’ from a dynamic set of filters on the client.     &lt;br /&gt;&lt;strong&gt;Query: Dynamic ‘Or’ &lt;/strong&gt;– Creating an &lt;strong&gt;EntityQuery &lt;/strong&gt;using ‘Or’ from a dynamic set of filters on the client.     &lt;br /&gt;&lt;strong&gt;Query: Nested – &lt;/strong&gt;Creating an &lt;strong&gt;EntityQuery &lt;/strong&gt;with nested clauses from a dynamic set of filters on the client.     &lt;br /&gt;&lt;strong&gt;Query: Shaping– &lt;/strong&gt;Creating an &lt;strong&gt;EntityQuery&lt;/strong&gt; from a dynamic set of sorts, groups, or paging parameters on the client.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Other: Strong-Typing – &lt;/strong&gt;Strongly-typed API for &lt;strong&gt;Entity&lt;/strong&gt; interaction.     &lt;br /&gt;&lt;strong&gt;Other: Source Code – &lt;/strong&gt;Feature source code.     &lt;br /&gt;&lt;strong&gt;Other: Samples – &lt;/strong&gt;Feature samples.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Quality: Framework – &lt;/strong&gt;High-quality, fully-supported features.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160; ===== Low Priority =====&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Client: Sorting – &lt;/strong&gt;Applying sorting to the source collection on the client.     &lt;br /&gt;&lt;strong&gt;Client: Grouping – &lt;/strong&gt;Applying grouping to the source collection on the client.     &lt;br /&gt;&lt;strong&gt;Client: Paging – &lt;/strong&gt;Applying paging to the source collection on the client.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Loading: Auto – &lt;/strong&gt;Tracking changes that affect the query and automatically reloading.     &lt;br /&gt;&lt;strong&gt;Loading: Timed – &lt;/strong&gt;Reloading based on a timed interval.     &lt;br /&gt;&lt;strong&gt;Loading: Incremental – &lt;/strong&gt;Incrementally loading a large data set in smaller blocks.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Testing: Top-level Interfaces – &lt;/strong&gt;Interfaces for the top-most aggregate objects.     &lt;br /&gt;&lt;strong&gt;Testing: Component Interfaces – &lt;/strong&gt;Interfaces for individual components.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Designer: Filtering – &lt;/strong&gt;Defining filters in xaml using a designer.     &lt;br /&gt;&lt;strong&gt;Designer: Sorting – &lt;/strong&gt;Defining sorts in xaml using a designer.     &lt;br /&gt;&lt;strong&gt;Designer: Grouping – &lt;/strong&gt;Defining groups in xaml using a designer.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Other: Hot-Swapping – &lt;/strong&gt;Switching between client and server data shaping during use.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Quality: Preview – &lt;/strong&gt;Medium-quality, mostly unsupported features; as soon as possible.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10064058" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="DomainDataSource" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/DomainDataSource/" /><category term="MVVM" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/MVVM/" /><category term="CollectionView" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/CollectionView/" /></entry><entry><title>What is an MVVM-friendly DomainDataSource?</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/09/01/what-is-an-mvvm-friendly-domaindatasource.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/09/01/what-is-an-mvvm-friendly-domaindatasource.aspx</id><published>2010-09-01T15:30:00Z</published><updated>2010-09-01T15:30:00Z</updated><content type="html">&lt;p&gt;The second most requested feature on our &lt;a href="http://dotnet.uservoice.com/forums/57026-wcf-ria-services"&gt;WCF RIA Services Wish List&lt;/a&gt; is an MVVM-friendly &lt;strong&gt;DomainDataSource&lt;/strong&gt;. The neat part about this request is that it means many different things to many different people. The challenge in addressing it is to figure out what are the most valuable changes that will satisfy the greatest number of scenarios.&lt;/p&gt;
&lt;p&gt;This is where I turn to you. I&amp;rsquo;d love to hear some opinions about what people think is important. For now, let&amp;rsquo;s keep the discussion constrained to two questions.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;What are the two most important changes for us to make to the &lt;strong&gt;DomainDataSource&lt;/strong&gt; to make it MVVM-friendly? &lt;/li&gt;
&lt;li&gt;If those changes were made, would you use the &lt;strong&gt;DomainDataSource&lt;/strong&gt; in your View Models? &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I know there&amp;rsquo;s more on this topic to talk about, but let&amp;rsquo;s start slow. I've started this &lt;a href="http://forums.silverlight.net/forums/p/199051/464064.aspx#464064"&gt;thread on the forum&lt;/a&gt; to discuss the issue.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10056866" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="DomainDataSource" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/DomainDataSource/" /><category term="MVVM" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/MVVM/" /><category term="CollectionView" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/CollectionView/" /></entry><entry><title>Authorization Sample 305 – Permission-Based Authorization for Silverlight</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/08/31/authorization-sample-305-permission-based-authorization-for-silverlight.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/08/31/authorization-sample-305-permission-based-authorization-for-silverlight.aspx</id><published>2010-08-31T16:29:26Z</published><updated>2010-08-31T16:29:26Z</updated><content type="html">&lt;p&gt;In &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/07/09/authorization-sample-301.aspx"&gt;Authorization Sample 301&lt;/a&gt; I explained the ins-and-outs of the &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/05/03/silverlight-authorization-sample.aspx"&gt;authorization sample&lt;/a&gt; and offered a few hints as to how it could be used. In this post, I will show a specific example where I show how to &lt;a href="http://code.msdn.microsoft.com/Silverlight-Authorization-33999e76"&gt;extend the authorization library to support read and write permissions&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/3666.image_5F00_77ED5590.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/0435.image_5F00_thumb_5F00_7E342C1E.png" width="500" height="128" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h3&gt;Permissions&lt;/h3&gt;  &lt;p&gt;The first challenge with this sample was to figure out how to represent permissions in metadata in a way that could be used by &lt;strong&gt;AuthorizationAttributes&lt;/strong&gt;. After churning the design for a while, I came away with something simple that made authorization convenient. &lt;/p&gt;  &lt;p&gt;The first step was to create a &lt;strong&gt;Permission&lt;/strong&gt;, a type that&lt;strong&gt;&amp;#160;&lt;/strong&gt;combines a name and a list of allowed activities. The name property needs to be treated as the unique key for the permission.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Permission
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Name { get; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermissionKind &lt;/span&gt;Kind { get; }
  }&lt;/pre&gt;

&lt;p&gt;The next step was to define the all the activity types in a &lt;strong&gt;PermissionKind &lt;/strong&gt;enumeration.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;Flags&lt;/span&gt;]
&lt;span style="color: blue"&gt;  public enum &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermissionKind
&lt;/span&gt;  {
    None = 0x0,
    Read = 0x1,
    Write = 0x2,
    All = Read | Write,
  }&lt;/pre&gt;

&lt;p&gt;With these two types, I was able to create an &lt;strong&gt;AuthorizationAttribute&lt;/strong&gt; for requiring permissions.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;RequiresPermissionAttribute &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;AuthorizationAttribute
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; _permissionNames;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;RequiresPermissionAttribute(&lt;span style="color: blue"&gt;params string&lt;/span&gt;[] permissionNames)
    {
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(permissionNames == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
      {
        permissionNames = &lt;span style="color: blue"&gt;new string&lt;/span&gt;[0];
      }
      &lt;span style="color: blue"&gt;this&lt;/span&gt;._permissionNames = permissionNames.ToArray();
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; PermissionNames
    {
      &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return this&lt;/span&gt;._permissionNames; }
    }

    &lt;span style="color: blue"&gt;protected override &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AuthorizationResult &lt;/span&gt;IsAuthorized(&lt;br /&gt;                         &lt;span style="color: #2b91af"&gt;IPrincipal &lt;/span&gt;principal,&lt;br /&gt;                         &lt;span style="color: #2b91af"&gt;AuthorizationContext &lt;/span&gt;authorizationContext)
    {
      &lt;span style="color: #2b91af"&gt;PermissionKind &lt;/span&gt;kind = &lt;span style="color: #2b91af"&gt;PermissionKind&lt;/span&gt;.All;
      &lt;span style="color: blue"&gt;if &lt;/span&gt;(authorizationContext.Items.ContainsKey(&lt;br /&gt;                                       &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;PermissionKind&lt;/span&gt;)))
      {
        kind = (&lt;span style="color: #2b91af"&gt;PermissionKind&lt;/span&gt;)&lt;br /&gt;                 authorizationContext.Items[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;PermissionKind&lt;/span&gt;)];
      }

      &lt;span style="color: #2b91af"&gt;User &lt;/span&gt;user = (&lt;span style="color: #2b91af"&gt;User&lt;/span&gt;)principal;
      &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;string &lt;/span&gt;name &lt;span style="color: blue"&gt;in this&lt;/span&gt;.PermissionNames)
      {
        &lt;span style="color: #2b91af"&gt;Permission &lt;/span&gt;permission = user.Permissions.FirstOrDefault(&lt;br /&gt;                                                   p =&amp;gt; p.Name == name);
        &lt;span style="color: blue"&gt;if &lt;/span&gt;((permission != &lt;span style="color: blue"&gt;null&lt;/span&gt;) &amp;amp;&amp;amp; ((kind &amp;amp; permission.Kind) == kind))
        {
          &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AuthorizationResult&lt;/span&gt;.Allowed;
        }
      }

      &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AuthorizationResult&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;User does not have permission.&amp;quot;&lt;/span&gt;);
    }
  }&lt;/pre&gt;

&lt;p&gt;It may look a little complex at first, so let’s break it down. First, the &lt;strong&gt;RequiresPermissionAttribute &lt;/strong&gt;is created with a permission name.&lt;/p&gt;

&lt;pre class="code"&gt;  [&lt;span style="color: #2b91af"&gt;RequiresPermission&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Model&amp;quot;&lt;/span&gt;)]&lt;/pre&gt;

&lt;p&gt;To be authorized, the user must have the &lt;strong&gt;“Model”&lt;/strong&gt; permission with &lt;strong&gt;PermissionKind.All&lt;/strong&gt;. Also, like the &lt;strong&gt;RequiresRolesAttribute&lt;/strong&gt;, the attribute can be declared with a list of names. In that case, the user must match at least one of the permissions in the list to be authorized.&lt;/p&gt;

&lt;p&gt;Apart from the primary authorization mode, the &lt;strong&gt;RequiresPermissionAttribute &lt;/strong&gt;can be queried for one particular &lt;strong&gt;PermissionKind&lt;/strong&gt;. This allows calling code to determine if the user has only a subset of the &lt;strong&gt;PermissionKinds&lt;/strong&gt;; only &lt;strong&gt;PermissionKind.Read&lt;/strong&gt;, for example. To query for a specific kind, an entry for the kind can be added to the &lt;strong&gt;AuthorizationContext&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;UI Modes&lt;/h3&gt;

&lt;p&gt;The second challenge was how to represent permissions with respect to the UI. I found I needed to create a second enumeration to identify the states that were interesting from a UI perspective.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public enum &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ReadWriteMode
&lt;/span&gt;  {
    None = 0,
    Read,
    ReadOnly,
    ReadWrite,
  }&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Read&lt;/strong&gt; – This mode is designed for switching control visibility on authorization. If the user has the right read permission the control will be visible. 

  &lt;br /&gt;&lt;strong&gt;ReadOnly &lt;/strong&gt;– This mode is designed to work in tandem with &lt;strong&gt;ReadWrite&lt;/strong&gt;. When the user has permission to read but not write the control will be visible. 

  &lt;br /&gt;&lt;strong&gt;ReadWrite&lt;/strong&gt; – This mode works with &lt;strong&gt;ReadOnly&lt;/strong&gt;. When the user has permission to read and write the control will be visible.&lt;/p&gt;

&lt;p&gt;The pairing of &lt;strong&gt;ReadOnly &lt;/strong&gt;and &lt;strong&gt;ReadWrite &lt;/strong&gt;allows controls for viewing and editing to be declared alongside each other in the xaml. Setting the mode ensures they will never be visible at the same time.&lt;/p&gt;

&lt;pre class="code"&gt;  &lt;span style="color: green"&gt;&amp;lt;!-- Value --&amp;gt;
  &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Row&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Column&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;0&amp;quot;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: red"&gt;             Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Value&amp;quot;
             &lt;/span&gt;&lt;span style="color: red"&gt;rws&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ReadWriteAuthorization.RequiresPermission&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Model&amp;quot;&lt;br /&gt;             &lt;span style="color: red"&gt;rws&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ReadWriteAuthorization.Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Read&amp;quot; /&amp;gt; &lt;/span&gt;
&lt;/span&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Row&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Column&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;1&amp;quot;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: blue"&gt;             &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Value&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot;
             &lt;/span&gt;&lt;span style="color: red"&gt;rws&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ReadWriteAuthorization.RequiresPermission&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Model&amp;quot;&lt;br /&gt;            &lt;/span&gt;&lt;span style="color: blue"&gt; &lt;/span&gt;&lt;span style="color: red"&gt;rws&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ReadWriteAuthorization.Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;ReadOnly&amp;quot; /&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ComboBox &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Row&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Column&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;1&amp;quot;&lt;/span&gt;&lt;span style="color: blue"&gt;
            &lt;/span&gt;&lt;span style="color: red"&gt;SelectedValue&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Value&lt;/span&gt;&lt;span style="color: blue"&gt;, &lt;/span&gt;&lt;span style="color: red"&gt;Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=TwoWay}&amp;quot;
            &lt;/span&gt;&lt;span style="color: red"&gt;rws&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ReadWriteAuthorization.RequiresPermission&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Model&amp;quot;&lt;br /&gt;            &lt;/span&gt;&lt;span style="color: red"&gt;rws&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ReadWriteAuthorization.Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;ReadWrite&amp;quot; /&amp;gt;

&lt;/span&gt;&lt;/pre&gt;

&lt;h3&gt;Rules, Behaviors, and Sources&lt;/h3&gt;

&lt;p&gt;Writing a permission-based solution takes advantage of (and was a catalyst for) most of the extensibility points in the authorization library. First there is a custom &lt;strong&gt;AuthorizationRule &lt;/strong&gt;that ties the whole thing together. It creates &lt;strong&gt;RequiresPermissionAttributes &lt;/strong&gt;for authorization from the permission names in the attached &lt;strong&gt;ReadWriteAuthorization.RequiresPermission&lt;/strong&gt; dependency property. The rule also creates custom &lt;strong&gt;AuthorizationBehaviors&lt;/strong&gt; that handle updating the UI using the attached &lt;strong&gt;Authorization.TargetProperties &lt;/strong&gt;and &lt;strong&gt;ReadWriteAuthorization.Mode &lt;/strong&gt;dependency properties.&lt;/p&gt;

&lt;p&gt;To control the UI behavior, the custom &lt;strong&gt;ReadWriteAuthorizationBehavior&lt;/strong&gt; creates a binding between the target dependency property and a custom &lt;strong&gt;AuthorizationSource&lt;/strong&gt;. Based on the mode, it will bind to one of the &lt;strong&gt;Result&lt;/strong&gt;, &lt;strong&gt;ReadOnlyResult&lt;/strong&gt;, or &lt;strong&gt;ReadWriteResult&lt;/strong&gt; properties on the source.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;ReadWriteAuthorizationSource &lt;/strong&gt;has three result properties to match up with the &lt;strong&gt;ReadWriteMode &lt;/strong&gt;enumeration; &lt;strong&gt;Result&lt;/strong&gt;, &lt;strong&gt;ReadOnlyResult&lt;/strong&gt;, and &lt;strong&gt;ReadWriteResult&lt;/strong&gt;. The default &lt;strong&gt;Result&lt;/strong&gt; property matches up with &lt;strong&gt;ReadWriteMode.Read&lt;/strong&gt;. The source is created with one or more &lt;strong&gt;RequiresPermissionAttributes &lt;/strong&gt;and uses them to authorize the current user and determine each of the results. Also, each of these properties can be listened to for changes and will update in response to changes in &lt;strong&gt;WebContext.Current.User&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I hope you’re still following, but that was a lot of types and relationships condensed into a few short paragraphs. In summary, there is a custom &lt;strong&gt;AuthorizationRule&lt;/strong&gt;, a custom &lt;strong&gt;AuthorizationBehavior&lt;/strong&gt;, and a custom &lt;strong&gt;AuthorizationSource&lt;/strong&gt;. Together they work to require permissions and update the UI.&lt;/p&gt;

&lt;h3&gt;A Custom Rule for Text&lt;/h3&gt;

&lt;p&gt;One of the benefits of rule extensibility is the control it provides. In this sample, I created a custom rule to apply only to &lt;strong&gt;TextBoxes&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ReadWriteTextAuthorizationRule &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;AuthorizationRule
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public override &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;AuthorizationBehavior&lt;/span&gt;&amp;gt;&lt;br /&gt;                      GetAuthorizationBehaviors(&lt;span style="color: blue"&gt;object &lt;/span&gt;target)
    {
      &lt;span style="color: blue"&gt;return new&lt;/span&gt;[]
      {
        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ReadWriteAuthorizationBehavior&lt;/span&gt;(&lt;br /&gt;              &lt;span style="color: #a31515"&gt;&amp;quot;Visibility&amp;quot;&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;ReadWriteMode&lt;/span&gt;.Read),
        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ReadWriteAuthorizationBehavior&lt;/span&gt;(&lt;br /&gt;              &lt;span style="color: #a31515"&gt;&amp;quot;IsReadOnly&amp;quot;&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;ReadWriteMode&lt;/span&gt;.ReadOnly),
      };
    }
  }&lt;/pre&gt;

&lt;p&gt;It uses the custom &lt;strong&gt;ReadWriteAuthorizationBehavior &lt;/strong&gt;to bind the &lt;strong&gt;Visibility &lt;/strong&gt;and &lt;strong&gt;IsReadOnly &lt;/strong&gt;properties to an &lt;strong&gt;AuthorizationSource&lt;/strong&gt;. I chose to make it the default rule for &lt;strong&gt;TextBoxes&lt;/strong&gt;, but it could just as easily be applied to individual controls. Also, since a target can have more than one rule, I can use the &lt;strong&gt;ReadWriteAuthorization.RequiresPermission &lt;/strong&gt;property to define the &lt;strong&gt;RequiresPermissionAttributes&lt;/strong&gt; used for authorization and the default text rule to define the behaviors and binding to apply.&lt;/p&gt;

&lt;pre class="code"&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBox &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;, &lt;/span&gt;&lt;span style="color: red"&gt;Mode&lt;/span&gt;&lt;span style="color: blue"&gt;=TwoWay}&amp;quot;
           &lt;/span&gt;&lt;span style="color: red"&gt;rws&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ReadWriteAuthorization.RequiresPermission&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Model&amp;quot; /&amp;gt;

&lt;/span&gt;&lt;/pre&gt;

&lt;h3&gt;Wrap Up&lt;/h3&gt;

&lt;p&gt;There’s a lot of code in this sample, but I wanted to show how a more complex authorization scenario could be implemented. I imagine this same design could be scaled up to support more than just Read and Write permissions. For each &lt;strong&gt;PermissionKind&lt;/strong&gt; that was added, one or more corresponding UI Modes could be added as well.&lt;/p&gt;

&lt;p&gt;I’ve included the source &lt;a href="http://code.msdn.microsoft.com/Silverlight-Authorization-33999e76"&gt;here for your reference&lt;/a&gt;. I hope it’s a helpful reference point for implementing authorization in your own applications.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10056414" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Authentication" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Authentication/" /><category term="Authorization" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Authorization/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /></entry><entry><title>Authorization Sample 304 – MVVM Authorization for Silverlight</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/kylemc/archive/2010/08/31/authorization-sample-304-mvvm-authorization-for-silverlight.aspx" /><id>http://blogs.msdn.com/b/kylemc/archive/2010/08/31/authorization-sample-304-mvvm-authorization-for-silverlight.aspx</id><published>2010-08-31T16:17:00Z</published><updated>2010-08-31T16:17:00Z</updated><content type="html">&lt;p&gt;In &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/07/09/authorization-sample-301.aspx"&gt;Authorization Sample 301&lt;/a&gt; I explained the ins-and-outs of the &lt;a href="http://blogs.msdn.com/b/kylemc/archive/2010/05/03/silverlight-authorization-sample.aspx"&gt;authorization sample&lt;/a&gt; and offered a few hints as to how it could be used. In this post, I will show a specific example where I put together an &lt;a href="http://code.msdn.microsoft.com/Silverlight-Authorization-33999e76"&gt;authorized form using the Model-View-ViewModel pattern&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/7522.image_5F00_3CF22D10.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-37-63-metablogapi/4314.image_5F00_thumb_5F00_3C19C726.png" width="500" height="127" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;For this form, I created a simple view model with the following properties.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ViewModel &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;INotifyPropertyChanged
&lt;/span&gt;  {
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;Id { get; set; }&lt;br /&gt;
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ModelValue &lt;/span&gt;Value { get; set; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Visibility &lt;/span&gt;ValueVisibility { get; private set; }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Text { get; set; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Visibility &lt;/span&gt;TextVisibility { get; private set; }
    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;IsTextReadOnly { get; private set; }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICommand &lt;/span&gt;ResetCommand { get; }
  }&lt;/pre&gt;

&lt;p&gt;My goal was to present a customized view for each user role. To implement this I created a couple &lt;strong&gt;AuthorizationSources &lt;/strong&gt;using &lt;strong&gt;AuthorizationAttributes&lt;/strong&gt;. The benefit of using sources&lt;strong&gt; &lt;/strong&gt;is they subscribe to user changes and apply the attributes to provide an &lt;strong&gt;AuthorizationResult&lt;/strong&gt; that I can bind to in my view model. The _&lt;strong&gt;memberSource&lt;/strong&gt; tells me if the user is a “member”, and the _&lt;strong&gt;administratorSource&lt;/strong&gt; tells me if the user is an “administrator”.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  public &lt;/span&gt;ViewModel()
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._memberSource =&lt;br /&gt;      &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AuthorizationSource&lt;/span&gt;(&lt;br /&gt;            &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;RequiresRoleAttribute&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;member&amp;quot;&lt;/span&gt;) });
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._administratorSource =&lt;br /&gt;      &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AuthorizationSource&lt;/span&gt;(&lt;br /&gt;            &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;RequiresRoleAttribute&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;administrator&amp;quot;&lt;/span&gt;) });

    &lt;span style="color: blue"&gt;this&lt;/span&gt;._resetCommand = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AuthorizationCommand&lt;/span&gt;(&lt;br /&gt;                               &lt;span style="color: blue"&gt;this&lt;/span&gt;._administratorSource,&lt;br /&gt;                               &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ResetCommand&lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;));

    &lt;span style="color: blue"&gt;this&lt;/span&gt;._memberSource.PropertyChanged +=&lt;br /&gt;     (s, e) =&amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.CalculateAuthorizedProperties();
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._administratorSource.PropertyChanged +=&lt;br /&gt;     (s, e) =&amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.CalculateAuthorizedProperties();

    &lt;span style="color: blue"&gt;this&lt;/span&gt;.CalculateAuthorizedProperties();
  }&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;CalculateAuthorizedProperties&lt;/strong&gt; method takes the results from each source and uses them to set other view model properties that I’ve bound to in my view.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;  private void &lt;/span&gt;CalculateAuthorizedProperties()
  {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.ValueVisibility =&lt;br /&gt;      (&lt;span style="color: blue"&gt;this&lt;/span&gt;._memberSource.Result == &lt;span style="color: #2b91af"&gt;AuthorizationResult&lt;/span&gt;.Allowed) ?&lt;br /&gt;        &lt;span style="color: #2b91af"&gt;Visibility&lt;/span&gt;.Visible :&lt;br /&gt;        &lt;span style="color: #2b91af"&gt;Visibility&lt;/span&gt;.Collapsed;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.TextVisibility = &lt;span style="color: blue"&gt;this&lt;/span&gt;.ValueVisibility;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;.IsTextReadOnly =&lt;br /&gt;      (&lt;span style="color: blue"&gt;this&lt;/span&gt;._administratorSource.Result != &lt;span style="color: #2b91af"&gt;AuthorizationResult&lt;/span&gt;.Allowed);
  }&lt;/pre&gt;

&lt;p&gt;The last bit of the sample to highlight is the _&lt;strong&gt;resetCommand&lt;/strong&gt;. An &lt;strong&gt;AuthorizationCommand &lt;/strong&gt;is created taking an &lt;strong&gt;AuthorizationSource &lt;/strong&gt;and a command to delegate to. When the result on the source is not equal to &lt;strong&gt;AuthorizationResult.Allowed&lt;/strong&gt;, the command’s &lt;strong&gt;CanExecute &lt;/strong&gt;property will be set to false. When the authorization command is allowed, it will delegate to other command passed in to its constructor.&lt;/p&gt;

&lt;p&gt;I’ve included the source for the sample &lt;a href="http://code.msdn.microsoft.com/Silverlight-Authorization-33999e76"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In this sample I stuck mostly to &lt;strong&gt;AuthorizationAttributes &lt;/strong&gt;and &lt;strong&gt;AuthorizationSources&lt;/strong&gt;. These are definitely the most interesting types for MVVM authorization, but &lt;strong&gt;AuthorizationRules &lt;/strong&gt;might also prove helpful. For instance, for complex logic like interpreting metadata on an Entity a rule could be used to determine which attributes to pass to the source. That would make the logic both encapsulated and reusable for multiple view models.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10056356" width="1" height="1"&gt;</content><author><name>kylemc</name><uri>http://blogs.msdn.com/kylemc/ProfileUrlRedirect.ashx</uri></author><category term="WCF RIA Services" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/WCF+RIA+Services/" /><category term="Authentication" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Authentication/" /><category term="Authorization" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Authorization/" /><category term="Silverlight" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/Silverlight/" /><category term="MVVM" scheme="http://blogs.msdn.com/b/kylemc/archive/tags/MVVM/" /></entry></feed>