<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Extemporaneous Mumblings</title>
    <link>http://dunnry.com/blog/</link>
    <description>... a blog by Ryan Dunn</description>
    <language>en-us</language>
    <copyright>Ryan Dunn</copyright>
    <lastBuildDate>Wed, 02 Jul 2008 23:43:26 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.0.7226.0</generator>
    <managingEditor>ryan@dunnry.com</managingEditor>
    <webMaster>ryan@dunnry.com</webMaster>
    <item>
      <trackback:ping>http://dunnry.com/blog/Trackback.aspx?guid=b37072b9-1fe8-4785-9df3-00861ab346f7</trackback:ping>
      <pingback:server>http://dunnry.com/blog/pingback.aspx</pingback:server>
      <pingback:target>http://dunnry.com/blog/PermaLink,guid,b37072b9-1fe8-4785-9df3-00861ab346f7.aspx</pingback:target>
      <dc:creator>Ryan Dunn</dc:creator>
      <wfw:comment>http://dunnry.com/blog/CommentView,guid,b37072b9-1fe8-4785-9df3-00861ab346f7.aspx</wfw:comment>
      <wfw:commentRss>http://dunnry.com/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=b37072b9-1fe8-4785-9df3-00861ab346f7</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Here is my last installment in this series of working with objects in SQL Server Data
Services.  For background, readers should read the following:
</p>
        <p>
          <a href="http://dunnry.com/blog/SerializationInSSDS.aspx">Serialization in SSDS</a>
        </p>
        <p>
          <a href="http://dunnry.com/blog/WorkingWithObjectsInSSDSPart1.aspx">Working with Objects
in SSDS Part 1</a>
        </p>
        <p>
          <a href="http://dunnry.com/blog/WorkingWithObjectsInSSDSPart2.aspx">Working with Objects
in SSDS Part 2</a>
        </p>
        <p>
Last time, we concluded with a class called <strong>SsdsEntity&lt;T&gt;</strong> that
became an all-purpose wrapper or veneer around our CLR objects.  This made it
simple to take our existing classes and serialize them as entities in SSDS.
</p>
        <p>
In this post, I want to discuss how the querying in the REST library works. 
First a simple example:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">var ctx = <span style="color: #0000ff">new</span> SsdsContext( <span style="color: #006080">"authority=http://dunnry.data.beta.mssds.com/v1/;username=dunnry;password=secret"</span> );
var container = ctx.OpenContainer(<span style="color: #006080">"foo"</span>); var
foo = <span style="color: #0000ff">new</span> Foo { IsPublic = <span style="color: #0000ff">false</span>,
Name = <span style="color: #006080">"MyFoo"</span>, Size = 12 }; <span style="color: #008000">//insert
it with unique id guid string</span> container.Insert(foo, Guid.NewGuid().ToString()); <span style="color: #008000">//now
query for it</span> var results = container.Query&lt;Foo&gt;(e =&gt; e.Entity.IsPublic
== <span style="color: #0000ff">false</span> &amp;&amp; e.Entity.Size &gt; 2); <span style="color: #008000">//Query&lt;T&gt;
returns IEnumerable&lt;SsdsEntity&lt;T&gt;&gt;, so foreach over it</span><span style="color: #0000ff">foreach</span> (var
item <span style="color: #0000ff">in</span> results) { Console.WriteLine(item.Entity.Name);
}</pre>
        </div>
        <p>
I glossed over it in my previous posts with this library, but I have a class called <strong>SsdsContext</strong> that
acts as my credential store and factory to create <strong>SsdsContainer</strong> objects
where I perform my operations.  Here, I have opened a container called 'foo',
which would relate to the URI (<a href="http://dunnry.data.beta.mssds.com/v1/foo">http://dunnry.data.beta.mssds.com/v1/foo</a>)
according to the authority name I passed on the <strong>SsdsContext</strong> constructor
arguments.
</p>
        <p>
I created an instance of my <strong>Foo</strong> class (see <a href="http://dunnry.com/blog/WorkingWithObjectsInSSDSPart1.aspx">this
post</a> if you want to see what a <strong>Foo</strong> looks like) and inserted it. 
We know that under the covers we have an <strong>XmlSerializer</strong> doing the
work to serialize that to the proper POX wire format.  So far, so good. 
Now, I want to retrieve that same entity back from SSDS. The key line here is the
table.Query&lt;T&gt;() call.  It accepts a <strong>Expression&lt;Func&lt;SsdsEntity&lt;T&gt;,
bool&gt;&gt;</strong> argument that represents a strongly typed query.
</p>
        <p>
For the uninitiated, the <strong>Expression&lt;TDelegate&gt;</strong> is a way to
represent lambda expressions in an abstract syntax tree.  We can think of them
as a way to model what the expression does without generating the bits of code necessary
to actually do it.  We can inspect the <strong>Expression</strong> and create
new ones based on it until finally we can call Compile and actually convert the representation
of the lambda into something that can execute.
</p>
        <p>
The <strong>Func&lt;SsdsEntity&lt;T&gt;, bool&gt;</strong> represents a delegate that
accepts a <strong>SsdsEntity&lt;T&gt;</strong> as an argument and returns a boolean. 
This effectively represents the WHERE clause in the SSDS LINQ query syntax. 
Since <strong>SsdsEntity&lt;T&gt;</strong> contains an actual type T in the <strong>Entity</strong> property,
you can query directly against it in a strongly typed fashion!
</p>
        <p>
What about those flexible properties that I added to support flexible attributes outside
of our T?  I mentioned that I wanted to keep the <strong>PropertyBucket</strong> (a <strong>Dictionary&lt;string,
object&gt;</strong>) property public for querying.  In order to use the flexible
properties that you add, you simply use it in a weakly typed manner:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">var results = container.Query&lt;Foo&gt;(e =&gt; e.PropertyBucket[<span style="color: #006080">"MyFlexProp"</span>]
&gt; 10);</pre>
        </div>
        <p>
As you can see, any boolean expression that you can think of in the string-based SSDS
LINQ query syntax can now be expressed in a strongly-typed manner using the <strong>Func&lt;SsdsEntity&lt;T&gt;,
bool&gt;</strong> lambda syntax.
</p>
        <h3>How it works
</h3>
        <p>
Since I have the expression tree of what your query looks like in strongly-typed terms,
it is a simple matter to take that and convert it to the SSDS LINQ query syntax that
looks like "from e in entities where [....] select e" that is appended to the query
string in the REST interface.  I should say it is a simple matter because <a href="http://blogs.msdn.com/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx">Matt
Warren</a> did a lot of the heavy lifting for us and provided the abstract expression
visitor (<strong>ExpressionVisitor</strong>) as well as the expression visitor that
partially evaluates the tree to evaluate constants (<strong>SubTreeEvaluator</strong>). 
This last part is important because it allows us to write this:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">int</span> i
= 10; <span style="color: #0000ff">string</span> name = <span style="color: #006080">"MyFoo"</span>;
var results = container.Query&lt;Foo&gt;(e =&gt; e.Entity.Name == name &amp;&amp;
e.Entity.Size &gt; i);</pre>
        </div>
        <p>
Without the partial tree evaluation, you would not be able to express the right hand
side of the equation.  All I had to do was implement an expression visitor that
correctly evaluated the lambda expression and converted it to the LINQ syntax that
SSDS expects (<strong>SsdsExpressionVisitor</strong>).  It would be a trivial
matter to actually implement the <strong>IQueryProvider</strong> and <strong>IQueryable</strong> interfaces
to make the whole thing work inside LINQ to Objects.
</p>
        <p>
Originally, I did supply the <strong>IQueryProvider</strong> for this implementation
but after consideration I have decided that using methods from the <strong>SsdsContainer</strong> class
instead of the standard LINQ syntax is the best way to proceed.  Mainly, this
has to do with the fact that I want to make it more explicit to the developer what
will happen under the covers rather than using the standard <strong>Where()</strong> extension
method.
</p>
        <h3>Querying data
</h3>
        <p>
The main interaction to return data is via the <strong>Query&lt;T&gt;</strong> method. 
This method is smart enough to add the Kind into the query for you based on the T
supplied.  So, if you write something like:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">var results = container.Query&lt;Foo&gt;(e =&gt; e.Entity.Size &gt; 2);</pre>
        </div>
        <p>
This is actually translated to "<em>from e in entities where e["Size"] &gt; 2 &amp;&amp;
e.Kind == "Foo" select e</em>".  The addition of the kind is important because
we want to limit the results as much as possible.  If there happened to be many
kinds in the container that had the flexible property "Size", it would actually return
those as well in the wire response.
</p>
        <p>
Of course, what about if you want that to happen?  What if you want to return
other kinds that have the "Size" property?  To do this, I have introduced a class
called <strong>SsdsEntityBucket</strong>.  It is exactly what it sounds like. 
To use it, you simply specify a query that uses additional types with either the <strong>Query&lt;T,U,V&gt;</strong> or <strong>Query&lt;T,U&gt;</strong> methods. 
Here is an example:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">var foo = <span style="color: #0000ff">new</span> Foo
{ IsPublic = <span style="color: #0000ff">true</span>, MyCheese = <span style="color: #0000ff">new</span> Cheese
{ LastModified = DateTime.Now, Name = <span style="color: #006080">"MyCheese"</span> },
Name = <span style="color: #006080">"FooMaster"</span>, Size = 10 }; container.Insert(foo,
foo.Name); container.Insert(foo.MyCheese, foo.MyCheese.Name); <span style="color: #008000">//query
for bucket...</span> var bucket = container.Query&lt;Foo, Cheese&gt;( (f, c) =&gt;
f.Entity.Name == <span style="color: #006080">"FooMaster"</span> || c.Entity.Name
== <span style="color: #006080">"MyCheese"</span> ); var f1 = bucket.GetEntities&lt;Foo&gt;().Single();
var c1 = bucket.GetEntities&lt;Cheese&gt;().Single();</pre>
        </div>
        <p>
The calls to <strong>GetEntities&lt;T&gt;</strong> returns <strong>IEnumerable&lt;SsdsEntity&lt;T&gt;&gt;</strong> again. 
However, this was done in a single call to SSDS instead of multiple calls per T.
</p>
        <h3>Paging
</h3>
        <p>
As I mentioned earlier, I wanted the developer to understand what they were doing
when they called each method, so I decided to make paging explicit.  If I had
potentially millions of entities in SSDS, it would be a bad mistake to allow a developer
to issue a simple query that seamlessly paged the items back - especially if the query
was something like <em>e =&gt; e.Id != ""</em>.  Here is how I handled paging:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">var container = ctx.OpenContainer(<span style="color: #006080">"paging"</span>);
List&lt;Foo&gt; items = <span style="color: #0000ff">new</span> List&lt;Foo&gt;(); <span style="color: #0000ff">int</span> i
= 1; container.PagedQuery&lt;Foo&gt;( e =&gt; e.Entity.Size != 0, c =&gt; { Console.WriteLine(<span style="color: #006080">"Got
Page {0}"</span>, i++); items.AddRange(c.Select(s =&gt; s.Entity)); } ); Console.WriteLine(items.Count);</pre>
        </div>
        <p>
The <strong>PagedQuery&lt;T&gt;</strong> method takes two arguments.  One is
the standard <strong>Expression&lt;Func&lt;SsdsEntity&lt;T&gt;, bool&gt;&gt;</strong> that
you use to specify the WHERE clause for SSDS, and the other is <strong>Action&lt;IEnumerable&lt;SsdsEntity&lt;T&gt;&gt;&gt;</strong> which
represents a delegate that takes an <strong>IEnumerable&lt;SsdsEntity&lt;T&gt;&gt;</strong> and
has a void return.  This is a delegate you provide that does something with the
500 entities returned per page (it gets called once per page).  Here, I am just
adding them into a <strong>List&lt;T&gt;</strong>, but I could easily be doing anything
else here.  Under the covers, this is adding the paging term dynamically into
the expression tree that is evaluated.
</p>
        <h3>What's next
</h3>
        <p>
This is a good head start on using the REST API with SSDS today.  However, there
are a number of optimizations that could be made to the model: additional overloads,
perhaps some extension methods for common operations, etc. 
</p>
        <p>
As new features are added, I will endeavor to update this as well (blob support comes
to mind here).  Additionally, I have a few optimizations planned around concurrency
for CRUD operations.  
</p>
        <p>
I have published this out to Code Gallery and I welcome feedback and bug fixes.  <a href="http://code.msdn.microsoft.com/ssdsrest">Linked
here</a>.
</p>
        <img width="0" height="0" src="http://dunnry.com/blog/aggbug.ashx?id=b37072b9-1fe8-4785-9df3-00861ab346f7" />
      </body>
      <title>Working with Objects in SSDS Part 3</title>
      <guid isPermaLink="false">http://dunnry.com/blog/PermaLink,guid,b37072b9-1fe8-4785-9df3-00861ab346f7.aspx</guid>
      <link>http://dunnry.com/blog/WorkingWithObjectsInSSDSPart3.aspx</link>
      <pubDate>Wed, 02 Jul 2008 23:43:26 GMT</pubDate>
      <description>&lt;p&gt;
Here is my last installment in this series of working with objects in SQL Server Data
Services.&amp;nbsp; For background, readers should read the following:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://dunnry.com/blog/SerializationInSSDS.aspx"&gt;Serialization in SSDS&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://dunnry.com/blog/WorkingWithObjectsInSSDSPart1.aspx"&gt;Working with Objects
in SSDS Part 1&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://dunnry.com/blog/WorkingWithObjectsInSSDSPart2.aspx"&gt;Working with Objects
in SSDS Part 2&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Last time, we concluded with a class called &lt;strong&gt;SsdsEntity&amp;lt;T&amp;gt;&lt;/strong&gt; that
became an all-purpose wrapper or veneer around our CLR objects.&amp;nbsp; This made it
simple to take our existing classes and serialize them as entities in SSDS.
&lt;/p&gt;
&lt;p&gt;
In this post, I want to discuss how the querying in the REST library works.&amp;nbsp;
First a simple example:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;var ctx = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SsdsContext( &lt;span style="color: #006080"&gt;"authority=http://dunnry.data.beta.mssds.com/v1/;username=dunnry;password=secret"&lt;/span&gt; );
var container = ctx.OpenContainer(&lt;span style="color: #006080"&gt;"foo"&lt;/span&gt;); var
foo = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Foo { IsPublic = &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;,
Name = &lt;span style="color: #006080"&gt;"MyFoo"&lt;/span&gt;, Size = 12 }; &lt;span style="color: #008000"&gt;//insert
it with unique id guid string&lt;/span&gt; container.Insert(foo, Guid.NewGuid().ToString()); &lt;span style="color: #008000"&gt;//now
query for it&lt;/span&gt; var results = container.Query&amp;lt;Foo&amp;gt;(e =&amp;gt; e.Entity.IsPublic
== &lt;span style="color: #0000ff"&gt;false&lt;/span&gt; &amp;amp;&amp;amp; e.Entity.Size &amp;gt; 2); &lt;span style="color: #008000"&gt;//Query&amp;lt;T&amp;gt;
returns IEnumerable&amp;lt;SsdsEntity&amp;lt;T&amp;gt;&amp;gt;, so foreach over it&lt;/span&gt; &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (var
item &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; results) { Console.WriteLine(item.Entity.Name);
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I glossed over it in my previous posts with this library, but I have a class called &lt;strong&gt;SsdsContext&lt;/strong&gt; that
acts as my credential store and factory to create &lt;strong&gt;SsdsContainer&lt;/strong&gt; objects
where I perform my operations.&amp;nbsp; Here, I have opened a container called 'foo',
which would relate to the URI (&lt;a href="http://dunnry.data.beta.mssds.com/v1/foo"&gt;http://dunnry.data.beta.mssds.com/v1/foo&lt;/a&gt;)
according to the authority name I passed on the &lt;strong&gt;SsdsContext&lt;/strong&gt; constructor
arguments.
&lt;/p&gt;
&lt;p&gt;
I created an instance of my &lt;strong&gt;Foo&lt;/strong&gt; class (see &lt;a href="http://dunnry.com/blog/WorkingWithObjectsInSSDSPart1.aspx"&gt;this
post&lt;/a&gt; if you want to see what a &lt;strong&gt;Foo&lt;/strong&gt; looks like) and inserted it.&amp;nbsp;
We know that under the covers we have an &lt;strong&gt;XmlSerializer&lt;/strong&gt; doing the
work to serialize that to the proper POX wire format.&amp;nbsp; So far, so good.&amp;nbsp;
Now, I want to retrieve that same entity back from SSDS. The key line here is the
table.Query&amp;lt;T&amp;gt;() call.&amp;nbsp; It accepts a &lt;strong&gt;Expression&amp;lt;Func&amp;lt;SsdsEntity&amp;lt;T&amp;gt;,
bool&amp;gt;&amp;gt;&lt;/strong&gt; argument that represents a strongly typed query.
&lt;/p&gt;
&lt;p&gt;
For the uninitiated, the &lt;strong&gt;Expression&amp;lt;TDelegate&amp;gt;&lt;/strong&gt; is a way to
represent lambda expressions in an abstract syntax tree.&amp;nbsp; We can think of them
as a way to model what the expression does without generating the bits of code necessary
to actually do it.&amp;nbsp; We can inspect the &lt;strong&gt;Expression&lt;/strong&gt; and create
new ones based on it until finally we can call Compile and actually convert the representation
of the lambda into something that can execute.
&lt;/p&gt;
&lt;p&gt;
The &lt;strong&gt;Func&amp;lt;SsdsEntity&amp;lt;T&amp;gt;, bool&amp;gt;&lt;/strong&gt; represents a delegate that
accepts a &lt;strong&gt;SsdsEntity&amp;lt;T&amp;gt;&lt;/strong&gt; as an argument and returns a boolean.&amp;nbsp;
This effectively represents the WHERE clause in the SSDS LINQ query syntax.&amp;nbsp;
Since &lt;strong&gt;SsdsEntity&amp;lt;T&amp;gt;&lt;/strong&gt; contains an actual type T in the &lt;strong&gt;Entity&lt;/strong&gt; property,
you can query directly against it in a strongly typed fashion!
&lt;/p&gt;
&lt;p&gt;
What about those flexible properties that I added to support flexible attributes outside
of our T?&amp;nbsp; I mentioned that I wanted to keep the &lt;strong&gt;PropertyBucket&lt;/strong&gt; (a &lt;strong&gt;Dictionary&amp;lt;string,
object&amp;gt;&lt;/strong&gt;) property public for querying.&amp;nbsp; In order to use the flexible
properties that you add, you simply use it in a weakly typed manner:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;var results = container.Query&amp;lt;Foo&amp;gt;(e =&amp;gt; e.PropertyBucket[&lt;span style="color: #006080"&gt;"MyFlexProp"&lt;/span&gt;]
&amp;gt; 10);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
As you can see, any boolean expression that you can think of in the string-based SSDS
LINQ query syntax can now be expressed in a strongly-typed manner using the &lt;strong&gt;Func&amp;lt;SsdsEntity&amp;lt;T&amp;gt;,
bool&amp;gt;&lt;/strong&gt; lambda syntax.
&lt;/p&gt;
&lt;h3&gt;How it works
&lt;/h3&gt;
&lt;p&gt;
Since I have the expression tree of what your query looks like in strongly-typed terms,
it is a simple matter to take that and convert it to the SSDS LINQ query syntax that
looks like "from e in entities where [....] select e" that is appended to the query
string in the REST interface.&amp;nbsp; I should say it is a simple matter because &lt;a href="http://blogs.msdn.com/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx"&gt;Matt
Warren&lt;/a&gt; did a lot of the heavy lifting for us and provided the abstract expression
visitor (&lt;strong&gt;ExpressionVisitor&lt;/strong&gt;) as well as the expression visitor that
partially evaluates the tree to evaluate constants (&lt;strong&gt;SubTreeEvaluator&lt;/strong&gt;).&amp;nbsp;
This last part is important because it allows us to write this:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; i
= 10; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; name = &lt;span style="color: #006080"&gt;"MyFoo"&lt;/span&gt;;
var results = container.Query&amp;lt;Foo&amp;gt;(e =&amp;gt; e.Entity.Name == name &amp;amp;&amp;amp;
e.Entity.Size &amp;gt; i);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Without the partial tree evaluation, you would not be able to express the right hand
side of the equation.&amp;nbsp; All I had to do was implement an expression visitor that
correctly evaluated the lambda expression and converted it to the LINQ syntax that
SSDS expects (&lt;strong&gt;SsdsExpressionVisitor&lt;/strong&gt;).&amp;nbsp; It would be a trivial
matter to actually implement the &lt;strong&gt;IQueryProvider&lt;/strong&gt; and &lt;strong&gt;IQueryable&lt;/strong&gt; interfaces
to make the whole thing work inside LINQ to Objects.
&lt;/p&gt;
&lt;p&gt;
Originally, I did supply the &lt;strong&gt;IQueryProvider&lt;/strong&gt; for this implementation
but after consideration I have decided that using methods from the &lt;strong&gt;SsdsContainer&lt;/strong&gt; class
instead of the standard LINQ syntax is the best way to proceed.&amp;nbsp; Mainly, this
has to do with the fact that I want to make it more explicit to the developer what
will happen under the covers rather than using the standard &lt;strong&gt;Where()&lt;/strong&gt; extension
method.
&lt;/p&gt;
&lt;h3&gt;Querying data
&lt;/h3&gt;
&lt;p&gt;
The main interaction to return data is via the &lt;strong&gt;Query&amp;lt;T&amp;gt;&lt;/strong&gt; method.&amp;nbsp;
This method is smart enough to add the Kind into the query for you based on the T
supplied.&amp;nbsp; So, if you write something like:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;var results = container.Query&amp;lt;Foo&amp;gt;(e =&amp;gt; e.Entity.Size &amp;gt; 2);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is actually translated to "&lt;em&gt;from e in entities where e["Size"] &amp;gt; 2 &amp;amp;&amp;amp;
e.Kind == "Foo" select e&lt;/em&gt;".&amp;nbsp; The addition of the kind is important because
we want to limit the results as much as possible.&amp;nbsp; If there happened to be many
kinds in the container that had the flexible property "Size", it would actually return
those as well in the wire response.
&lt;/p&gt;
&lt;p&gt;
Of course, what about if you want that to happen?&amp;nbsp; What if you want to return
other kinds that have the "Size" property?&amp;nbsp; To do this, I have introduced a class
called &lt;strong&gt;SsdsEntityBucket&lt;/strong&gt;.&amp;nbsp; It is exactly what it sounds like.&amp;nbsp;
To use it, you simply specify a query that uses additional types with either the &lt;strong&gt;Query&amp;lt;T,U,V&amp;gt;&lt;/strong&gt; or &lt;strong&gt;Query&amp;lt;T,U&amp;gt;&lt;/strong&gt; methods.&amp;nbsp;
Here is an example:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;var foo = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Foo
{ IsPublic = &lt;span style="color: #0000ff"&gt;true&lt;/span&gt;, MyCheese = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Cheese
{ LastModified = DateTime.Now, Name = &lt;span style="color: #006080"&gt;"MyCheese"&lt;/span&gt; },
Name = &lt;span style="color: #006080"&gt;"FooMaster"&lt;/span&gt;, Size = 10 }; container.Insert(foo,
foo.Name); container.Insert(foo.MyCheese, foo.MyCheese.Name); &lt;span style="color: #008000"&gt;//query
for bucket...&lt;/span&gt; var bucket = container.Query&amp;lt;Foo, Cheese&amp;gt;( (f, c) =&amp;gt;
f.Entity.Name == &lt;span style="color: #006080"&gt;"FooMaster"&lt;/span&gt; || c.Entity.Name
== &lt;span style="color: #006080"&gt;"MyCheese"&lt;/span&gt; ); var f1 = bucket.GetEntities&amp;lt;Foo&amp;gt;().Single();
var c1 = bucket.GetEntities&amp;lt;Cheese&amp;gt;().Single();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The calls to &lt;strong&gt;GetEntities&amp;lt;T&amp;gt;&lt;/strong&gt; returns &lt;strong&gt;IEnumerable&amp;lt;SsdsEntity&amp;lt;T&amp;gt;&amp;gt;&lt;/strong&gt; again.&amp;nbsp;
However, this was done in a single call to SSDS instead of multiple calls per T.
&lt;/p&gt;
&lt;h3&gt;Paging
&lt;/h3&gt;
&lt;p&gt;
As I mentioned earlier, I wanted the developer to understand what they were doing
when they called each method, so I decided to make paging explicit.&amp;nbsp; If I had
potentially millions of entities in SSDS, it would be a bad mistake to allow a developer
to issue a simple query that seamlessly paged the items back - especially if the query
was something like &lt;em&gt;e =&amp;gt; e.Id != ""&lt;/em&gt;.&amp;nbsp; Here is how I handled paging:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;var container = ctx.OpenContainer(&lt;span style="color: #006080"&gt;"paging"&lt;/span&gt;);
List&amp;lt;Foo&amp;gt; items = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; List&amp;lt;Foo&amp;gt;(); &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; i
= 1; container.PagedQuery&amp;lt;Foo&amp;gt;( e =&amp;gt; e.Entity.Size != 0, c =&amp;gt; { Console.WriteLine(&lt;span style="color: #006080"&gt;"Got
Page {0}"&lt;/span&gt;, i++); items.AddRange(c.Select(s =&amp;gt; s.Entity)); } ); Console.WriteLine(items.Count);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The &lt;strong&gt;PagedQuery&amp;lt;T&amp;gt;&lt;/strong&gt; method takes two arguments.&amp;nbsp; One is
the standard &lt;strong&gt;Expression&amp;lt;Func&amp;lt;SsdsEntity&amp;lt;T&amp;gt;, bool&amp;gt;&amp;gt;&lt;/strong&gt; that
you use to specify the WHERE clause for SSDS, and the other is &lt;strong&gt;Action&amp;lt;IEnumerable&amp;lt;SsdsEntity&amp;lt;T&amp;gt;&amp;gt;&amp;gt;&lt;/strong&gt; which
represents a delegate that takes an &lt;strong&gt;IEnumerable&amp;lt;SsdsEntity&amp;lt;T&amp;gt;&amp;gt;&lt;/strong&gt; and
has a void return.&amp;nbsp; This is a delegate you provide that does something with the
500 entities returned per page (it gets called once per page).&amp;nbsp; Here, I am just
adding them into a &lt;strong&gt;List&amp;lt;T&amp;gt;&lt;/strong&gt;, but I could easily be doing anything
else here.&amp;nbsp; Under the covers, this is adding the paging term dynamically into
the expression tree that is evaluated.
&lt;/p&gt;
&lt;h3&gt;What's next
&lt;/h3&gt;
&lt;p&gt;
This is a good head start on using the REST API with SSDS today.&amp;nbsp; However, there
are a number of optimizations that could be made to the model: additional overloads,
perhaps some extension methods for common operations, etc. 
&lt;/p&gt;
&lt;p&gt;
As new features are added, I will endeavor to update this as well (blob support comes
to mind here).&amp;nbsp; Additionally, I have a few optimizations planned around concurrency
for CRUD operations.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
I have published this out to Code Gallery and I welcome feedback and bug fixes.&amp;nbsp; &lt;a href="http://code.msdn.microsoft.com/ssdsrest"&gt;Linked
here&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dunnry.com/blog/aggbug.ashx?id=b37072b9-1fe8-4785-9df3-00861ab346f7" /&gt;</description>
      <comments>http://dunnry.com/blog/CommentView,guid,b37072b9-1fe8-4785-9df3-00861ab346f7.aspx</comments>
      <category>.NET</category>
      <category>Cloud Services</category>
      <category>SSDS</category>
    </item>
    <item>
      <trackback:ping>http://dunnry.com/blog/Trackback.aspx?guid=bdbc0cbd-e845-49e9-9e43-52a079bda687</trackback:ping>
      <pingback:server>http://dunnry.com/blog/pingback.aspx</pingback:server>
      <pingback:target>http://dunnry.com/blog/PermaLink,guid,bdbc0cbd-e845-49e9-9e43-52a079bda687.aspx</pingback:target>
      <dc:creator>Ryan Dunn</dc:creator>
      <wfw:comment>http://dunnry.com/blog/CommentView,guid,bdbc0cbd-e845-49e9-9e43-52a079bda687.aspx</wfw:comment>
      <wfw:commentRss>http://dunnry.com/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=bdbc0cbd-e845-49e9-9e43-52a079bda687</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is the second post in my series on working with SQL Server Data Service (SSDS)
and objects.  For background, you should read my post on <a href="http://dunnry.com/blog/SerializationInSSDS.aspx">Serializing
Objects in SSDS</a> and the <a href="http://dunnry.com/blog/WorkingWithObjectsInSSDSPart1.aspx">first
post</a> in this series.
</p>
        <p>
Last time I showed how to create a general purpose serializer for SSDS using the standard <strong>XmlSerializer</strong> class
in .NET.  I created a shell entity or a 'thin veneer' for objects called <strong>SsdsEntity&lt;T&gt;</strong>,
where T was any POCO (plain old C#/CLR object).  This allowed me to abstract
away the metadata properties required for SSDS without changing my actual POCO object
(which, I noted was lame to do).
</p>
        <p>
If we decide that we will use SSDS to interact with POCO T, an interesting situation
arises.  Namely, once we have defined T, we have in fact defined a schema - albeit
one only enforced in code you write and not by the SSDS service itself.  One
of the advantages of using something like SSDS is that you have a lot of flexibility
in storing entities  (hence the term 'flexible entity') without conforming to
schema.  Since, I want to support this flexibility, it means I need to think
of a way to support not only the schema implied by T, but also additional and arbitrary
properties that a user might consider.
</p>
        <p>
Some may wonder why we need this flexibility:  after all, why not just change
T to support whatever we like?  The issue comes up most often with code you do
not control.  If you already have an existing codebase with objects that you
would like to store in SSDS, it might not be practical or even possible to change
the T to add additional schema.
</p>
        <p>
Even if you completely control the codebase, expressing relationships between CLR
objects and expressing relationships between things in your data are two different
ideas - sometimes this problem has been termed 'impedance mismatch'.
</p>
        <p>
In the CLR, if two objects are related, they are often part of a collection, or they
refer to an instance on another object.  This is easy to express in the CLR (e.g. <strong>Instance.ChildrenCollection["key"]</strong>). 
In your typical datasource, this same relationship is done using foreign keys to refer
to other entities.
</p>
        <p>
Consider the following classes:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">public</span>
            <span style="color: #0000ff">class</span> Employee
{ <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> EmployeeId
{ get; set; } <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> Name
{ get; set; } <span style="color: #0000ff">public</span> DateTime HireDate { get;
set; } <span style="color: #0000ff">public</span> Employee Manager { get; set; } <span style="color: #0000ff">public</span> Project[]
Projects { get; set; } } <span style="color: #0000ff">public</span><span style="color: #0000ff">class</span> Project
{ <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> ProjectId
{ get; set; } <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> Name
{ get; set; } <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> BillCode
{ get; set; } }</pre>
        </div>
        <p>
Here we see that the <strong>Employee</strong> class refers to itself as well as contains
a collection of related projects (<strong>Project</strong> class) that the employee
works on.  SSDS only supports simple scalar types and no arrays or nested objects
today, so we cannot directly express this in SSDS.  However, we can decompose
this class and store the bits separately and then reassemble later.  First, let's
see what that looks like and then we can see how it was done:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">var projects = <span style="color: #0000ff">new</span> Project[]
{ <span style="color: #0000ff">new</span> Project { BillCode = <span style="color: #006080">"123"</span>,
Name = <span style="color: #006080">"TPS Slave"</span>, ProjectId = <span style="color: #006080">"PID01"</span>}, <span style="color: #0000ff">new</span> Project
{ BillCode = <span style="color: #006080">"124"</span>, Name = <span style="color: #006080">"Programmer"</span>,
ProjectId = <span style="color: #006080">"PID02"</span> } }; var bill = <span style="color: #0000ff">new</span> Employee
{ EmployeeId = <span style="color: #006080">"EMP01"</span>, HireDate = DateTime.Now.AddMonths(-1),
Manager = <span style="color: #0000ff">null</span>, Name = <span style="color: #006080">"Bill
Lumbergh"</span>, Projects = <span style="color: #0000ff">new</span> Project[] {}
}; var peter = <span style="color: #0000ff">new</span> Employee { EmployeeId = <span style="color: #006080">"EMP02"</span>,
HireDate = DateTime.Now, Manager = bill, Name = <span style="color: #006080">"Peter
Gibbons"</span>, Projects = projects }; var cloudpeter = <span style="color: #0000ff">new</span> SsdsEntity&lt;Employee&gt;
{ Entity = peter, Id = peter.EmployeeId }; var cloudbill = <span style="color: #0000ff">new</span> SsdsEntity&lt;Employee&gt;
{ Entity = bill, Id = bill.EmployeeId }; <span style="color: #008000">//here is how
we add flexible props</span> cloudpeter.Add&lt;<span style="color: #0000ff">string</span>&gt;(<span style="color: #006080">"ManagerId"</span>,
peter.Manager.EmployeeId); var table = _context.OpenContainer(<span style="color: #006080">"initech"</span>);
table.Insert(cloudpeter); table.Insert(cloudbill); var cloudprojects = peter.Projects
.Select(s =&gt; <span style="color: #0000ff">new</span> SsdsEntity&lt;Project&gt;
{ Entity = s, Id = Guid.NewGuid().ToString() }); <span style="color: #008000">//add
some metadata to track the project to employee</span><span style="color: #0000ff">foreach</span> (var
proj <span style="color: #0000ff">in</span> cloudprojects) { proj.Add&lt;<span style="color: #0000ff">string</span>&gt;(<span style="color: #006080">"RelatedEmployee"</span>,
peter.EmployeeId); table.Insert(proj); }</pre>
        </div>
        <p>
All this code does is create two employees and two projects and set the relationships
between them.  Using the <strong>Add&lt;K&gt;</strong> method, I can insert any
primitive type to go along for the ride with the POCO.  If we query the container
now, this is what we see:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">&lt;</span>
            <span style="color: #800000">s:EntitySet</span>
            <span style="color: #ff0000">xmlns:s</span>
            <span style="color: #0000ff">="http://schemas.microsoft.com/sitka/2008/03/"</span>
            <span style="color: #ff0000">xmlns:xsi</span>
            <span style="color: #0000ff">="http://www.w3.org/2001/XMLSchema-instance"</span>
            <span style="color: #ff0000">xmlns:x</span>
            <span style="color: #0000ff">="http://www.w3.org/2001/XMLSchema"</span>
            <span style="color: #0000ff">&gt;</span>
            <span style="color: #0000ff">&lt;</span>
            <span style="color: #800000">Project</span>
            <span style="color: #0000ff">&gt;</span>
            <span style="color: #0000ff">&lt;</span>
            <span style="color: #800000">s:Id</span>
            <span style="color: #0000ff">&gt;</span>2ffd7a92-2a3b-4cd8-a5f7-55f40c3ba2b0<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Id</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span>1<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">ProjectId</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>PID01<span style="color: #0000ff">&lt;/</span><span style="color: #800000">ProjectId</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Name</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>TPS
Slave<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Name</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">BillCode</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>123<span style="color: #0000ff">&lt;/</span><span style="color: #800000">BillCode</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">RelatedEmployee</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>EMP02<span style="color: #0000ff">&lt;/</span><span style="color: #800000">RelatedEmployee</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;/</span><span style="color: #800000">Project</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Project</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Id</span><span style="color: #0000ff">&gt;</span>892dbb1e-ba47-4c87-80e6-64fbb46da935<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Id</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span>1<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">ProjectId</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>PID02<span style="color: #0000ff">&lt;/</span><span style="color: #800000">ProjectId</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Name</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>Programmer<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Name</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">BillCode</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>124<span style="color: #0000ff">&lt;/</span><span style="color: #800000">BillCode</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">RelatedEmployee</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>EMP02<span style="color: #0000ff">&lt;/</span><span style="color: #800000">RelatedEmployee</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;/</span><span style="color: #800000">Project</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Employee</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Id</span><span style="color: #0000ff">&gt;</span>EMP01<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Id</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span>1<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">EmployeeId</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>EMP01<span style="color: #0000ff">&lt;/</span><span style="color: #800000">EmployeeId</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Name</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>Bill
Lumbergh<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Name</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">HireDate</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:dateTime"</span><span style="color: #0000ff">&gt;</span>2008-05-25T23:59:49<span style="color: #0000ff">&lt;/</span><span style="color: #800000">HireDate</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;/</span><span style="color: #800000">Employee</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Employee</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Id</span><span style="color: #0000ff">&gt;</span>EMP02<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Id</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span>1<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">EmployeeId</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>EMP02<span style="color: #0000ff">&lt;/</span><span style="color: #800000">EmployeeId</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Name</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>Peter
Gibbons<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Name</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">HireDate</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:dateTime"</span><span style="color: #0000ff">&gt;</span>2008-06-25T23:59:49<span style="color: #0000ff">&lt;/</span><span style="color: #800000">HireDate</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">ManagerId</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>EMP01<span style="color: #0000ff">&lt;/</span><span style="color: #800000">ManagerId</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;/</span><span style="color: #800000">Employee</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:EntitySet</span><span style="color: #0000ff">&gt;</span></pre>
        </div>
        <p>
As you can see, I have stored extra data in my 'flexible' entity with the <strong>ManagerId</strong> property
(on one entity) and <strong>RelatedEmployee</strong> property on the <strong>Project</strong> kinds. 
This allows me to figure out later what objects are related to each other since we
can't model the CLR objects relationships directly.  Let's see how this was done.
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">public</span>
            <span style="color: #0000ff">class</span> SsdsEntity&lt;T&gt; <span style="color: #0000ff">where</span> T: <span style="color: #0000ff">class</span> {
Dictionary&lt;<span style="color: #0000ff">string</span>, <span style="color: #0000ff">object</span>&gt;
_propertyBucket = <span style="color: #0000ff">new</span> Dictionary&lt;<span style="color: #0000ff">string</span>, <span style="color: #0000ff">object</span>&gt;(); <span style="color: #0000ff">public</span> SsdsEntity()
{ } [XmlIgnore] <span style="color: #0000ff">public</span> Dictionary&lt;<span style="color: #0000ff">string</span>, <span style="color: #0000ff">object</span>&gt;
PropertyBucket { get { <span style="color: #0000ff">return</span> _propertyBucket;
} } [XmlAnyElement] <span style="color: #0000ff">public</span> XElement[] Attributes
{ get { <span style="color: #008000">//using XElement is much easier than XmlElement
to build</span><span style="color: #008000">//take all properties on object instance
and build XElement</span> var props = from prop <span style="color: #0000ff">in</span><span style="color: #0000ff">typeof</span>(T).GetProperties()
let val = prop.GetValue(<span style="color: #0000ff">this</span>.Entity, <span style="color: #0000ff">null</span>) <span style="color: #0000ff">where</span> prop.GetSetMethod()
!= <span style="color: #0000ff">null</span> &amp;&amp; allowableTypes.Contains(prop.PropertyType)
&amp;&amp; val != <span style="color: #0000ff">null</span> select <span style="color: #0000ff">new</span> XElement(prop.Name, <span style="color: #0000ff">new</span> XAttribute(Constants.xsi
+ <span style="color: #006080">"type"</span>, XsdTypeResolver.Solve(prop.PropertyType)),
EncodeValue(val) ); <span style="color: #008000">//Then stuff in any extra stuff you
want</span> var extra = _propertyBucket.Select( e =&gt; <span style="color: #0000ff">new</span> XElement(e.Key, <span style="color: #0000ff">new</span> XAttribute(Constants.xsi
+ <span style="color: #006080">"type"</span>, XsdTypeResolver.Solve(e.Value.GetType())),
EncodeValue(e.Value) ) ); <span style="color: #0000ff">return</span> props.Union(extra).ToArray();
} set { <span style="color: #008000">//wrap the XElement[] with the name of the type</span> var
xml = <span style="color: #0000ff">new</span> XElement(<span style="color: #0000ff">typeof</span>(T).Name, <span style="color: #0000ff">value</span>);
var xs = <span style="color: #0000ff">new</span> XmlSerializer(<span style="color: #0000ff">typeof</span>(T)); <span style="color: #008000">//xml.CreateReader()
cannot be used as it won't support base64 content</span> XmlTextReader reader = <span style="color: #0000ff">new</span> XmlTextReader(
xml.ToString(), XmlNodeType.Document, <span style="color: #0000ff">null</span> ); <span style="color: #0000ff">this</span>.Entity
= (T)xs.Deserialize(reader); <span style="color: #008000">//now deserialize the other
stuff left over into the property bucket...</span> var stuff = from v <span style="color: #0000ff">in</span><span style="color: #0000ff">value</span>.AsEnumerable()
let props = <span style="color: #0000ff">typeof</span>(T).GetProperties().Select(s
=&gt; s.Name) <span style="color: #0000ff">where</span> !props.Contains(v.Name.ToString())
select v; <span style="color: #0000ff">foreach</span> (var item <span style="color: #0000ff">in</span> stuff)
{ _propertyBucket.Add( item.Name.ToString(), DecodeValue( item.Attribute(Constants.xsi
+ <span style="color: #006080">"type"</span>).Value, item.Value) ); } } } <span style="color: #0000ff">public</span><span style="color: #0000ff">void</span> Add&lt;K&gt;(<span style="color: #0000ff">string</span> key,
K <span style="color: #0000ff">value</span>) { <span style="color: #0000ff">if</span> (!allowableTypes.Contains(<span style="color: #0000ff">typeof</span>(K))) <span style="color: #0000ff">throw</span><span style="color: #0000ff">new</span> ArgumentException(
String.Format( <span style="color: #006080">"Type {0} not supported in SsdsEntity"</span>, <span style="color: #0000ff">typeof</span>(K).Name)
); <span style="color: #0000ff">if</span> (!_propertyBucket.ContainsKey(key)) { _propertyBucket.Add(key, <span style="color: #0000ff">value</span>);
} <span style="color: #0000ff">else</span> { <span style="color: #008000">//replace
the value</span> _propertyBucket.Remove(key); _propertyBucket.Add(key, <span style="color: #0000ff">value</span>);
} } }</pre>
        </div>
        <p>
I have omitted the parts of <strong>SsdsEntity&lt;T&gt;</strong> from the first post
that didn't change.  The only other addition you don't see here is a helper method
called <strong>DecodeValue</strong>, which as you might guess, interprets the string
value in XML and attempts to cast it to a CLR type based on the xsi:type that comes
back.
</p>
        <p>
All we did here was add a <strong>Dictionary&lt;string, object&gt;</strong> property
called <strong>PropertyBucket</strong> that holds our extra stuff we want to associate
with our T instance.  Then in the getter and setter for the <strong>XElement[]</strong> property
called <strong>Attributes</strong>, we are adding them into our array of <strong>XElement</strong> as
well as pulling them back out on deserialization and stuffing them back into the Dictionary. 
With this simple addition, we have fixed our in flexibility (or lack thereof) problem. 
We are still limited to the simple scalar types, but as you can see you can work around
this in a lot of cases by decomposing the objects down enough to be able to recreate
them later.
</p>
        <p>
The <strong>Add&lt;K&gt;</strong> method is a convenience only as we could operate
directly against the Dictionary.  I also could have chosen to keep the Dictionary
property bucket private and not expose it.  That would have worked just fine
for serialization, but I wanted to also be able to query it later.
</p>
        <p>
In my last post, I said I would introduce a library where all this code is coming
from, but I didn't realize at the time how long this post would be and that I still
need to cover querying.  So... next time, I will finish up this series by explaining
how the strongly typed query model works and how all these pieces fit together to
recompose the data back into objects (and release the library).
</p>
        <img width="0" height="0" src="http://dunnry.com/blog/aggbug.ashx?id=bdbc0cbd-e845-49e9-9e43-52a079bda687" />
      </body>
      <title>Working with Objects in SSDS Part 2</title>
      <guid isPermaLink="false">http://dunnry.com/blog/PermaLink,guid,bdbc0cbd-e845-49e9-9e43-52a079bda687.aspx</guid>
      <link>http://dunnry.com/blog/WorkingWithObjectsInSSDSPart2.aspx</link>
      <pubDate>Thu, 26 Jun 2008 20:03:54 GMT</pubDate>
      <description>&lt;p&gt;
This is the second post in my series on working with SQL Server Data Service (SSDS)
and objects.&amp;nbsp; For background, you should read my post on &lt;a href="http://dunnry.com/blog/SerializationInSSDS.aspx"&gt;Serializing
Objects in SSDS&lt;/a&gt; and the &lt;a href="http://dunnry.com/blog/WorkingWithObjectsInSSDSPart1.aspx"&gt;first
post&lt;/a&gt; in this series.
&lt;/p&gt;
&lt;p&gt;
Last time I showed how to create a general purpose serializer for SSDS using the standard &lt;strong&gt;XmlSerializer&lt;/strong&gt; class
in .NET.&amp;nbsp; I created a shell entity or a 'thin veneer' for objects called &lt;strong&gt;SsdsEntity&amp;lt;T&amp;gt;&lt;/strong&gt;,
where T was any POCO (plain old C#/CLR object).&amp;nbsp; This allowed me to abstract
away the metadata properties required for SSDS without changing my actual POCO object
(which, I noted was lame to do).
&lt;/p&gt;
&lt;p&gt;
If we decide that we will use SSDS to interact with POCO T, an interesting situation
arises.&amp;nbsp; Namely, once we have defined T, we have in fact defined a schema - albeit
one only enforced in code you write and not by the SSDS service itself.&amp;nbsp; One
of the advantages of using something like SSDS is that you have a lot of flexibility
in storing entities&amp;nbsp; (hence the term 'flexible entity') without conforming to
schema.&amp;nbsp; Since, I want to support this flexibility, it means I need to think
of a way to support not only the schema implied by T, but also additional and arbitrary
properties that a user might consider.
&lt;/p&gt;
&lt;p&gt;
Some may wonder why we need this flexibility:&amp;nbsp; after all, why not just change
T to support whatever we like?&amp;nbsp; The issue comes up most often with code you do
not control.&amp;nbsp; If you already have an existing codebase with objects that you
would like to store in SSDS, it might not be practical or even possible to change
the T to add additional schema.
&lt;/p&gt;
&lt;p&gt;
Even if you completely control the codebase, expressing relationships between CLR
objects and expressing relationships between things in your data are two different
ideas - sometimes this problem has been termed 'impedance mismatch'.
&lt;/p&gt;
&lt;p&gt;
In the CLR, if two objects are related, they are often part of a collection, or they
refer to an instance on another object.&amp;nbsp; This is easy to express in the CLR (e.g. &lt;strong&gt;Instance.ChildrenCollection["key"]&lt;/strong&gt;).&amp;nbsp;
In your typical datasource, this same relationship is done using foreign keys to refer
to other entities.
&lt;/p&gt;
&lt;p&gt;
Consider the following classes:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Employee
{ &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; EmployeeId
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Name
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; DateTime HireDate { get;
set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Employee Manager { get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Project[]
Projects { get; set; } } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Project
{ &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; ProjectId
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Name
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; BillCode
{ get; set; } }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Here we see that the &lt;strong&gt;Employee&lt;/strong&gt; class refers to itself as well as contains
a collection of related projects (&lt;strong&gt;Project&lt;/strong&gt; class) that the employee
works on.&amp;nbsp; SSDS only supports simple scalar types and no arrays or nested objects
today, so we cannot directly express this in SSDS.&amp;nbsp; However, we can decompose
this class and store the bits separately and then reassemble later.&amp;nbsp; First, let's
see what that looks like and then we can see how it was done:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;var projects = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Project[]
{ &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Project { BillCode = &lt;span style="color: #006080"&gt;"123"&lt;/span&gt;,
Name = &lt;span style="color: #006080"&gt;"TPS Slave"&lt;/span&gt;, ProjectId = &lt;span style="color: #006080"&gt;"PID01"&lt;/span&gt;}, &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Project
{ BillCode = &lt;span style="color: #006080"&gt;"124"&lt;/span&gt;, Name = &lt;span style="color: #006080"&gt;"Programmer"&lt;/span&gt;,
ProjectId = &lt;span style="color: #006080"&gt;"PID02"&lt;/span&gt; } }; var bill = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Employee
{ EmployeeId = &lt;span style="color: #006080"&gt;"EMP01"&lt;/span&gt;, HireDate = DateTime.Now.AddMonths(-1),
Manager = &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;, Name = &lt;span style="color: #006080"&gt;"Bill
Lumbergh"&lt;/span&gt;, Projects = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Project[] {}
}; var peter = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Employee { EmployeeId = &lt;span style="color: #006080"&gt;"EMP02"&lt;/span&gt;,
HireDate = DateTime.Now, Manager = bill, Name = &lt;span style="color: #006080"&gt;"Peter
Gibbons"&lt;/span&gt;, Projects = projects }; var cloudpeter = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SsdsEntity&amp;lt;Employee&amp;gt;
{ Entity = peter, Id = peter.EmployeeId }; var cloudbill = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SsdsEntity&amp;lt;Employee&amp;gt;
{ Entity = bill, Id = bill.EmployeeId }; &lt;span style="color: #008000"&gt;//here is how
we add flexible props&lt;/span&gt; cloudpeter.Add&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;(&lt;span style="color: #006080"&gt;"ManagerId"&lt;/span&gt;,
peter.Manager.EmployeeId); var table = _context.OpenContainer(&lt;span style="color: #006080"&gt;"initech"&lt;/span&gt;);
table.Insert(cloudpeter); table.Insert(cloudbill); var cloudprojects = peter.Projects
.Select(s =&amp;gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SsdsEntity&amp;lt;Project&amp;gt;
{ Entity = s, Id = Guid.NewGuid().ToString() }); &lt;span style="color: #008000"&gt;//add
some metadata to track the project to employee&lt;/span&gt; &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (var
proj &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; cloudprojects) { proj.Add&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;(&lt;span style="color: #006080"&gt;"RelatedEmployee"&lt;/span&gt;,
peter.EmployeeId); table.Insert(proj); }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
All this code does is create two employees and two projects and set the relationships
between them.&amp;nbsp; Using the &lt;strong&gt;Add&amp;lt;K&amp;gt;&lt;/strong&gt; method, I can insert any
primitive type to go along for the ride with the POCO.&amp;nbsp; If we query the container
now, this is what we see:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:EntitySet&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xmlns:s&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="http://schemas.microsoft.com/sitka/2008/03/"&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xmlns:xsi&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="http://www.w3.org/2001/XMLSchema-instance"&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xmlns:x&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="http://www.w3.org/2001/XMLSchema"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Project&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;2ffd7a92-2a3b-4cd8-a5f7-55f40c3ba2b0&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;1&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;ProjectId&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;PID01&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;ProjectId&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;TPS
Slave&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;BillCode&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;123&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;BillCode&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;RelatedEmployee&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;EMP02&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;RelatedEmployee&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Project&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Project&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;892dbb1e-ba47-4c87-80e6-64fbb46da935&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;1&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;ProjectId&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;PID02&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;ProjectId&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;Programmer&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;BillCode&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;124&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;BillCode&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;RelatedEmployee&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;EMP02&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;RelatedEmployee&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Project&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Employee&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;EMP01&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;1&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;EmployeeId&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;EMP01&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;EmployeeId&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;Bill
Lumbergh&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;HireDate&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:dateTime"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;2008-05-25T23:59:49&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;HireDate&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Employee&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Employee&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;EMP02&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;1&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;EmployeeId&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;EMP02&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;EmployeeId&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;Peter
Gibbons&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;HireDate&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:dateTime"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;2008-06-25T23:59:49&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;HireDate&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;ManagerId&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;EMP01&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;ManagerId&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Employee&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:EntitySet&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
As you can see, I have stored extra data in my 'flexible' entity with the &lt;strong&gt;ManagerId&lt;/strong&gt; property
(on one entity) and &lt;strong&gt;RelatedEmployee&lt;/strong&gt; property on the &lt;strong&gt;Project&lt;/strong&gt; kinds.&amp;nbsp;
This allows me to figure out later what objects are related to each other since we
can't model the CLR objects relationships directly.&amp;nbsp; Let's see how this was done.
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; SsdsEntity&amp;lt;T&amp;gt; &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; T: &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; {
Dictionary&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;, &lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&amp;gt;
_propertyBucket = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Dictionary&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;, &lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&amp;gt;(); &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; SsdsEntity()
{ } [XmlIgnore] &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Dictionary&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;, &lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&amp;gt;
PropertyBucket { get { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; _propertyBucket;
} } [XmlAnyElement] &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; XElement[] Attributes
{ get { &lt;span style="color: #008000"&gt;//using XElement is much easier than XmlElement
to build&lt;/span&gt; &lt;span style="color: #008000"&gt;//take all properties on object instance
and build XElement&lt;/span&gt; var props = from prop &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; &lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T).GetProperties()
let val = prop.GetValue(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt;.Entity, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;) &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; prop.GetSetMethod()
!= &lt;span style="color: #0000ff"&gt;null&lt;/span&gt; &amp;amp;&amp;amp; allowableTypes.Contains(prop.PropertyType)
&amp;amp;&amp;amp; val != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt; select &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XElement(prop.Name, &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XAttribute(Constants.xsi
+ &lt;span style="color: #006080"&gt;"type"&lt;/span&gt;, XsdTypeResolver.Solve(prop.PropertyType)),
EncodeValue(val) ); &lt;span style="color: #008000"&gt;//Then stuff in any extra stuff you
want&lt;/span&gt; var extra = _propertyBucket.Select( e =&amp;gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XElement(e.Key, &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XAttribute(Constants.xsi
+ &lt;span style="color: #006080"&gt;"type"&lt;/span&gt;, XsdTypeResolver.Solve(e.Value.GetType())),
EncodeValue(e.Value) ) ); &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; props.Union(extra).ToArray();
} set { &lt;span style="color: #008000"&gt;//wrap the XElement[] with the name of the type&lt;/span&gt; var
xml = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XElement(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T).Name, &lt;span style="color: #0000ff"&gt;value&lt;/span&gt;);
var xs = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlSerializer(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T)); &lt;span style="color: #008000"&gt;//xml.CreateReader()
cannot be used as it won't support base64 content&lt;/span&gt; XmlTextReader reader = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlTextReader(
xml.ToString(), XmlNodeType.Document, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt; ); &lt;span style="color: #0000ff"&gt;this&lt;/span&gt;.Entity
= (T)xs.Deserialize(reader); &lt;span style="color: #008000"&gt;//now deserialize the other
stuff left over into the property bucket...&lt;/span&gt; var stuff = from v &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; &lt;span style="color: #0000ff"&gt;value&lt;/span&gt;.AsEnumerable()
let props = &lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T).GetProperties().Select(s
=&amp;gt; s.Name) &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; !props.Contains(v.Name.ToString())
select v; &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (var item &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; stuff)
{ _propertyBucket.Add( item.Name.ToString(), DecodeValue( item.Attribute(Constants.xsi
+ &lt;span style="color: #006080"&gt;"type"&lt;/span&gt;).Value, item.Value) ); } } } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Add&amp;lt;K&amp;gt;(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; key,
K &lt;span style="color: #0000ff"&gt;value&lt;/span&gt;) { &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (!allowableTypes.Contains(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(K))) &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; ArgumentException(
String.Format( &lt;span style="color: #006080"&gt;"Type {0} not supported in SsdsEntity"&lt;/span&gt;, &lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(K).Name)
); &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (!_propertyBucket.ContainsKey(key)) { _propertyBucket.Add(key, &lt;span style="color: #0000ff"&gt;value&lt;/span&gt;);
} &lt;span style="color: #0000ff"&gt;else&lt;/span&gt; { &lt;span style="color: #008000"&gt;//replace
the value&lt;/span&gt; _propertyBucket.Remove(key); _propertyBucket.Add(key, &lt;span style="color: #0000ff"&gt;value&lt;/span&gt;);
} } }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I have omitted the parts of &lt;strong&gt;SsdsEntity&amp;lt;T&amp;gt;&lt;/strong&gt; from the first post
that didn't change.&amp;nbsp; The only other addition you don't see here is a helper method
called &lt;strong&gt;DecodeValue&lt;/strong&gt;, which as you might guess, interprets the string
value in XML and attempts to cast it to a CLR type based on the xsi:type that comes
back.
&lt;/p&gt;
&lt;p&gt;
All we did here was add a &lt;strong&gt;Dictionary&amp;lt;string, object&amp;gt;&lt;/strong&gt; property
called &lt;strong&gt;PropertyBucket&lt;/strong&gt; that holds our extra stuff we want to associate
with our T instance.&amp;nbsp; Then in the getter and setter for the &lt;strong&gt;XElement[]&lt;/strong&gt; property
called &lt;strong&gt;Attributes&lt;/strong&gt;, we are adding them into our array of &lt;strong&gt;XElement&lt;/strong&gt; as
well as pulling them back out on deserialization and stuffing them back into the Dictionary.&amp;nbsp;
With this simple addition, we have fixed our in flexibility (or lack thereof) problem.&amp;nbsp;
We are still limited to the simple scalar types, but as you can see you can work around
this in a lot of cases by decomposing the objects down enough to be able to recreate
them later.
&lt;/p&gt;
&lt;p&gt;
The &lt;strong&gt;Add&amp;lt;K&amp;gt;&lt;/strong&gt; method is a convenience only as we could operate
directly against the Dictionary.&amp;nbsp; I also could have chosen to keep the Dictionary
property bucket private and not expose it.&amp;nbsp; That would have worked just fine
for serialization, but I wanted to also be able to query it later.
&lt;/p&gt;
&lt;p&gt;
In my last post, I said I would introduce a library where all this code is coming
from, but I didn't realize at the time how long this post would be and that I still
need to cover querying.&amp;nbsp; So... next time, I will finish up this series by explaining
how the strongly typed query model works and how all these pieces fit together to
recompose the data back into objects (and release the library).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dunnry.com/blog/aggbug.ashx?id=bdbc0cbd-e845-49e9-9e43-52a079bda687" /&gt;</description>
      <comments>http://dunnry.com/blog/CommentView,guid,bdbc0cbd-e845-49e9-9e43-52a079bda687.aspx</comments>
      <category>.NET</category>
      <category>Cloud Services</category>
      <category>SSDS</category>
    </item>
    <item>
      <trackback:ping>http://dunnry.com/blog/Trackback.aspx?guid=2021b648-8af2-4702-95f5-c5ec1455c1e1</trackback:ping>
      <pingback:server>http://dunnry.com/blog/pingback.aspx</pingback:server>
      <pingback:target>http://dunnry.com/blog/PermaLink,guid,2021b648-8af2-4702-95f5-c5ec1455c1e1.aspx</pingback:target>
      <dc:creator>Ryan Dunn</dc:creator>
      <wfw:comment>http://dunnry.com/blog/CommentView,guid,2021b648-8af2-4702-95f5-c5ec1455c1e1.aspx</wfw:comment>
      <wfw:commentRss>http://dunnry.com/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=2021b648-8af2-4702-95f5-c5ec1455c1e1</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://dunnry.com/blog/SerializationInSSDS.aspx">Last time</a> we talked
about SQL Server Data Services and serializing objects, we discussed how easy it was
to use the <strong>XmlSerializer</strong> to deserialize objects using the REST interface. 
The problem was that when we serialized objects using the <strong>XmlSerializer</strong>,
it left out the xsi type declarations that we needed.  I gave two possible solutions
to this problem - one that used the <strong>XmlSerializer</strong> and 'fixed' the
output after the fact, and the other built the XML that we needed using XLINQ and
Reflection.
</p>
        <p>
Today, I am going to talk about a third technique that I have been using lately that
I like better.  It uses some of the previous techniques and leverages a few tricks
with <strong>XmlSerializer</strong> to get what I want.  First, let's start with
a POCO (plain ol' C# object) class that we would like to use with SSDS.
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">public</span>
            <span style="color: #0000ff">class</span> Foo
{ <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> Name
{ get; set; } <span style="color: #0000ff">public</span><span style="color: #0000ff">int</span> Size
{ get; set; } <span style="color: #0000ff">public</span><span style="color: #0000ff">bool</span> IsPublic
{ get; set; } }</pre>
        </div>
        <p>
In it's correctly serialized form, it looks like this on the wire:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">&lt;</span>
            <span style="color: #800000">Foo</span>
            <span style="color: #ff0000">xmlns:s</span>
            <span style="color: #0000ff">="http://schemas.microsoft.com/sitka/2008/03/"</span>
            <span style="color: #ff0000">xmlns:xsi</span>
            <span style="color: #0000ff">="http://www.w3.org/2001/XMLSchema-instance"</span>
            <span style="color: #ff0000">xmlns:x</span>
            <span style="color: #0000ff">="http://www.w3.org/2001/XMLSchema"</span>
            <span style="color: #0000ff">&gt;</span>
            <span style="color: #0000ff">&lt;</span>
            <span style="color: #800000">s:Id</span>
            <span style="color: #0000ff">&gt;</span>someid<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Id</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span>1<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Version</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Name</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:string"</span><span style="color: #0000ff">&gt;</span>My
Foo<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Name</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">Size</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:decimal"</span><span style="color: #0000ff">&gt;</span>10<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Size</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;</span><span style="color: #800000">IsPublic</span><span style="color: #ff0000">xsi:type</span><span style="color: #0000ff">="x:boolean"</span><span style="color: #0000ff">&gt;</span>false<span style="color: #0000ff">&lt;/</span><span style="color: #800000">IsPublic</span><span style="color: #0000ff">&gt;</span><span style="color: #0000ff">&lt;/</span><span style="color: #800000">Foo</span><span style="color: #0000ff">&gt;</span></pre>
        </div>
        <p>
You'll notice that we have the additional system metadata attributes "Id" and "Version"
in the markup.  We can account for the metadata attributes by doing something
cheesy like deriving from a base class:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">public</span>
            <span style="color: #0000ff">abstract</span>
            <span style="color: #0000ff">class</span> Cheese
{ <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> Id
{ get; set; } <span style="color: #0000ff">public</span><span style="color: #0000ff">int</span> Version
{ get; set; } }</pre>
        </div>
        <p>
However this is very unnatural as our classes would all have to derive from our "Cheese"
abstract base class (ABC).
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">public</span>
            <span style="color: #0000ff">class</span> Foo
: Cheese { <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> Name
{ get; set; } <span style="color: #0000ff">public</span><span style="color: #0000ff">int</span> Size
{ get; set; } <span style="color: #0000ff">public</span><span style="color: #0000ff">bool</span> IsPublic
{ get; set; } }</pre>
        </div>
        <p>
Developers familiar with remoting in .NET should be cringing right now as they remember
the hassles associated with deriving from <strong>MarshalByRefObject</strong>. 
In a world without multiple inheritance, this can be painful.  I want a model
where I can use arbitrary POCO objects (<a href="http://haacked.com/archive/2008/06/13/ras-syndrome.aspx">redundant</a>,
yes I know) and not be forced to derive from anything or do what I would otherwise
term unnatural acts.
</p>
        <p>
What if instead, we derived a generic entity that could contain any other entity?
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">public</span>
            <span style="color: #0000ff">class</span> SsdsEntity&lt;T&gt; <span style="color: #0000ff">where</span> T: <span style="color: #0000ff">class</span> { <span style="color: #0000ff">string</span> _kind; <span style="color: #0000ff">public</span> SsdsEntity()
{ } [XmlElement(Namespace = <span style="color: #006080">@"http://schemas.microsoft.com/sitka/2008/03/"</span>)] <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> Id
{ get; set; } [XmlIgnore] <span style="color: #0000ff">public</span><span style="color: #0000ff">string</span> Kind
{ get { <span style="color: #0000ff">if</span> (String.IsNullOrEmpty(_kind)) { _kind
= <span style="color: #0000ff">typeof</span>(T).Name; } <span style="color: #0000ff">return</span> _kind;
} set { _kind = <span style="color: #0000ff">value</span>; } } [XmlElement(Namespace
= <span style="color: #006080">@"http://schemas.microsoft.com/sitka/2008/03/"</span>)] <span style="color: #0000ff">public</span><span style="color: #0000ff">int</span> Version
{ get; set; } [XmlIgnore] <span style="color: #0000ff">public</span> T Entity { get;
set; } }</pre>
        </div>
        <p>
In this case, we have simply wrapped the POCO that we care about in a class that knows
about the specifics of the SSDS wire format (or more accurately could serialize down
to the wire format).
</p>
        <p>
This <strong>SsdsEntity&lt;T&gt;</strong> is easy to use and provides access to the
strongly typed object via the Entity property.
</p>
        <p>
          <a href="http://dunnry.com/blog/content/binary/WindowsLiveWriter/SerializationinSSDSRevisited_BEC9/foomembers_2.png">
            <img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="293" alt="foomembers" src="http://dunnry.com/blog/content/binary/WindowsLiveWriter/SerializationinSSDSRevisited_BEC9/foomembers_thumb.png" width="487" border="0" />
          </a>
        </p>
        <p>
Now, we just have to figure out how to serialize the <strong>SsdsEntity&lt;Foo&gt;</strong> object
and we know that the metadata attributes are taken care of and our original POCO object
that we care about is included.  I call it wrapping POCOs in a thin SSDS veneer.
</p>
        <p>
The trick to this is to add a bucket of XElement objects on the <strong>SsdsEntity&lt;T&gt;</strong> class
that will hold our public properties on our class T (i.e. 'Foo' class).  It looks
something like this:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">[XmlAnyElement]
<span style="color: #0000ff">public</span> XElement[]
Attributes { get { <span style="color: #008000">//using XElement is much easier than
XmlElement to build</span><span style="color: #008000">//take all properties on object
instance and build XElement</span> var props = from prop <span style="color: #0000ff">in</span><span style="color: #0000ff">typeof</span>(T).GetProperties()
let val = prop.GetValue(<span style="color: #0000ff">this</span>.Entity, <span style="color: #0000ff">null</span>) <span style="color: #0000ff">where</span> prop.GetSetMethod()
!= <span style="color: #0000ff">null</span> &amp;&amp; allowableTypes.Contains(prop.PropertyType)
&amp;&amp; val != <span style="color: #0000ff">null</span> select <span style="color: #0000ff">new</span> XElement(prop.Name, <span style="color: #0000ff">new</span> XAttribute(Constants.xsi
+ <span style="color: #006080">"type"</span>, XsdTypeResolver.Solve(prop.PropertyType)),
EncodeValue(val) ); <span style="color: #0000ff">return</span> props.ToArray(); }
set { <span style="color: #008000">//wrap the XElement[] with the name of the type</span> var
xml = <span style="color: #0000ff">new</span> XElement(<span style="color: #0000ff">typeof</span>(T).Name, <span style="color: #0000ff">value</span>);
var xs = <span style="color: #0000ff">new</span> XmlSerializer(<span style="color: #0000ff">typeof</span>(T)); <span style="color: #008000">//xml.CreateReader()
cannot be used as it won't support base64 content</span> XmlTextReader reader = <span style="color: #0000ff">new</span> XmlTextReader(
xml.ToString(), XmlNodeType.Document, <span style="color: #0000ff">null</span>); <span style="color: #0000ff">this</span>.Entity
= (T)xs.Deserialize(reader); } }</pre>
        </div>
        <p>
In the getter, we use Reflection and pull back a list of all the public properties
on the T object and build an array of <strong>XElement</strong>.  This is the
same technique I used in my first post on serialization.  The 'allowableTypes'
object is a <strong>HashSet&lt;Type&gt;</strong> that we use to figure out which property
types we can support in the service (DateTime, numeric, string, boolean, and byte[]). 
When this property serializes, the <strong>XElement</strong>s are simply added to
the markup.
</p>
        <p>
The <strong>EncodeValue</strong> method shown is a simple helper method that correctly
encodes string values, boolean, dates, integers, and byte[] values for the attribute. 
Finally, we are using a helper method that returns from a <strong>Dictionary&lt;Type,string&gt;</strong> the
correct xsi type for the required attribute (as determined from the property type).
</p>
        <p>
For deserialization, what happens is that the <strong>[XmlAnyElement]</strong> attribute
causes all unmapped attributes (in this case, all non-system metadata attributes)
to be collected in a collection of <strong>XElement</strong>.  When we deserialize,
if we simply wrap an enclosing element around this <strong>XElement</strong> collection,
it is exactly what we need for deserialization of T.  This is shown in the setter
implementation.
</p>
        <p>
It might look a little complicated, but now simple serialization will just work via
the <strong>XmlSerializer</strong>.  Here is one such implementation:
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">public</span>
            <span style="color: #0000ff">string</span> Serialize(SsdsEntity&lt;T&gt;
entity) { <span style="color: #008000">//add a bunch of namespaces and override the
default ones too</span> XmlSerializerNamespaces namespaces = <span style="color: #0000ff">new</span> XmlSerializerNamespaces();
namespaces.Add(<span style="color: #006080">"s"</span>, Constants.ns.NamespaceName);
namespaces.Add(<span style="color: #006080">"x"</span>, Constants.x.NamespaceName);
namespaces.Add(<span style="color: #006080">"xsi"</span>, Constants.xsi.NamespaceName);
var xs = <span style="color: #0000ff">new</span> XmlSerializer( entity.GetType(), <span style="color: #0000ff">new</span> XmlRootAttribute(<span style="color: #0000ff">typeof</span>(T).Name)
); XmlWriterSettings xws = <span style="color: #0000ff">new</span> XmlWriterSettings();
xws.Indent = <span style="color: #0000ff">true</span>; xws.OmitXmlDeclaration = <span style="color: #0000ff">true</span>; <span style="color: #0000ff">using</span> (var
ms = <span style="color: #0000ff">new</span> MemoryStream()) { <span style="color: #0000ff">using</span> (XmlWriter
writer = XmlWriter.Create(ms, xws)) { xs.Serialize(writer, entity, namespaces); ms.Position
= 0; <span style="color: #008000">//reset to beginning</span><span style="color: #0000ff">using</span> (var
sr = <span style="color: #0000ff">new</span> StreamReader(ms)) { <span style="color: #0000ff">return</span> sr.ReadToEnd();
} } } }</pre>
        </div>
        <p>
Deserialization is even easier since we are starting with the XML representation and
don't have to build a Stream in memory.
</p>
        <div>
          <pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">
            <span style="color: #0000ff">public</span> SsdsEntity&lt;T&gt;
Deserialize(XElement node) { var xs = <span style="color: #0000ff">new</span> XmlSerializer( <span style="color: #0000ff">typeof</span>(SsdsEntity&lt;T&gt;), <span style="color: #0000ff">new</span> XmlRootAttribute(<span style="color: #0000ff">typeof</span>(T).Name)
); <span style="color: #008000">//xml.CreateReader() cannot be used as it won't support
base64 content</span> XmlTextReader reader = <span style="color: #0000ff">new</span> XmlTextReader(
node.ToString(), XmlNodeType.Document, <span style="color: #0000ff">null</span>); <span style="color: #0000ff">return</span> (SsdsEntity&lt;T&gt;)xs.Deserialize(reader);
}</pre>
        </div>
        <p>
If you notice, I am using an <strong>XmlTextReader</strong> to pass to the <strong>XmlSerializer</strong>. 
Unfortunately, the <strong>XmlReader</strong> from XLINQ does not support handling
of base64 content, so this workaround is necessary.
</p>
        <p>
At this point, we have a working serializer/deserializer that can handle arbitrary
POCOs.  There are some limitations of course:
</p>
        <ul>
          <li>
            <font color="#555555">We are limited to the same datatypes that SSDS supports. 
This also means nested objects and arrays are not directly supported.</font>
          </li>
          <li>
            <font color="#555555">We have lost a little of the 'flexible' in the Flexible Entity
(the E in the <a href="http://dunnry.com/blog/EntitiesContainersAndAuthorities.aspx">ACE
model</a>).  We now have a rigid schema defined by SSDS metadata and T public
properties and enforced on our objects.</font>
          </li>
        </ul>
        <p>
In my next post, I will attempt to address some of those limitations and I will introduce
a library that handles most of this for you.
</p>
        <img width="0" height="0" src="http://dunnry.com/blog/aggbug.ashx?id=2021b648-8af2-4702-95f5-c5ec1455c1e1" />
      </body>
      <title>Working with Objects in SSDS Part 1</title>
      <guid isPermaLink="false">http://dunnry.com/blog/PermaLink,guid,2021b648-8af2-4702-95f5-c5ec1455c1e1.aspx</guid>
      <link>http://dunnry.com/blog/WorkingWithObjectsInSSDSPart1.aspx</link>
      <pubDate>Wed, 18 Jun 2008 03:17:10 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://dunnry.com/blog/SerializationInSSDS.aspx"&gt;Last time&lt;/a&gt; we talked
about SQL Server Data Services and serializing objects, we discussed how easy it was
to use the &lt;strong&gt;XmlSerializer&lt;/strong&gt; to deserialize objects using the REST interface.&amp;nbsp;
The problem was that when we serialized objects using the &lt;strong&gt;XmlSerializer&lt;/strong&gt;,
it left out the xsi type declarations that we needed.&amp;nbsp; I gave two possible solutions
to this problem - one that used the &lt;strong&gt;XmlSerializer&lt;/strong&gt; and 'fixed' the
output after the fact, and the other built the XML that we needed using XLINQ and
Reflection.
&lt;/p&gt;
&lt;p&gt;
Today, I am going to talk about a third technique that I have been using lately that
I like better.&amp;nbsp; It uses some of the previous techniques and leverages a few tricks
with &lt;strong&gt;XmlSerializer&lt;/strong&gt; to get what I want.&amp;nbsp; First, let's start with
a POCO (plain ol' C# object) class that we would like to use with SSDS.
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Foo
{ &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Name
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; Size
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; IsPublic
{ get; set; } }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In it's correctly serialized form, it looks like this on the wire:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Foo&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xmlns:s&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="http://schemas.microsoft.com/sitka/2008/03/"&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xmlns:xsi&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="http://www.w3.org/2001/XMLSchema-instance"&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xmlns:x&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="http://www.w3.org/2001/XMLSchema"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;someid&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Id&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;1&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;s:Version&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:string"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;My
Foo&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Name&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Size&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:decimal"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;10&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Size&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;IsPublic&lt;/span&gt; &lt;span style="color: #ff0000"&gt;xsi:type&lt;/span&gt;&lt;span style="color: #0000ff"&gt;="x:boolean"&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;false&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;IsPublic&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Foo&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
You'll notice that we have the additional system metadata attributes "Id" and "Version"
in the markup.&amp;nbsp; We can account for the metadata attributes by doing something
cheesy like deriving from a base class:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;abstract&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Cheese
{ &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Id
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; Version
{ get; set; } }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
However this is very unnatural as our classes would all have to derive from our "Cheese"
abstract base class (ABC).
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Foo
: Cheese { &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Name
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; Size
{ get; set; } &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; IsPublic
{ get; set; } }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Developers familiar with remoting in .NET should be cringing right now as they remember
the hassles associated with deriving from &lt;strong&gt;MarshalByRefObject&lt;/strong&gt;.&amp;nbsp;
In a world without multiple inheritance, this can be painful.&amp;nbsp; I want a model
where I can use arbitrary POCO objects (&lt;a href="http://haacked.com/archive/2008/06/13/ras-syndrome.aspx"&gt;redundant&lt;/a&gt;,
yes I know) and not be forced to derive from anything or do what I would otherwise
term unnatural acts.
&lt;/p&gt;
&lt;p&gt;
What if instead, we derived a generic entity that could contain any other entity?
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; SsdsEntity&amp;lt;T&amp;gt; &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; T: &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; _kind; &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; SsdsEntity()
{ } [XmlElement(Namespace = &lt;span style="color: #006080"&gt;@"http://schemas.microsoft.com/sitka/2008/03/"&lt;/span&gt;)] &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Id
{ get; set; } [XmlIgnore] &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Kind
{ get { &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (String.IsNullOrEmpty(_kind)) { _kind
= &lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T).Name; } &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; _kind;
} set { _kind = &lt;span style="color: #0000ff"&gt;value&lt;/span&gt;; } } [XmlElement(Namespace
= &lt;span style="color: #006080"&gt;@"http://schemas.microsoft.com/sitka/2008/03/"&lt;/span&gt;)] &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; Version
{ get; set; } [XmlIgnore] &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; T Entity { get;
set; } }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this case, we have simply wrapped the POCO that we care about in a class that knows
about the specifics of the SSDS wire format (or more accurately could serialize down
to the wire format).
&lt;/p&gt;
&lt;p&gt;
This &lt;strong&gt;SsdsEntity&amp;lt;T&amp;gt;&lt;/strong&gt; is easy to use and provides access to the
strongly typed object via the Entity property.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://dunnry.com/blog/content/binary/WindowsLiveWriter/SerializationinSSDSRevisited_BEC9/foomembers_2.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="293" alt="foomembers" src="http://dunnry.com/blog/content/binary/WindowsLiveWriter/SerializationinSSDSRevisited_BEC9/foomembers_thumb.png" width="487" border="0"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Now, we just have to figure out how to serialize the &lt;strong&gt;SsdsEntity&amp;lt;Foo&amp;gt;&lt;/strong&gt; object
and we know that the metadata attributes are taken care of and our original POCO object
that we care about is included.&amp;nbsp; I call it wrapping POCOs in a thin SSDS veneer.
&lt;/p&gt;
&lt;p&gt;
The trick to this is to add a bucket of XElement objects on the &lt;strong&gt;SsdsEntity&amp;lt;T&amp;gt;&lt;/strong&gt; class
that will hold our public properties on our class T (i.e. 'Foo' class).&amp;nbsp; It looks
something like this:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;[XmlAnyElement]
&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; XElement[]
Attributes { get { &lt;span style="color: #008000"&gt;//using XElement is much easier than
XmlElement to build&lt;/span&gt; &lt;span style="color: #008000"&gt;//take all properties on object
instance and build XElement&lt;/span&gt; var props = from prop &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; &lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T).GetProperties()
let val = prop.GetValue(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt;.Entity, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;) &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; prop.GetSetMethod()
!= &lt;span style="color: #0000ff"&gt;null&lt;/span&gt; &amp;amp;&amp;amp; allowableTypes.Contains(prop.PropertyType)
&amp;amp;&amp;amp; val != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt; select &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XElement(prop.Name, &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XAttribute(Constants.xsi
+ &lt;span style="color: #006080"&gt;"type"&lt;/span&gt;, XsdTypeResolver.Solve(prop.PropertyType)),
EncodeValue(val) ); &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; props.ToArray(); }
set { &lt;span style="color: #008000"&gt;//wrap the XElement[] with the name of the type&lt;/span&gt; var
xml = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XElement(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T).Name, &lt;span style="color: #0000ff"&gt;value&lt;/span&gt;);
var xs = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlSerializer(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T)); &lt;span style="color: #008000"&gt;//xml.CreateReader()
cannot be used as it won't support base64 content&lt;/span&gt; XmlTextReader reader = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlTextReader(
xml.ToString(), XmlNodeType.Document, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;); &lt;span style="color: #0000ff"&gt;this&lt;/span&gt;.Entity
= (T)xs.Deserialize(reader); } }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In the getter, we use Reflection and pull back a list of all the public properties
on the T object and build an array of &lt;strong&gt;XElement&lt;/strong&gt;.&amp;nbsp; This is the
same technique I used in my first post on serialization.&amp;nbsp; The 'allowableTypes'
object is a &lt;strong&gt;HashSet&amp;lt;Type&amp;gt;&lt;/strong&gt; that we use to figure out which property
types we can support in the service (DateTime, numeric, string, boolean, and byte[]).&amp;nbsp;
When this property serializes, the &lt;strong&gt;XElement&lt;/strong&gt;s are simply added to
the markup.
&lt;/p&gt;
&lt;p&gt;
The &lt;strong&gt;EncodeValue&lt;/strong&gt; method shown is a simple helper method that correctly
encodes string values, boolean, dates, integers, and byte[] values for the attribute.&amp;nbsp;
Finally, we are using a helper method that returns from a &lt;strong&gt;Dictionary&amp;lt;Type,string&amp;gt;&lt;/strong&gt; the
correct xsi type for the required attribute (as determined from the property type).
&lt;/p&gt;
&lt;p&gt;
For deserialization, what happens is that the &lt;strong&gt;[XmlAnyElement]&lt;/strong&gt; attribute
causes all unmapped attributes (in this case, all non-system metadata attributes)
to be collected in a collection of &lt;strong&gt;XElement&lt;/strong&gt;.&amp;nbsp; When we deserialize,
if we simply wrap an enclosing element around this &lt;strong&gt;XElement&lt;/strong&gt; collection,
it is exactly what we need for deserialization of T.&amp;nbsp; This is shown in the setter
implementation.
&lt;/p&gt;
&lt;p&gt;
It might look a little complicated, but now simple serialization will just work via
the &lt;strong&gt;XmlSerializer&lt;/strong&gt;.&amp;nbsp; Here is one such implementation:
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Serialize(SsdsEntity&amp;lt;T&amp;gt;
entity) { &lt;span style="color: #008000"&gt;//add a bunch of namespaces and override the
default ones too&lt;/span&gt; XmlSerializerNamespaces namespaces = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlSerializerNamespaces();
namespaces.Add(&lt;span style="color: #006080"&gt;"s"&lt;/span&gt;, Constants.ns.NamespaceName);
namespaces.Add(&lt;span style="color: #006080"&gt;"x"&lt;/span&gt;, Constants.x.NamespaceName);
namespaces.Add(&lt;span style="color: #006080"&gt;"xsi"&lt;/span&gt;, Constants.xsi.NamespaceName);
var xs = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlSerializer( entity.GetType(), &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlRootAttribute(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T).Name)
); XmlWriterSettings xws = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlWriterSettings();
xws.Indent = &lt;span style="color: #0000ff"&gt;true&lt;/span&gt;; xws.OmitXmlDeclaration = &lt;span style="color: #0000ff"&gt;true&lt;/span&gt;; &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (var
ms = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; MemoryStream()) { &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (XmlWriter
writer = XmlWriter.Create(ms, xws)) { xs.Serialize(writer, entity, namespaces); ms.Position
= 0; &lt;span style="color: #008000"&gt;//reset to beginning&lt;/span&gt; &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (var
sr = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; StreamReader(ms)) { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; sr.ReadToEnd();
} } } }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Deserialization is even easier since we are starting with the XML representation and
don't have to build a Stream in memory.
&lt;/p&gt;
&lt;div&gt;&lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; SsdsEntity&amp;lt;T&amp;gt;
Deserialize(XElement node) { var xs = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlSerializer( &lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(SsdsEntity&amp;lt;T&amp;gt;), &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlRootAttribute(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(T).Name)
); &lt;span style="color: #008000"&gt;//xml.CreateReader() cannot be used as it won't support
base64 content&lt;/span&gt; XmlTextReader reader = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; XmlTextReader(
node.ToString(), XmlNodeType.Document, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;); &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; (SsdsEntity&amp;lt;T&amp;gt;)xs.Deserialize(reader);
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
If you notice, I am using an &lt;strong&gt;XmlTextReader&lt;/strong&gt; to pass to the &lt;strong&gt;XmlSerializer&lt;/strong&gt;.&amp;nbsp;
Unfortunately, the &lt;strong&gt;XmlReader&lt;/strong&gt; from XLINQ does not support handling
of base64 content, so this workaround is necessary.
&lt;/p&gt;
&lt;p&gt;
At this point, we have a working serializer/deserializer that can handle arbitrary
POCOs.&amp;nbsp; There are some limitations of course:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;font color="#555555"&gt;We are limited to the same datatypes that SSDS supports.&amp;nbsp;
This also means nested objects and arrays are not directly supported.&lt;/font&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;font color="#555555"&gt;We have lost a little of the 'flexible' in the Flexible Entity
(the E in the &lt;a href="http://dunnry.com/blog/EntitiesContainersAndAuthorities.aspx"&gt;ACE
model&lt;/a&gt;).&amp;nbsp; We now have a rigid schema defined by SSDS metadata and T public
properties and enforced on our objects.&lt;/font&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
In my next post, I will attempt to address some of those limitations and I will introduce
a library that handles most of this for you.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dunnry.com/blog/aggbug.ashx?id=2021b648-8af2-4702-95f5-c5ec1455c1e1" /&gt;</description>
      <comments>http://dunnry.com/blog/CommentView,guid,2021b648-8af2-4702-95f5-c5ec1455c1e1.aspx</comments>
      <category>.NET</category>
      <category>Cloud Services</category>
      <category>Design</category>
      <category>SSDS</category>
    </item>
    <item>
      <trackback:ping>http://dunnry.com/blog/Trackback.aspx?guid=ada84666-9fb7-4142-8764-adff11fd8552</trackback:ping>
      <pingback:server>http://dunnry.com/blog/pingback.aspx</pingback:server>
      <pingback:target>http://dunnry.com/blog/PermaLink,guid,ada84666-9fb7-4142-8764-adff11fd8552.aspx</pingback:target>
      <dc:creator>Ryan Dunn</dc:creator>
      <wfw:comment>http://dunnry.com/blog/CommentView,guid,ada84666-9fb7-4142-8764-adff11fd8552.aspx</wfw:comment>
      <wfw:commentRss>http://dunnry.com/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=ada84666-9fb7-4142-8764-adff11fd8552</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I officially love <a href="http://www.linqpad.net/">LINQPad</a>.  Joe Albahari
has done a great job of introducing a light weight tool that is great for learning
and prototyping LINQ queries.  From what I gather, Joe and Ben Albahari built
this tool as part of <a href="http://www.amazon.com/exec/obidos/ASIN/0596527578/extemporaneou-20-20">their
book</a> offering.  It was so useful, it has taken on a life of its own.
</p>
        <p>
It may not be entirely obvious, but it turns out don't have to use LINQPad solely
for LINQ queries.  You can actually prototype any type of snippet of code. 
I have been using it now instead of <a href="http://www.sliver.com/dotnet/SnippetCompiler/">SnippetCompiler</a> (another
great quick snippet tool).
</p>
        <p>
As an example, here is how to use System.DirectoryServices snippets inside of LINQPad:
</p>
        <p>
Hit F4 to bring up the Advanced Query Properties Window
</p>
        <p>
          <a href="http://dunnry.com/blog/content/binary/WindowsLiveWriter/LINQPadnotjustforLINQ_9627/image_2.png">
            <img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="364" alt="image" src="http://dunnry.com/blog/content/binary/WindowsLiveWriter/LINQPadnotjustforLINQ_9627/image_thumb.png" width="461" border="0" />
          </a>
        </p>
        <p>
Add the System.DirectoryServices.dll reference in the Additional References window,
and then add "System.DirectoryServices" in the Additional Namespace Imports window.
</p>
        <p>
Now, just type your code normally and hit F5 when you are done:
</p>
        <p>
          <a href="http://dunnry.com/blog/content/binary/WindowsLiveWriter/LINQPadnotjustforLINQ_9627/image_6.png">
            <img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="352" alt="image" src="http://dunnry.com/blog/content/binary/WindowsLiveWriter/LINQPadnotjustforLINQ_9627/image_thumb_2.png" width="457" border="0" />
          </a> 
</p>
        <p>
This is a great little tool to have as you can query databases, build LINQ expressions,
and visually inspect the results that come back pretty easily.  Now, as you can
see you can also execute arbitrary code snippets as well.  Highly recommended.
</p>
        <img width="0" height="0" src="http://dunnry.com/blog/aggbug.ashx?id=ada84666-9fb7-4142-8764-adff11fd8552" />
      </body>
      <title>LINQPad - not just for LINQ</title>
      <guid isPermaLink="false">http://dunnry.com/blog/PermaLink,guid,ada84666-9fb7-4142-8764-adff11fd8552.aspx</guid>
      <link>http://dunnry.com/blog/LINQPadNotJustForLINQ.aspx</link>
      <pubDate>Wed, 11 Jun 2008 17:47:50 GMT</pubDate>
      <description>&lt;p&gt;
I officially love &lt;a href="http://www.linqpad.net/"&gt;LINQPad&lt;/a&gt;.&amp;nbsp; Joe Albahari
has done a great job of introducing a light weight tool that is great for learning
and prototyping LINQ queries.&amp;nbsp; From what I gather, Joe and Ben Albahari built
this tool as part of &lt;a href="http://www.amazon.com/exec/obidos/ASIN/0596527578/extemporaneou-20-20"&gt;their
book&lt;/a&gt; offering.&amp;nbsp; It was so useful, it has taken on a life of its own.
&lt;/p&gt;
&lt;p&gt;
It may not be entirely obvious, but it turns out don't have to use LINQPad solely
for LINQ queries.&a