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

<channel>
	<title>Bizcoder</title>
	<atom:link href="http://www.bizcoder.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bizcoder.com</link>
	<description>Developing business applications for small businesses</description>
	<lastBuildDate>Sat, 28 Aug 2010 10:44:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Agent Fielding is on a mission</title>
		<link>http://www.bizcoder.com/index.php/2010/08/28/agent-fielding-is-on-a-mission/</link>
		<comments>http://www.bizcoder.com/index.php/2010/08/28/agent-fielding-is-on-a-mission/#comments</comments>
		<pubDate>Sat, 28 Aug 2010 10:34:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/08/28/agent-fielding-is-on-a-mission/</guid>
		<description><![CDATA[This is a continuation of a series on a Rest Agent library I am building for accessing REST apis.&#160; The first post is here and and the second is here. So far the only significant operation that we enabled our RestAgent to perform is NavigateTo().&#160; However, for a RestAgent on a mission, going places is [...]]]></description>
			<content:encoded><![CDATA[<p>This is a continuation of a series on a Rest Agent library I am building for accessing REST apis.&#160; The first post is <a href="http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/">here</a> and and the second is <a href="http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/">here</a>. </p>
<p>So far the only significant operation that we enabled our RestAgent to perform is NavigateTo().&#160; However, for a RestAgent on a mission, going places is only half the story, the other major purpose of the agent is to gather content.</p>
<p>I was planning to show some real examples of missions using Stack Overflow’s API, but I ended up spending so much time explaining why it currently would not work, that my points were lost.&#160; So forgive me as I continue with a somewhat more hypothetical example.&#160; We are going to use an instance of our RestAgent to do a mashup of Twitter users and Stackoverflow users.</p>
<div>
<pre class="csharpcode">var agentFielding = <span class="kwrd">new</span> RestAgent(<span class="kwrd">new</span> HttpClient()); 

agentFielding.RegisterMediaType(“application/twitterdoc+xml”,
                                    <span class="kwrd">new</span> TwitterMediaHandler());
agentFielding.RegisterMediaType(“application/stackoverflowdoc+xml”,
                                    <span class="kwrd">new</span> StackOverflowMediaHandler());</pre>
</div>
<p>In the following code, Agent Fielding retrieves my Twitter followers and attempts to find matching accounts on Stack Overflow.&#160; In order to interpret the representations that will be retrieved from these two sites, we are going to pretend that these sites actually return non-generic media types and we register handlers for these media types that will transform the wire representation into strong types.</p>
<p>The first step is to navigate Twitter and retrieve the user profiles of my followers:</p>
<div>
<pre class="csharpcode">agentFielding.NavigateTo(<span class="kwrd">new</span> Uri(“http:<span class="rem">//api.twitter.com/”));</span>
var userSearch = agentFielding.CurrentLinks(“UserSearch”);
userSearch.SetParameter(&quot;darrel_miller”);
agentFielding.NavigateTo(userSearch);

var followersLink = agentFielding.CurrentLinks[“Followers”);
agentFielding.NavigateTo(followersLink);

var twitterUserProfiles = <span class="kwrd">new</span> List&lt;TwitterUserProfile&gt;();
var followerLinks = agentFielding.GetCurrentLinks(l=&gt; l.Relation.Name == ”Follower”];
<span class="kwrd">foreach</span>(Link followerLink <span class="kwrd">in</span> followerLinks) {

  var twitterProfile = agentFielding.GetContent(followerLink).ReadAsTwitterUserProfile();
  twitterUserProfiles.Add(twitterProfile);

}</pre>
</div>
<p>Now we have a list of TwitterUserProfile objects from which we can retrieve the name and search on Stack Overflow.</p>
<div>
<pre class="csharpcode">agentFielding.NavigateTo(<span class="kwrd">new</span> Uri(“http:<span class="rem">//api.stackoverflow.com/1.0/”));</span> 

agentFielding.NavigateTo(agent.CurrentLinks[“Users”]);
var searchLink = agent.CurrentLinks[“Search”];
var foundProfiles = <span class="kwrd">new</span> List&lt;StackOverflowUserProfile&gt;();
<span class="kwrd">foreach</span>(var profile <span class="kwrd">in</span> twitterUserProfiles) {   searchLink.SetParameter(profile.UserName);
  agentFielding.NavigateTo(searchLink); 

  var matchingUserLinks = agentFielding.GetCurrentLinks(l=&gt; l.Relation.Name == ”User”])
  <span class="kwrd">foreach</span>(Link userLink <span class="kwrd">in</span> matchingUserLinks) {
       var content = agentFielding.GetContent(userLink);
       foundProfiles.Add(content.ReadAsStackOverflowUserProfile();
  }
}</pre>
</div>
<p>Don’t get too hung up on the precise details of the above, there is a bit of smoke and mirrors going on.&#160; I’m really just trying to convey the concept that the same agent class can be used to navigate multiple different services.&#160; This brings the concept of the uniform interface a little further into the client code.&#160; </p>
<p>My hope is that in the future that REST api producers will supply media type handlers for their custom media types and we can use a standardized agent like interface for navigating any REST api.&#160; There will be no need the API producers to create complete client side facades.</p>
<p>There is still plenty of coupling in the above example, when it comes to handling specific representations and knowing about the existence of specific links, there is plenty of service specific code.&#160; This is especially true of these type of scripted or (machine to machine) interactions.&#160; Machines are really dumb, so they need to understand a lot of specifics of the services that they are interacting with.&#160; In the next article I’m going to start digging into how you can use an agent to react to a human driven application, and that will&#160; further reduce the coupling.&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/08/28/agent-fielding-is-on-a-mission/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rest Agent uses hypermedia</title>
		<link>http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/</link>
		<comments>http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 11:46:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/</guid>
		<description><![CDATA[As I alluded to in my first post, REST clients really should be driven by hypermedia.&#160; So how can our RestAgent class access this hypermedia and its links.&#160; Ideally, given a single root URI, I would like to be able to do: var agent = new RestAgent(new HttpClient()); agent.NavigateTo(new Uri(“http://api.stackoverflow.com/”)); var questionsLink = agent.CurrentLinks[“Questions”] agent.NavigateTo(questionsLink); [...]]]></description>
			<content:encoded><![CDATA[<p>As I alluded to in <a href="http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/">my first post</a>, REST clients really should be driven by hypermedia.&#160; So how can our RestAgent class access this hypermedia and its links.&#160; Ideally, given a single root URI, I would like to be able to do:</p>
<div>
<pre class="csharpcode">var agent = <span class="kwrd">new</span> RestAgent(<span class="kwrd">new</span> HttpClient());
agent.NavigateTo(<span class="kwrd">new</span> Uri(“http:<span class="rem">//api.stackoverflow.com/”)); </span>
var questionsLink = agent.CurrentLinks[“Questions”]
agent.NavigateTo(questionsLink);
var questions = agent.CurrentContent.ReadAsJson(); </pre>
</div>
<p>Before I talk about the magic that is going on under the covers here, let me take a little jab at my friend StackOverflow.&#160; The above code would not work, because when the team created the api, they chose not to put a root representation on the API. Making the request to the root of the api actually redirects to an html page with API documentation.&#160; I’ve tried scraping the urls out of that document, but it is proving to be painful.</p>
<h3>The Link Class</h3>
<p>The CurrentLinks property makes a dictionary of links available based on the links contained in the current content and potentially links that were included in the header.&#160; You will notice that the second call to NavigateTo passes a “Link”, not a URL.&#160; So what’s the difference?&#160; Here is a basic implementation of the Link class:</p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Link {

  <span class="kwrd">public</span> <span class="kwrd">string</span> Name{ get; set;}
  <span class="kwrd">public</span> LinkRelation Relation{ get; set;}
  <span class="kwrd">public</span> Uri Url { get; set;}
  <span class="kwrd">public</span> HttpMethod Method { get; set;}
  <span class="kwrd">public</span> HttpContent Content {get; set;}

  <span class="kwrd">public</span> Dictionary&lt;Parameter&gt; QueryParameters {get; set;}
  <span class="kwrd">public</span> Dictionary&lt;Parameter&gt; PathParameters {get; set;}

}</pre>
</div>
<p>The Link class holds plenty of additional information that is needed to allow the NavigateTo method to transfer to a new state.&#160; The Link objects are created from information contained in retrieved hypermedia content.&#160; If the HttpMethod is a PUT or a POST then the Content property can be used to hold the entity that will be sent to the origin server.&#160; </p>
<p>The LinkRelation property is critical concept.&#160; The Link Relation is one of the two points of coupling between the client and the server.&#160; The other being the media-type.&#160; From an architectural point of view the Link Relation describes the relationship between two resources.&#160; For example, if you have a representation A that contains a link to resource B with the relation “edit”, this can be interpreted as B allows you to “edit” A.&#160; IANA keeps a registry of well known link relations here <a href="http://www.iana.org/assignments/link-relations/link-relations.txt">http://www.iana.org/assignments/link-relations/link-relations.txt</a>.&#160; The WHATWG group are also maintaining a list here <a href="http://wiki.whatwg.org/wiki/RelExtensions">http://wiki.whatwg.org/wiki/RelExtensions</a>.</p>
<p>From an implementation perspective, the Link Relation can be used to tell the client mechanical information about how to perform the HTTP request.&#160; For example, what HTTP method to use, what content needs to be posted back to the server, if any. It also can be used to tell the client what query string parameters are valid.&#160; Arguably you can introduce any kind of arbitrary significance to a link relation as long as you are prepared to put up with the client/server coupling.</p>
<p>I have been experimenting with implementing LinkRelation as an actual class instead of just an identifer.&#160; Many different link relations have similar sets of behaviour and by creating a base class with some standard attributes it is possible to represent specific link relations as derived classes and still have plenty of generic mechanisms that process links without scattering the code base with fragile switch statements.&#160; Hopefully as we go into more detail I will show some examples that take advantage of this LinkRelation base class.</p>
<p>So far I have only used very simple URI templates and so my needs have been satisfied with just a collection of query parameter values and path parameter values.&#160; The current draft of the URI template specification introduces many more variants that I could be supported by the Link class.</p>
<p>The Name property is the black sheep of the Link class.&#160; I’m not convinced that we really need this property.&#160; However, I include it to support the scenario where there are multiple links within a hypermedia document that has the same LinkRelation.&#160; How a client is supposed to differentiate between those different links without introducing out of band coupling is not always clear to me.&#160; If the current representation is to be rendered to the user as a set of links then the user should be capable of deciding which they wish to follow.&#160; However, in a scripted (ie. machine 2 machine) scenario, it becomes highly suspect if the script starts referring to link names.&#160; Depending on how precise the media type, is, the link names could be pre-specified in the media-type.&#160; Or code-download could be used to activate links with particular names.&#160; The final solution that I have seen is to drop the name property completely and use very specific link relation values.&#160; I’m not a big fan of this approach because I think it leads to the same explosion problems as using extremely specific media-types.&#160; Highly specific media-types and link relations destroy the possibility of serendipitous reuse.</p>
<h3>Hypermedia Content</h3>
<p>So now, you have an idea of how I handle links, let’s look at how those links get created in the first place.&#160; As I mentioned before, the CurrentLinks dictionary is populated from the CurrentContent.&#160; The question of course is how can the generic RestAgent know how to pull links out of content that could be any media type.&#160; The solution is a plug in model that allows handlers to be registered in a media type handler registry.&#160; </p>
<p>Behind the scenes I use MEF to load up the media type handlers, but I stuck an interface in front, mainly because I’m not very experienced with MEF and I wasn’t exactly sure how to setup unit tests using MEF.&#160; With the interface I can easily create a fake registry.</p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IHandlerRegistry {
        IMediaTypeHandler GetHandler(ContentType contentType);
    }</pre>
</div>
<p>Media type handlers I will cover in more detail at a later date.&#160; All we care about for this series of articles, is that they can be used to do two things:&#160; 1) they can convert the stream of bytes coming from the http response into a class that implements IHypermediaContent and 2) they can create and run a controller with RunController(HttpResponseMessage response) method that will “do” whatever that media type is supposed to do.&#160; I realize that sounds very vague, but vague is good when we don’t want to introduce coupling <img src='http://www.bizcoder.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IMediaTypeHandler {
    IHypermediaContent GetContent(HttpContent content);
    IMediaTypeController RunController(HttpResponseMessage message);
}</pre>
</div>
<p>For this article I’m going to ignore RunController and we will get to human driven clients in an upcoming article.&#160; That leaves us with GetContent that returns an IHypermediaContent interface.&#160; That interface looks like this: </p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IHypermediaContent {
       IDictionary&lt;<span class="kwrd">string</span>, Link&gt; Links { get; }
   } </pre>
</div>
<p>Not exactly complex to implement!&#160; Consider what it would take to write a handler that processes, HTML, XHTML, Atom Feeds, <a href="http://restafari.blogspot.com/2010/06/please-accept-applicationhalxml.html">HAL</a>, or even one that attempts to scrape links out of Json or generic XML based on some link convention.&#160; </p>
<h3>Magical Links</h3>
<p>Pulling this all back together, when you navigate the agent to a particular location on the web, the agent will identify the media type of the returned response, determine a handler for that media type, allow the handler to process the bytes and extra the links and store them in a dictionary available via the CurrentLinks property of the agent. </p>
<p>Here is a completely hypothetical use of the RestAgent to crawl safe links on a site: </p>
<div>
<pre class="csharpcode">var agent = <span class="kwrd">new</span> RestAgent(<span class="kwrd">new</span> HttpClient(), <span class="kwrd">new</span> Uri(“http:<span class="rem">//mythical.com/hypermediaService”));</span>
ExploreLinks(agent);

<span class="kwrd">public</span> <span class="kwrd">void</span> ExploreLinks(RestAgent agent) {
var links = CopyLinks(agent.CurrentLinks);
<span class="kwrd">foreach</span>(Link link <span class="kwrd">in</span> links) {
    <span class="kwrd">if</span> (Link.Method == HttpMethod.GET &amp;&amp; Link.LinkRelation.RequiresParameters == <span class="kwrd">false</span>) {
        agent.NavigateTo(link);
        Explore(agent);
    }
}
}</pre>
</div>
<p>To keep things simple, I only traverse links whose LinkRelation specifies a GET is the appropriate verb and only links that do not require parameters.&#160; </p>
<p>I realize that this is still not a very useful example, but enough of the pieces are in place so that in the next article I will talk more about how to get the agent to actually do something useful. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rest Agent &#8211; An introduction</title>
		<link>http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/</link>
		<comments>http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 11:14:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/</guid>
		<description><![CDATA[You might say I’m a bit of a fan of the REST architectural style. Let me provide a little background to clarify why REST is important to me, so you can better understand my underlying objectives.&#160; If we have similar objective then maybe this series of posts will be of interest to you. I write [...]]]></description>
			<content:encoded><![CDATA[<p>You might say I’m a bit of a fan of the REST architectural style. Let me provide a little background to clarify why REST is important to me, so you can better understand my underlying objectives.&#160; If we have similar objective then maybe this series of posts will be of interest to you.</p>
<p>I write distributed business applications for a living and to date, it appears that I end up supporting the code I write for at least 10 to 15 years.&#160; When ever you deploy and update distributed systems there is a nasty side effect of having different components to update and trying to deploy them simultaneously is rife with pitfalls.&#160; Deploying an update to a server compared with updating software on 50 client machines is just a completely different set of problems and keeping them synchronized can be challenging.&#160; </p>
<p>I realize that many people would argue that using a web browser as a client platform would solve my distribution problems.&#160; It would solve the distribution problem, but it would also introduce a whole host of other problems for the types of applications I write.&#160; Browser based apps are awesome for many things, some things they are not so awesome for.</p>
<p>The REST constraints allow you to manage the coupling between the distributed components and allow them to evolve more independently. This allows the system as a whole to evolve incrementally over long periods of time.&#160; I need this kind of robustness in my line of work. </p>
<p>In the three years that I have been building RESTful systems I have seen lots written about how to design and implement RESTful APIs but very little has been written about how REST client applications need to be written.&#160; The few people I have seen talk about it are <a href="http://www.stucharlton.com/blog/archives/2010/03/building-a-restful-hypermedia.html">Stu Charlton</a> and <a href="http://restfulie.caelumobjects.com/">Guilherme Silveira</a>.</p>
<p>This is hopefully the first in a series of blog posts where I cover what I am learning about writing client applications that are part of a RESTful distributed system.</p>
<h4>REST clients are a different breed</h4>
<p>One of the core concepts when designing a REST client is the notion of Hypermedia as the Engine of Application State.&#160; I’m not going to try and explain what I think it means, as many people far more eloquent than I, have tried and yet its meaning is still much debated.&#160; Instead, I would prefer to show some code that I believe embodies the concept.</p>
<p>My REST client applications are built around a class called RestAgent.&#160; I like to imagine my instance of the RestAgent class as little guy travelling across the web making requests and fetching data on my behalf [1].&#160; This agent is responsible for holding all of my application state and for transferring state to and from origin servers. </p>
<p>In its most simple incarnation the class looks something like:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> RestAgent(HttpClient client) {

<span class="kwrd">  private</span> Uri _CurrentLocation;
<span class="kwrd">  private</span> HttpContent_CurrentContent;

<span class="kwrd">  public</span> <span class="kwrd">void</span> NavigateTo(Uri url) {

    _CurrentContent = client.Get(url).Content;
    _CurrentLocation = url;
  }

}</pre>
<p>The RestAgent itself does not know any of the nitty gritty details of how to do HTTP interactions, so I need to provide it with some kind of Http client library.&#160; Obviously, I’ve chosen to use the Microsoft Http client, but in theory any library could work.&#160; </p>
<p>At this point the only thing that the RestAgent is really capable of doing is navigating to the provided url and retreiving the returned content.&#160; The important concept here is that at any one point in time, the RESTAgent can only be in one place.&#160; As we expand on the capabilities of the agent we will allow it to accumulate content during its travels and the aggregate of all of that content will be the “application state”, but if our client application really needs to be in multiple places at once, then we will create multiple agent instances.</p>
<p>For just a small taste of how you might use this RestAgent, </p>
<p>&#160;</p>
<div>
<pre class="csharpcode">var agent = <span class="kwrd">new</span> RestAgent(<span class="kwrd">new</span> HttpClient());

agent.NavigateTo(<span class="kwrd">new</span> Uri(“http:<span class="rem">//api.stackoverflow.com/1.0/questions”)); </span>
var questions = agent.CurrentContent.ReadAsJson();

agent.NavigateTo(“http:<span class="rem">//search.twitter.com/search.atom?q=@darrel_miller”) </span>
var mentions = agent.CurrentContent.ReadAsSyndicationFeed();</pre>
</div>
<p>&#160;</p>
<p>In the next post, I’ll talk more about hypermedia and how the agent can use links from hypermedia content to travel further and gather more content.</p>
<p>&#160;</p>
<p>&#160;</p>
<p>[1]&#160; I originally wanted to call this class AgentFielding to anthropomorphize the class even more, but it seemed a touch presumptuous <img src='http://www.bizcoder.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The StackOverflow question that couldn’t stay open</title>
		<link>http://www.bizcoder.com/index.php/2010/07/21/the-stackoverflow-question-that-couldnt-stay-open/</link>
		<comments>http://www.bizcoder.com/index.php/2010/07/21/the-stackoverflow-question-that-couldnt-stay-open/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 16:08:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/07/21/the-stackoverflow-question-that-couldnt-stay-open/</guid>
		<description><![CDATA[This http://stackoverflow.com/questions/3285704/why-does-rest-exist is the question that I want to give an answer to.&#160; I am answering here because people keep closing it.&#160; Sorry, the post refers directly to issues raised in the question and so won’t make much sense without reading the question first.&#160; I would even recommend reading version of the question prior to [...]]]></description>
			<content:encoded><![CDATA[<p>This <a href="http://stackoverflow.com/questions/3285704/why-does-rest-exist">http://stackoverflow.com/questions/3285704/why-does-rest-exist</a> is the question that I want to give an answer to.&#160; I am answering here because people keep closing it.&#160; Sorry, the post refers directly to issues raised in the question and so won’t make much sense without reading the question first.&#160; I would even recommend reading version of the question prior to editing as it shows more clearly the frustration of the poster.</p>
<h3>A canary in a coal mine.</h3>
<p> I have been waiting for a question like this for close to a year now. It was inevitable that this day would come and I am sure we are going to see many more questions like this in the coming months.<br />
<h3>The warning signs</h3>
<p>You are absolutely correct, it does take longer to build RESTful clients than SOAP clients. The SOAP toolkits take away lots of boilerplate code and make client proxy objects available with almost no effort. With a tool like Visual Studio and a server URL I can be accessing remote objects of arbitrary complexity, locally in under five minutes. </p>
<p>Services that return application/xml and application/json are so annoying for client developers. What are we supposed to do with that blob of data? </p>
<p>Fortunately, lots of sites that provide REST services also provide a bunch of client libraries so that we can use those libraries to get access to a bunch of strongly typed objects. Seems kind of dumb though. If they had used SOAP we could have code-gen&#8217;d those proxy classes ourselves. </p>
<p>SOAP overhead, ha. It&#8217;s latency that kills. If people are really concerned about the number of excess bytes going across the wire then maybe HTTP is not the right choice. Have you seen how many bytes are used by the user-agent header?</p>
<p>Yeah, have you ever tried using a web browser as debugging tool for anything other than HTML and javascript. Trust me it sucks. You can only use two of the verbs, the caching is constantly getting in the way, the error handling swallows so much information, it&#8217;s constantly looking for a goddamn favicon.ico. Just shoot me. </p>
<p>Readable URL. Only nouns, no verbs. Yeah, that&#8217;s easy as long as we are only doing CRUD operations and we only need to access a hierarchy of objects in one way. Unfortunately most applications need a wee bit more functionality than that. </p>
<h3>The impending disaster</h3>
<p>There are a metric boatload of developers currently developing applications that integrate with REST services who are in the process of coming to the same set of conclusions that you have. They were promised simplicity, flexibility, scalability, evolvabilty and the holy grail of serendipitous reuse. The characteristics of the web itself, how can things go wrong.</p>
<p>However, they are finding that versioning is just as much of a problem, but the compiler doesn&#8217;t help detect issues. The hand written client code is a pain to maintain as the data structures evolve and URLs get refactored. Designing APIs around just nouns and four verbs can be really hard, especially with RESTful Url zealots telling you when you can and cannot use query strings. </p>
<p>Developers are going to start asking why are we wasting our effort on support both Json formats and Xml formats, why not just focus our efforts on one and do it well? </p>
<h3>How did things go so wrong</h3>
<p>I&#8217;ll tell you what went wrong. We as developers let the marketing departments take advantage of our primary weakness. Our eternal search for the silver bullet blinded us to the reality of what REST really is. On the surface REST seems so easy and simple. Name your resources with Urls and use GET, PUT, POST and DELETE. Hell, us devs already know how to do that, we have been dealing with databases for years that have tables and columns and SQL statements that have SELECT, INSERT, UPDATE and DELETE. It should have been a piece of cake. </p>
<p>There are other parts of REST that some people discuss, such as self-descriptiveness, and the hypermedia constraint, but these constraints are not so simple as resource identification and the uniform interface. The seem to add complexity where the desired goal is simplicity. </p>
<p>This watered down version of REST became validated in developer culture in many ways. Server frameworks were created that encouraged Resource Identification and the uniform interface, but did nothing to support the other constraints. Terms started to float around differentiating the approaches, (HI-REST vs LO-REST, Corporate REST vs Academic REST, REST vs RESTful). </p>
<p>A few people scream out that if you don&#8217;t apply all of the constraints it&#8217;s not REST. You will not get the benefits. There is no half REST. But those voices were labelled as religious zealots who were upset that their precious term had been stolen from obscurity and made mainstream. Jealous people who try to make REST sound more difficult than it is. </p>
<p>REST, the term, has definitely become mainstream. Almost every major web property that has an API supports &quot;REST&quot;. Twitter and Netflix are two very high profile ones. The scary thing is that I can only think of one public API that is self-descriptive and there are a handful that truly implement the hypermedia constraint. Sure some sites like StackOverflow and Gowalla support links in their responses, but there are huge gaping holes in their links. The StackOverflow API has no root page. Imagine how successful the web site would have been if there was no home page for the web site! </p>
<h3>You were misled I&#8217;m afraid</h3>
<p>If you have made it this far, the short answer to your question is those APIs (Netflix and Twitter) do not conform to all of the constraints and therefore you will not get the benefits that REST apis are supposed to bring. </p>
<p>REST clients do take longer to build than SOAP clients but they are not tied to one specific service, so you should be able to re-use them across services. Take the classic example, of a web browser. How many services can a web browser access? What about a Feed Reader? Now how many different services can the average Twitter client access? Yes, just one. </p>
<p>REST clients are not supposed to be built to interface with a single service, they are supposed to be built to handle specific media types that could be served by any service. The obvious question to that is, how can you build a REST client for a service that delivers application/json or application/xml. Well you can&#8217;t. That&#8217;s because those formats are completely useless to a REST client. You said it yourself, </p>
<blockquote><p>you have to make &quot;guesses&quot; as to what will come back across the pipe as there is no real schema or reference document </p>
</blockquote>
<p>You are absolutely correct for services like Twitter. However, the self-descriptive constraint in REST says that the HTTP content type header should describe exactly the content that is being transmitted across the wire. Delivering application/json and application/xml tells you nothing about the content. </p>
<p>When it comes to considering the performance of REST based systems it is necessary look at the bigger picture. Talking about envelope bytes is like talking about loop unwinding when comparing a quick-sort to a shell-sort. There are scenarios where SOAP can perform better, and there are scenarios where REST can perform better. Context is everything. </p>
<p>REST gains much of its performance advantage by being very flexible about what media types it supports and by having sophisticated support for caching. For caching to work well though nearly all of the constraints must be adhered to. </p>
<p>Your last point about readable urls is by far the most ironic. If you truly commit to the hypermedia constraint, then every URL could be a GUID and the client developer would lose nothing in readability. </p>
<p>The fact that URIs should be opaque to the client is one of the most key things when developing REST systems. Readable URLs are convenient for the server developer and well structured URLs make it easier for the server framework to dispatch requests, but those are implementation details that should have no impact on the developers consuming the API. </p>
<p>The Twitter API is not even close to being RESTful and that is why you are unable to see any benefit to using it over SOAP. The Netflix API is much closer but it&#8217;s use of generic media types demonstrates that failing to adhere to even a single constraint can have a profound impact on the benefits derived from the service. </p>
<h3>It may not be all their fault</h3>
<p>I&#8217;ve done a whole lot of dumping on the service providers, but it takes two to dance RESTfully. A service may follow all of the constraints religiously and a client can still easily undo all of the benefits. </p>
<p>If a client hard codes urls to access certain types of resources then it is preventing the server from changing those urls. Any kind URL construction based on implicit knowledge of how the service structures its urls is a violation. </p>
<p>Making assumptions about what type of representation will be returned from a link can lead to problems. Making assumptions about the content of the representation based on knowledge that is not explicitly stated in the HTTP headers is definitely going to create coupling that will cause pain in the future. </p>
<h3>Should they have used SOAP?</h3>
<p> Personally, I don&#8217;t think so. REST done right allows a distributed system to evolve over the long term. If you are building distributed systems that have components that are developed by different people and need to last for many years, then REST is a pretty good option.   </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/07/21/the-stackoverflow-question-that-couldnt-stay-open/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>World’s simplest OData service</title>
		<link>http://www.bizcoder.com/index.php/2010/03/26/worlds-simplest-odata-service/</link>
		<comments>http://www.bizcoder.com/index.php/2010/03/26/worlds-simplest-odata-service/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 11:50:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[OData]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/03/26/worlds-simplest-odata-service/</guid>
		<description><![CDATA[I get frustrated sometime trying to play around with new Microsoft technologies.&#160; The process usually involves;&#160; install this CTP, apply this hotfix, create a project using this template, and this item using another template.&#160; By then end I may have something working but I don’t know what magic happened behind the scenes. Here is a [...]]]></description>
			<content:encoded><![CDATA[<p>I get frustrated sometime trying to play around with new Microsoft technologies.&#160; The process usually involves;&#160; install this CTP, apply this hotfix, create a project using this template, and this item using another template.&#160; By then end I may have something working but I don’t know what magic happened behind the scenes.</p>
<p>Here is a bare bones implementation of an OData service, no magic allowed (Ok, without actually going to the command line compiler).&#160; </p>
<p>What you will need for this experiment is:</p>
<p>1) .Net Framework 3.5 sp1</p>
<p>2) A new Visual Studio 2008 console application</p>
<p>3) These references </p>
<ul>
<ul>
<li>System </li>
<li>System.Core </li>
<li>System.ServiceModel&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;—This brings in the WCF stack</li>
<li>System.ServiceModel.Web &lt;—This brings in the Web friendly WCF service host</li>
<li>System.Data.Services&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;—This brings in the OData service host</li>
</ul>
</ul>
<p>&#160;</p>
<p>4) and this code</p>
<div>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Data.Services;
<span class="kwrd">using</span> System.Linq;

<span class="kwrd">namespace</span> ODataConsoleService {
    <span class="kwrd">class</span> Program {
        <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args) {

            <span class="kwrd">string</span> serviceAddress = <span class="str">&quot;http://localhost:998&quot;</span>;
            Uri[] uriArray = { <span class="kwrd">new</span> Uri(serviceAddress) };
            Type serviceType = <span class="kwrd">typeof</span>(CustomerDataService);

            <span class="kwrd">using</span> (var host = <span class="kwrd">new</span> DataServiceHost(serviceType, uriArray)) {
                host.Open();
                Console.WriteLine(<span class="str">&quot;Press any key to stop service&quot;</span>);
                Console.ReadKey();
            }

        }

    }

    <span class="rem">// Expose IQueryable properties as read-only Atom collections</span>
    <span class="kwrd">public</span> <span class="kwrd">class</span> CustomerDataService : DataService&lt;CustomerService&gt; {
        <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> InitializeService(IDataServiceConfiguration config) {
            config.SetEntitySetAccessRule(<span class="str">&quot;*&quot;</span>, EntitySetRights.AllRead);
        }
    }

    <span class="rem">// Expose list of customers Customer as IQueryable</span>
    <span class="kwrd">public</span> <span class="kwrd">class</span> CustomerService {
        <span class="kwrd">private</span> List&lt;Customer&gt; _List = <span class="kwrd">new</span> List&lt;Customer&gt;();

        <span class="kwrd">public</span> CustomerService() {

            _List.Add(<span class="kwrd">new</span> Customer() { ID = 1, Code = <span class="str">&quot;BLAH&quot;</span>, Name = <span class="str">&quot;Blah&quot;</span> });
            _List.Add(<span class="kwrd">new</span> Customer() { ID = 2, Code = <span class="str">&quot;Bob&quot;</span>, Name = <span class="str">&quot;Bob's Hardware&quot;</span> });
            _List.Add(<span class="kwrd">new</span> Customer() { ID = 3, Code = <span class="str">&quot;Bill&quot;</span>, Name = <span class="str">&quot;Bills Fishmongers&quot;</span> });
        }

        <span class="kwrd">public</span> IQueryable&lt;Customer&gt; Customers {
            get {
                <span class="kwrd">return</span> _List.AsQueryable&lt;Customer&gt;();
            }
        }

    }

    <span class="rem">// Entity to expose in atom:Entry</span>
    <span class="kwrd">public</span> <span class="kwrd">class</span> Customer {
        <span class="kwrd">public</span> <span class="kwrd">int</span> ID { get; set; }  <span class="rem">// ID is required to be a viable OData entity</span>
        <span class="kwrd">public</span> <span class="kwrd">string</span> Code { get; set; }
        <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; }
    }

}</pre>
</div>
<p>&#160;</p>
<p>That’s it.&#160; That’s all you need to expose a complete <a href="http://tools.ietf.org/html/rfc5023">Atom Pub</a> compliant service exposing your objects.</p>
<p>Once you have that, you can Run the program and use a web browser to browse to <a href="http://localhost:998">http://localhost:998</a> to see the collections.&#160;&#160; Don’t forget to look in the magic url <a href="http://localhost:998/$metadata">http://localhost:998/$metadata</a>&#160; Sorry, some magic I am still trying to figure out how to remove!</p>
<p>Credit goes to <a href="http://blogs.msdn.com/alexj/archive/2009/12/11/tip-48-how-to-host-a-data-service-in-wcf.aspx">Alex James</a> and <a href="http://blogs.msdn.com/phaniraj/">Phani</a> for getting me most of the way there.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/03/26/worlds-simplest-odata-service/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using the HttpClient and the OData service to download Mix videos</title>
		<link>http://www.bizcoder.com/index.php/2010/03/20/using-the-httpclient-and-the-odata-service-to-download-mix-videos/</link>
		<comments>http://www.bizcoder.com/index.php/2010/03/20/using-the-httpclient-and-the-odata-service-to-download-mix-videos/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 02:13:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[OData]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/03/20/using-the-httpclient-and-the-odata-service-to-download-mix-videos/</guid>
		<description><![CDATA[Here is some code I wrote to give me some experience playing with an OData service, learning more Linq, using my favourite HTTP client library and getting to download mix videos.&#160; It will download only the videos related to the tag name that you specify and currently it is set to download the low quality [...]]]></description>
			<content:encoded><![CDATA[<p>Here is some code I wrote to give me some experience playing with an OData service, learning more Linq, using my favourite HTTP client library and getting to download mix videos.&#160; </p>
<p>It will download only the videos related to the tag name that you specify and currently it is set to download the low quality wmv files.&#160; Feel free to pick whatever content type you like!</p>
<p>You will need the http client library that is buried in <a href="http://aspnet.codeplex.com/releases/view/24644">here</a>, and you need to set the tagName to whatever interests you, other than that, it should just work.&#160; Please note, there is only one hardcoded url in this client <img src='http://www.bizcoder.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>If you have questions, you can usually find me on twitter @darrelmiller </p>
<p>&#160;</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var httpClient = <span class="kwrd">new</span> HttpClient(<span class="str">&quot;http://api.visitmix.com/OData.svc&quot;</span>);

<span class="kwrd">string</span> tagName = <span class="str">&quot;REST&quot;</span>;

var serviceDocument = httpClient.Get().Content.ReadAsDataContract&lt;AtomPub10ServiceDocumentFormatter&gt;().Document; ;

<span class="rem">// Get Url for Tags collection</span>
var tagsUrl = (from co <span class="kwrd">in</span> serviceDocument.Workspaces[0].Collections
               <span class="kwrd">where</span> co.Title.Text == <span class="str">&quot;Tags&quot;</span>
               select <span class="kwrd">new</span> Uri(serviceDocument.BaseUri, co.Link)).FirstOrDefault();

var tagsDocument = httpClient.Get(tagsUrl).Content.ReadAsDataContract&lt;Atom10FeedFormatter&gt;().Feed;

<span class="rem">// Find Sessions Link for tag</span>
var sessionsUri = (from tg <span class="kwrd">in</span> tagsDocument.Items
           from lk <span class="kwrd">in</span> tg.Links
           <span class="kwrd">where</span> tg.Title.Text == tagName &amp;&amp;
                lk.RelationshipType == <span class="str">&quot;http://schemas.microsoft.com/ado/2007/08/dataservices/related/Sessions&quot;</span>
          select <span class="kwrd">new</span> Uri(tagsDocument.BaseUri, lk.Uri)).First();

<span class="rem">// Follow the link to get the list of sessions</span>
var sessionsForTagFeed = httpClient.Get(sessionsUri).Content.ReadAsDataContract&lt;Atom10FeedFormatter&gt;().Feed; ;

<span class="rem">// Get the files links for each session</span>
var sessionFileLinks = (from st <span class="kwrd">in</span> sessionsForTagFeed.Items
              from lk <span class="kwrd">in</span> st.Links
              <span class="kwrd">where</span> lk.RelationshipType == <span class="str">&quot;http://schemas.microsoft.com/ado/2007/08/dataservices/related/Files&quot;</span>
              select <span class="kwrd">new</span> Uri(sessionsForTagFeed.BaseUri,lk.Uri)
              );

<span class="rem">// Loop through each list of files and download</span>
<span class="kwrd">foreach</span> (Uri sessionFilesLink <span class="kwrd">in</span> sessionFileLinks) {

    var filesDocument = httpClient.Get(sessionFilesLink).Content.ReadAsDataContract&lt;Atom10FeedFormatter&gt;().Feed;

    var files = from it <span class="kwrd">in</span> filesDocument.Items
                let uri = it.GetMediaResourceUri()
                <span class="kwrd">where</span> it.Content.Type == <span class="str">&quot;video/x-ms-wmv&quot;</span> &amp;&amp; !uri.ToString().Contains(<span class="str">&quot;wmv-hq&quot;</span>)
                select uri;

    <span class="kwrd">foreach</span> (Uri uri <span class="kwrd">in</span> files) {
        <span class="kwrd">try</span> {
            var response = httpClient.Get(uri);
            var filename = uri.Segments.Last();
            <span class="kwrd">using</span> (var file = <span class="kwrd">new</span> FileStream(filename, FileMode.CreateNew)) {
                response.Content.WriteTo(file);
                response.EnsureStatusIsSuccessful();
            }
        }
        <span class="kwrd">catch</span> (WebException ex) {
            Console.WriteLine(<span class="str">&quot;Failed to download &quot;</span> + uri.ToString() + <span class="str">&quot; : &quot;</span> + ex.Message);
            <span class="rem">// Continue onto next</span>
        }

    }
}</pre>
</div>
<p>&#160;</p>
<p>Just paste this code into a Console app and add references to the following DLL’s</p>
<ul>
<li>System.ServiceModel.Web (.Net 3.5)</li>
<li>System.Runtime.Serialization</li>
<li>Microsoft.Http&#160; ( found in \Program Files (x86)\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies)</li>
<li>Microsoft.Http.Extensions&#160; ( as above)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/03/20/using-the-httpclient-and-the-odata-service-to-download-mix-videos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Convert XML to JSON using XSLT</title>
		<link>http://www.bizcoder.com/index.php/2010/02/12/convert-xml-to-json-using-xslt/</link>
		<comments>http://www.bizcoder.com/index.php/2010/02/12/convert-xml-to-json-using-xslt/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 14:54:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/02/12/convert-xml-to-json-using-xslt/</guid>
		<description><![CDATA[How about that for acronym soup?&#160; In the spirit of doing smaller posts but more often, here is a handy little XSLT.&#160; Assuming you have the following XML, &#160; &#60;Customers&#62; &#60;Customer Id=&#34;99&#34;&#62; &#60;Name&#62;Bob&#60;/Name&#62; &#60;Age&#62;39&#60;/Age&#62; &#60;Address&#62; &#60;Street&#62;10 Idle Lane&#60;/Street&#62; &#60;City&#62;Yucksville&#60;/City&#62; &#60;PostalCode&#62;xxxyyy&#60;/PostalCode&#62; &#60;/Address&#62; &#60;/Customer&#62; &#60;Customer Id=&#34;101&#34;&#62; &#60;Name&#62;Bill&#60;/Name&#62; &#60;Age&#62;39&#60;/Age&#62; &#60;Address&#62; &#60;Street&#62;10 Idle Lane&#60;/Street&#62; &#60;City&#62;Yucksville&#60;/City&#62; &#60;PostalCode&#62;xxxyyy&#60;/PostalCode&#62; &#60;/Address&#62; &#60;/Customer&#62; &#60;/Customers&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>How about that for acronym soup?&#160; In the spirit of doing smaller posts but more often, here is a handy little XSLT.&#160; </p>
<p>Assuming you have the following XML, </p>
<p>&#160;</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Customers</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Customer</span> <span class="attr">Id</span><span class="kwrd">=&quot;99&quot;</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Name</span><span class="kwrd">&gt;</span>Bob<span class="kwrd">&lt;/</span><span class="html">Name</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Age</span><span class="kwrd">&gt;</span>39<span class="kwrd">&lt;/</span><span class="html">Age</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Address</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">Street</span><span class="kwrd">&gt;</span>10 Idle Lane<span class="kwrd">&lt;/</span><span class="html">Street</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">City</span><span class="kwrd">&gt;</span>Yucksville<span class="kwrd">&lt;/</span><span class="html">City</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">PostalCode</span><span class="kwrd">&gt;</span>xxxyyy<span class="kwrd">&lt;/</span><span class="html">PostalCode</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">Address</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Customer</span> <span class="attr">Id</span><span class="kwrd">=&quot;101&quot;</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Name</span><span class="kwrd">&gt;</span>Bill<span class="kwrd">&lt;/</span><span class="html">Name</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Age</span><span class="kwrd">&gt;</span>39<span class="kwrd">&lt;/</span><span class="html">Age</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Address</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">Street</span><span class="kwrd">&gt;</span>10 Idle Lane<span class="kwrd">&lt;/</span><span class="html">Street</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">City</span><span class="kwrd">&gt;</span>Yucksville<span class="kwrd">&lt;/</span><span class="html">City</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">PostalCode</span><span class="kwrd">&gt;</span>xxxyyy<span class="kwrd">&lt;/</span><span class="html">PostalCode</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">Address</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Customer</span><span class="kwrd">&gt;</span>

<span class="kwrd">&lt;/</span><span class="html">Customers</span><span class="kwrd">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>Using this XSLT </p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">&lt;?</span><span class="html">xml</span> <span class="attr">version</span><span class="kwrd">=&quot;1.0&quot;</span>?<span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">xsl:stylesheet</span> <span class="attr">version</span><span class="kwrd">=&quot;1.0&quot;</span> <span class="attr">xmlns:xsl</span><span class="kwrd">=&quot;http://www.w3.org/1999/XSL/Transform&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">xsl:output</span> <span class="attr">method</span><span class="kwrd">=&quot;text&quot;</span><span class="kwrd">/&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">xsl:template</span> <span class="attr">match</span><span class="kwrd">=&quot;/&quot;</span><span class="kwrd">&gt;</span>{
        <span class="kwrd">&lt;</span><span class="html">xsl:apply-templates</span> <span class="attr">select</span><span class="kwrd">=&quot;*&quot;</span><span class="kwrd">/&gt;</span>}
    <span class="kwrd">&lt;/</span><span class="html">xsl:template</span><span class="kwrd">&gt;</span>

    <span class="rem">&lt;!-- Object or Element Property--&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">xsl:template</span> <span class="attr">match</span><span class="kwrd">=&quot;*&quot;</span><span class="kwrd">&gt;</span>
        &quot;<span class="kwrd">&lt;</span><span class="html">xsl:value-of</span> <span class="attr">select</span><span class="kwrd">=&quot;name()&quot;</span><span class="kwrd">/&gt;</span>&quot; : <span class="kwrd">&lt;</span><span class="html">xsl:call-template</span> <span class="attr">name</span><span class="kwrd">=&quot;Properties&quot;</span><span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">xsl:template</span><span class="kwrd">&gt;</span>

    <span class="rem">&lt;!-- Array Element --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">xsl:template</span> <span class="attr">match</span><span class="kwrd">=&quot;*&quot;</span> <span class="attr">mode</span><span class="kwrd">=&quot;ArrayElement&quot;</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">xsl:call-template</span> <span class="attr">name</span><span class="kwrd">=&quot;Properties&quot;</span><span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">xsl:template</span><span class="kwrd">&gt;</span>

    <span class="rem">&lt;!-- Object Properties --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">xsl:template</span> <span class="attr">name</span><span class="kwrd">=&quot;Properties&quot;</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">xsl:variable</span> <span class="attr">name</span><span class="kwrd">=&quot;childName&quot;</span> <span class="attr">select</span><span class="kwrd">=&quot;name(*[1])&quot;</span><span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">xsl:choose</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">xsl:when</span> <span class="attr">test</span><span class="kwrd">=&quot;not(*|@*)&quot;</span><span class="kwrd">&gt;</span>&quot;<span class="kwrd">&lt;</span><span class="html">xsl:value-of</span> <span class="attr">select</span><span class="kwrd">=&quot;.&quot;</span><span class="kwrd">/&gt;</span>&quot;<span class="kwrd">&lt;/</span><span class="html">xsl:when</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">xsl:when</span> <span class="attr">test</span>=&quot;<span class="attr">count</span>(*[<span class="attr">name</span>()=$<span class="attr">childName</span>]) <span class="kwrd">&gt;</span> 1&quot;<span class="kwrd">&gt;</span>{ &quot;<span class="kwrd">&lt;</span><span class="html">xsl:value-of</span> <span class="attr">select</span><span class="kwrd">=&quot;$childName&quot;</span><span class="kwrd">/&gt;</span>&quot; :[<span class="kwrd">&lt;</span><span class="html">xsl:apply-templates</span> <span class="attr">select</span><span class="kwrd">=&quot;*&quot;</span> <span class="attr">mode</span><span class="kwrd">=&quot;ArrayElement&quot;</span><span class="kwrd">/&gt;</span>] }<span class="kwrd">&lt;/</span><span class="html">xsl:when</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">xsl:otherwise</span><span class="kwrd">&gt;</span>{
                <span class="kwrd">&lt;</span><span class="html">xsl:apply-templates</span> <span class="attr">select</span><span class="kwrd">=&quot;@*&quot;</span><span class="kwrd">/&gt;</span>
                <span class="kwrd">&lt;</span><span class="html">xsl:apply-templates</span> <span class="attr">select</span><span class="kwrd">=&quot;*&quot;</span><span class="kwrd">/&gt;</span>
    }<span class="kwrd">&lt;/</span><span class="html">xsl:otherwise</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">xsl:choose</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">xsl:if</span> <span class="attr">test</span><span class="kwrd">=&quot;following-sibling::*&quot;</span><span class="kwrd">&gt;</span>,<span class="kwrd">&lt;/</span><span class="html">xsl:if</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">xsl:template</span><span class="kwrd">&gt;</span>

    <span class="rem">&lt;!-- Attribute Property --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">xsl:template</span> <span class="attr">match</span><span class="kwrd">=&quot;@*&quot;</span><span class="kwrd">&gt;</span>&quot;<span class="kwrd">&lt;</span><span class="html">xsl:value-of</span> <span class="attr">select</span><span class="kwrd">=&quot;name()&quot;</span><span class="kwrd">/&gt;</span>&quot; : &quot;<span class="kwrd">&lt;</span><span class="html">xsl:value-of</span> <span class="attr">select</span><span class="kwrd">=&quot;.&quot;</span><span class="kwrd">/&gt;</span>&quot;,
    <span class="kwrd">&lt;/</span><span class="html">xsl:template</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">xsl:stylesheet</span><span class="kwrd">&gt;</span></pre>
</div>
<p>You can generate this JSON</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">{
    <span class="str">&quot;Customers&quot;</span> : {
        <span class="str">&quot;Customer&quot;</span> : [
            {
                <span class="str">&quot;Id&quot;</span> : <span class="str">&quot;99&quot;</span>,
                <span class="str">&quot;Name&quot;</span> : <span class="str">&quot;Bob&quot;</span>,
                <span class="str">&quot;Age&quot;</span> : <span class="str">&quot;39&quot;</span>,
                <span class="str">&quot;Address&quot;</span> : {
                    <span class="str">&quot;Street&quot;</span> : <span class="str">&quot;10 Idle Lane&quot;</span>,
                    <span class="str">&quot;City&quot;</span> : <span class="str">&quot;Yucksville&quot;</span>,
                    <span class="str">&quot;PostalCode&quot;</span> : <span class="str">&quot;xxxyyy&quot;</span>
                }
            },
            {
                <span class="str">&quot;Id&quot;</span> : <span class="str">&quot;101&quot;</span>,
                <span class="str">&quot;Name&quot;</span> : <span class="str">&quot;Bill&quot;</span>,
                <span class="str">&quot;Age&quot;</span> : <span class="str">&quot;39&quot;</span>,
                <span class="str">&quot;Address&quot;</span> : {
                    <span class="str">&quot;Street&quot;</span> : <span class="str">&quot;10 Idle Lane&quot;</span>,
                    <span class="str">&quot;City&quot;</span> : <span class="str">&quot;Yucksville&quot;</span>,
                    <span class="str">&quot;PostalCode&quot;</span> : <span class="str">&quot;xxxyyy&quot;</span>
                }
            }
        ]
    }
} </pre>
</div>
<p>It would be really interesting to try and use <a href="http://johannburkard.de/software/xsltjs/">this</a> Javascript XSLT processor to do the transform directly in the browser.&#160; That way any web api that generates XML could be flipped into a JSON representation for direct access in Javascript.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/02/12/convert-xml-to-json-using-xslt/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>But can you test it?</title>
		<link>http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/</link>
		<comments>http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 14:13:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/</guid>
		<description><![CDATA[Testing code that uses HttpWebRequest directly, is a real pain.&#160; Usually what I have seen people do is create a service interface that hides the real http client behind the interface and then create fake service implementations to actually run their tests against.&#160; The annoying part about that solution is that Http client interfaces tend [...]]]></description>
			<content:encoded><![CDATA[<p>Testing code that uses HttpWebRequest directly, is a real pain.&#160; Usually what I have seen people do is create a service interface that hides the real http client behind the interface and then create fake service implementations to actually run their tests against.&#160; The annoying part about that solution is that Http client interfaces tend to be relatively large to fake when you consider all the properties and methods of the Http request objects and http response objects.&#160; It is not inconceivable that the interface ends up exposing 90% of the functionality of the http client objects.</p>
<p>The Microsoft.Http library provides an alternative solution, assuming you don’t mind taking a dependency on it.&#160; The HttpClient class supports the notion of a pipeline of stages with one of those stages being a transport stage that actually makes the real http request.&#160; If we introduce a new stage prior to the transport stage we can intercept the request and return a response object with pre-canned values.&#160;&#160; </p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="rem">//Arrange</span>
var client = <span class="kwrd">new</span> HttpClient();
client.Stages.Add(<span class="kwrd">new</span> FixedTransport((key) =&gt; <span class="kwrd">new</span> HttpResponseMessage() {
   Content = HttpContent.Create(<span class="str">&quot;Hello World&quot;</span>)
}));

<span class="rem">//Act</span>
var  response = client.Get(<span class="str">&quot;http://example.org&quot;</span>);

<span class="rem">//Assert</span>
Assert.AreEqual(<span class="str">&quot;Hello World&quot;</span>,response.Content.ReadAsString());</pre>
</div>
<p>&#160;</p>
<p>This unit test creates a instance of the real HttpClient and adds a new processing stage called FixedTransport.&#160; This class is available in Microsoft.Http.Test and unfortunately you cannot create your own version of this class because the method that needs to be overridden to create a custom response is marked as internal.&#160; The Test dll can do it because it is pointed to by the InternalsVisibleTo attribute.&#160; The only other option is to recompile the core library yourself. <img src='http://www.bizcoder.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>The FixedTransport stage is actually derived from a caching stage that can associate a URI to particular response.&#160; In the sample above, I simply ignore the key and return the same content for all URIs.&#160; However, this mechanism would allow you to preload the cache with a set of URI/response pairs and then you could run a test that performed multiple GET requests.</p>
<p>I’m not exactly sure why but from looking through the source it does appear that if you made a non-GET request the key value would be null.&#160; That would allow you to return a specific response to a POST or PUT request based on that null key value.</p>
<p>I hope it is fairly obvious even after this very simple example that you should be able to easily generate pre-canned responses to standard http requests and still have access to the full capabilities of the HttpClient library without having to fake any classes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FOR XML PATH and CQRS</title>
		<link>http://www.bizcoder.com/index.php/2010/01/18/for-xml-path-and-cqrs/</link>
		<comments>http://www.bizcoder.com/index.php/2010/01/18/for-xml-path-and-cqrs/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 13:20:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CQRS]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/?p=107</guid>
		<description><![CDATA[In a recent twitter exchange with Colin Jack I claimed that SELECT {…} FROM […] FOR XML PATH() is pretty much all you need for providing the Reporting side of CQRS.&#160; Ok, so maybe I overstated it a tad, but it is a valuable technique.&#160; He suggested I blog about it, so I figured even [...]]]></description>
			<content:encoded><![CDATA[<p>In a recent twitter exchange with <a href="http://twitter.com/colin_jack">Colin Jack</a> I claimed that SELECT {…} FROM […] FOR XML PATH() is pretty much all you need for providing the Reporting side of CQRS.&#160; Ok, so maybe I overstated it a tad, but it is a valuable technique.&#160; He suggested I blog about it, so I figured even if people don’t use it for CQRS, some of the neat things you can do with FOR XML PATH may be interesting to a few people.</p>
<p>Command Query Responsibility Separation(CQRS) is an interesting architecture that is suitable for highly scalable applications with complex business logic.&#160; Instead of me doing a horrible job of trying to explain it, here are links to people who know what they are talking about.</p>
<p>Greg Young &#8211; <a href="http://codebetter.com/blogs/gregyoung/archive/2009/07/15/unshackle-your-domain.aspx">http://codebetter.com/blogs/gregyoung/archive/2009/07/15/unshackle-your-domain.aspx</a></p>
<p>UDI Dahan &#8211; <a href="http://www.udidahan.com/2009/12/09/clarified-cqrs/">http://www.udidahan.com/2009/12/09/clarified-cqrs/</a></p>
<p>The reporting side of CQRS requires a simple mechanism for getting read-only data from a server down to the presentation tier with minimal effort.&#160; I am suggesting the use of XML as a wire format and I am going to make the assumption that we have chosen a relational database as the store for the reporting database. More specifically, we require Microsoft SQL Server because, from what I can <a href="http://stackoverflow.com/questions/664815/is-there-an-equivalent-to-ms-sql-for-xml-path-in-other-database-products">find</a>, MS SQL Server is the only database engine that supports this level of flexibility when generating XML from relational tables.&#160;&#160; </p>
<p>Ideally we should be able to create any desired structure of XML based on data in our relational database.&#160; We need the flexibility to generate data as attributes or elements, create nested structures, use namespaces or not, at a minimum. </p>
<p>I’m going to start showing some of the basics of the FOR XML PATH syntax and build on it until we are creating relatively complex xml documents in a single SQL query.</p>
<p>This is pretty much the <strong>simplest query</strong> that you can create:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">SELECT</span> Code <span class="kwrd">AS</span> <span class="str">'Code'</span>,
       Name <span class="kwrd">AS</span> <span class="str">'Name'</span>
<span class="kwrd">FROM</span> tblCustomer
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Customer'</span>)</pre>
</p></div>
<p>It produces XML that looks like this:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Code</span><span class="kwrd">&gt;</span>CUSTOMER-ONE<span class="kwrd">&lt;/</span><span class="html">Code</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Name</span><span class="kwrd">&gt;</span>Hypro Networks Inc.<span class="kwrd">&lt;/</span><span class="html">Name</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Code</span><span class="kwrd">&gt;</span>CUSTOMER-A<span class="kwrd">&lt;/</span><span class="html">Code</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Name</span><span class="kwrd">&gt;</span>Customer A<span class="kwrd">&lt;/</span><span class="html">Name</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Customer</span><span class="kwrd">&gt;</span></pre>
</p></div>
<p>The only problem with this is that it is not a valid XML document as there is more than one root element.&#160; To <strong>create a proper XML document</strong>, you need to do:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">SELECT</span> Code <span class="kwrd">AS</span> <span class="str">'Code'</span>,
        Name <span class="kwrd">AS</span> <span class="str">'Name'</span>
<span class="kwrd">FROM</span> tblCustomer
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Customer'</span>), ROOT(<span class="str">'Customers'</span>)</pre>
</div>
<p>which then gives you,</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Customers</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Code</span><span class="kwrd">&gt;</span>CUSTOMER-ONE<span class="kwrd">&lt;/</span><span class="html">Code</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Name</span><span class="kwrd">&gt;</span>Hypro Networks Inc.<span class="kwrd">&lt;/</span><span class="html">Name</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Code</span><span class="kwrd">&gt;</span>CUSTOMER-A<span class="kwrd">&lt;/</span><span class="html">Code</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Name</span><span class="kwrd">&gt;</span>Customer A<span class="kwrd">&lt;/</span><span class="html">Name</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Customers</span><span class="kwrd">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>These examples showed how to create data as XML elements, but sometimes it is desirable to use attributes.&#160; Attributes take quite a bit less space and suitable for most content that is small and does not contain significant whitespace.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">SELECT</span> Code <span class="kwrd">AS</span> <span class="str">'@Code'</span>,
        Name <span class="kwrd">AS</span> <span class="str">'@Name'</span>
<span class="kwrd">FROM</span> tblCustomer
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Customer'</span>), ROOT(<span class="str">'Customers'</span>)</pre>
</div>
<p>By adding an @ symbol to the front of the column name, the data will be <strong>output as attributes</strong>:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Customers</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Customer</span> <span class="attr">Code</span><span class="kwrd">=&quot;CUSTOMER-ONE&quot;</span> <span class="attr">Name</span><span class="kwrd">=&quot;Hypro Networks Inc.&quot;</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Customer</span> <span class="attr">Code</span><span class="kwrd">=&quot;CUSTOMER-A&quot;</span> <span class="attr">Name</span><span class="kwrd">=&quot;Customer A&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Customers</span><span class="kwrd">&gt;</span></pre>
</div>
<p>One of the things that I like about using XML is that it is easy to <strong>group related pieces of data into other elements</strong>.&#160; The following query demonstrates how to do this: </p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">SELECT</span> Code <span class="kwrd">AS</span> <span class="str">'@Code'</span>,
        Name <span class="kwrd">AS</span> <span class="str">'@Name'</span>,
        Tel1 <span class="kwrd">AS</span> <span class="str">'Contact/@Tel'</span>,
        Fax1 <span class="kwrd">AS</span> <span class="str">'Contact/@Fax1'</span>
<span class="kwrd">FROM</span> tblCustomer
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Customer'</span>), ROOT(<span class="str">'Customers'</span>)</pre>
</div>
<p>Adding the slash into the column name directs SQL Server to create a <strong>new element to contain other nodes</strong>. </p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Customers</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Customer</span> <span class="attr">Code</span><span class="kwrd">=&quot;CUSTOMER-ONE&quot;</span> <span class="attr">Name</span><span class="kwrd">=&quot;Hypro Networks Inc.&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Contact</span> <span class="attr">Tel</span><span class="kwrd">=&quot;1-993-345-4146&quot;</span> <span class="attr">Fax1</span><span class="kwrd">=&quot;1-993-345-4140&quot;</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Customer</span> <span class="attr">Code</span><span class="kwrd">=&quot;CUSTOMER-A&quot;</span> <span class="attr">Name</span><span class="kwrd">=&quot;Customer A&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Contact</span> <span class="attr">Tel</span><span class="kwrd">=&quot;872-494-2000&quot;</span> <span class="attr">Fax1</span><span class="kwrd">=&quot;872-494-3008&quot;</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Customer</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Customers</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Just one small warning, columns must be adjacent in the SQL query to exist under the same child element and all attributes of the parent element must be specified in the SQL query before the columns that will be in a child element.</p>
<p>So far we have only considered data from a single table.&#160; Using a simple SQL join it is easy to pull in data from other tables, but we can also create <strong>parent/child documents</strong>.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">SELECT</span>  Code <span class="kwrd">AS</span> <span class="str">'@Code'</span>,
        Invoice_Date <span class="kwrd">AS</span> <span class="str">'@Date'</span>,
        (<span class="kwrd">SELECT</span> ii.qty <span class="kwrd">AS</span> <span class="str">'Quantity'</span>,
                <span class="kwrd">LEFT</span>(ii.description,20) <span class="kwrd">AS</span> <span class="str">'Description'</span>
         <span class="kwrd">FROM</span> tblinvoitem ii <span class="kwrd">WHERE</span> ii.invoice_id = iv.id <span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Item'</span>),type)
<span class="kwrd">FROM</span> tblInvoice iv
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Invoice'</span>), ROOT(<span class="str">'Invoices'</span>)</pre>
</div>
<p>&#160;</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Invoices</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Invoice</span> <span class="attr">Code</span><span class="kwrd">=&quot;21201     &quot;</span> <span class="attr">Date</span><span class="kwrd">=&quot;2005-05-26T00:00:00&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Item</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>1.0000<span class="kwrd">&lt;/</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Description</span><span class="kwrd">&gt;</span>To supply material a<span class="kwrd">&lt;/</span><span class="html">Description</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Item</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Invoice</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Invoice</span> <span class="attr">Code</span><span class="kwrd">=&quot;21200     &quot;</span> <span class="attr">Date</span><span class="kwrd">=&quot;2005-05-18T00:00:00&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Item</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>25.0000<span class="kwrd">&lt;/</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Description</span><span class="kwrd">&gt;</span>S.S. Control Box Cov<span class="kwrd">&lt;/</span><span class="html">Description</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Item</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Item</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>0.0000<span class="kwrd">&lt;/</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Description</span><span class="kwrd">&gt;</span>S.S. Main Control Bo<span class="kwrd">&lt;/</span><span class="html">Description</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Item</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Invoice</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Invoices</span><span class="kwrd">&gt;</span></pre>
</div>
<p>The extra “type” parameter on the end of the subquery indicates to SQL that we want to embed the contents of the sub query as XML rather than just an escaped string.</p>
<p>One limitation that you will probably run into once you create this type of document is that there is no obvious way to <strong>insert attributes and elements into the root node</strong>.&#160; This can be overcome with a small trick:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">SELECT</span> <span class="str">'1.0'</span> <span class="kwrd">AS</span> <span class="str">'@Version'</span>,
        <span class="str">'List of Invoices'</span> <span class="kwrd">AS</span> <span class="str">'Summary'</span>,
( <span class="kwrd">SELECT</span>  Code <span class="kwrd">AS</span> <span class="str">'@Code'</span>,
        Invoice_Date <span class="kwrd">AS</span> <span class="str">'@Date'</span>,
        (<span class="kwrd">SELECT</span> ii.qty <span class="kwrd">AS</span> <span class="str">'Quantity'</span>,
                <span class="kwrd">LEFT</span>(ii.description,20) <span class="kwrd">AS</span> <span class="str">'Description'</span>
         <span class="kwrd">FROM</span> tblinvoitem ii <span class="kwrd">WHERE</span> ii.invoice_id = iv.id <span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Item'</span>),type)
<span class="kwrd">FROM</span> tblInvoice iv
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Invoice'</span>),type)
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Invoices'</span>)</pre>
</div>
<p>Using an outer query you can specify the attributes and elements that you want to appear in the root.&#160; Note that there is no alias for the sub query column.&#160;
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Invoices</span> <span class="attr">Version</span><span class="kwrd">=&quot;1.0&quot;</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Summary</span><span class="kwrd">&gt;</span>List of Invoices<span class="kwrd">&lt;/</span><span class="html">Summary</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Invoice</span> <span class="attr">Code</span><span class="kwrd">=&quot;21201     &quot;</span> <span class="attr">Date</span><span class="kwrd">=&quot;2005-05-26T00:00:00&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Item</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>1.0000<span class="kwrd">&lt;/</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Description</span><span class="kwrd">&gt;</span>To supply material a<span class="kwrd">&lt;/</span><span class="html">Description</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Item</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Invoice</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Invoice</span> <span class="attr">Code</span><span class="kwrd">=&quot;21200     &quot;</span> <span class="attr">Date</span><span class="kwrd">=&quot;2005-05-18T00:00:00&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Item</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>25.0000<span class="kwrd">&lt;/</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Description</span><span class="kwrd">&gt;</span>S.S. Control Box Cov<span class="kwrd">&lt;/</span><span class="html">Description</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Item</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Item</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>0.0000<span class="kwrd">&lt;/</span><span class="html">Quantity</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">Description</span><span class="kwrd">&gt;</span>S.S. Main Control Bo<span class="kwrd">&lt;/</span><span class="html">Description</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Item</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Invoice</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Invoices</span><span class="kwrd">&gt;</span></pre>
</div>
<p>And of course, no discussion on XML is complete without discussing namespaces.&#160; Here is how you can <strong>add namespaces to the XML result</strong>:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">WITH</span> XMLNAMESPACES(<span class="kwrd">DEFAULT</span> <span class="str">'http://example.org/Invoices'</span>)
<span class="kwrd">SELECT</span> <span class="str">'1.0'</span> <span class="kwrd">AS</span> <span class="str">'@Version'</span>,
        <span class="str">'List of Invoices'</span> <span class="kwrd">AS</span> <span class="str">'Summary'</span>,
( <span class="kwrd">SELECT</span>  Code <span class="kwrd">AS</span> <span class="str">'@Code'</span>,
        Invoice_Date <span class="kwrd">AS</span> <span class="str">'@Date'</span>,
        (<span class="kwrd">SELECT</span> ii.qty <span class="kwrd">AS</span> <span class="str">'Quantity'</span>,
                <span class="kwrd">LEFT</span>(ii.description,20) <span class="kwrd">AS</span> <span class="str">'Description'</span>
         <span class="kwrd">FROM</span> tblinvoitem ii <span class="kwrd">WHERE</span> ii.invoice_id = iv.id <span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Item'</span>),type)
<span class="kwrd">FROM</span> tblInvoice iv
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Invoice'</span>),type)
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'Invoices'</span>)</pre>
</div>
<p>I’m not going to show you the output of this, because it is ugly!&#160; Actually, the annoying part is that it puts the namespace on the root and then on each row of the sub query.&#160; </p>
<p>Hopefully these examples have shown some of the capability of FOR XML PATH but I find that sometimes technologies work well while you are working on arbitrary examples, but then you hit the real world and they seem to fall short.&#160; So, I decided to try and <strong>create an Atom feed using FOR XML PATH</strong>.&#160; Here is what I came up with.</p>
</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd">WITH</span> XMLNAMESPACES(<span class="kwrd">DEFAULT</span> <span class="str">'http://www.w3.org/2005/Atom'</span>)
<span class="kwrd">SELECT</span> <span class="str">'Customers'</span> <span class="kwrd">AS</span> <span class="str">'title'</span>,
        <span class="str">'List of customers'</span> <span class="kwrd">AS</span> <span class="str">'subtitle'</span>,
        <span class="str">'http://tavis.net/Customers'</span> <span class="kwrd">AS</span> <span class="str">'id'</span>,
        REPLACE(<span class="kwrd">CONVERT</span>(<span class="kwrd">varchar</span>,(<span class="kwrd">SELECT</span> <span class="kwrd">MAX</span>(<span class="kwrd">COALESCE</span>(ModifiedDate,CreatedDate)) <span class="kwrd">FROM</span> tblCustomer), 121),<span class="str">' '</span>,<span class="str">'T'</span>) + <span class="str">'Z'</span> <span class="kwrd">AS</span> <span class="str">'updated'</span>,
    (<span class="kwrd">SELECT</span> cu.Code <span class="kwrd">AS</span> <span class="str">'title'</span>,
            REPLACE(<span class="kwrd">CONVERT</span>(<span class="kwrd">varchar</span>,<span class="kwrd">COALESCE</span>(ModifiedDate,CreatedDate) , 121),<span class="str">' '</span>,<span class="str">'T'</span>) + <span class="str">'Z'</span> <span class="kwrd">AS</span> <span class="str">'updated'</span>,
            <span class="str">'Darrel Miller'</span> <span class="kwrd">AS</span> <span class="str">'author/name'</span>,
            <span class="str">'http://tavis.net/Customer/'</span> + LTRIM(STR(cu.ID)) <span class="kwrd">AS</span> <span class="str">'id'</span>,
            (<span class="kwrd">SELECT</span> *
                <span class="kwrd">FROM</span> (<span class="kwrd">SELECT</span> <span class="str">'alternate'</span> <span class="kwrd">AS</span> <span class="str">'@rel'</span>,
                    <span class="str">'http://tavis.net/Customer/1.html'</span> <span class="kwrd">AS</span> <span class="str">'@href'</span>
              <span class="kwrd">UNION</span>
              <span class="kwrd">SELECT</span> <span class="str">'edit'</span> <span class="kwrd">AS</span> <span class="str">'@rel'</span>,
                    <span class="str">'http://tavis.net/Customer/1.html'</span> <span class="kwrd">AS</span> <span class="str">'@href'</span>) l
             <span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'link'</span>),type ),
            cu.ModifiedDate <span class="kwrd">AS</span> <span class="str">'updated'</span>,
            cu.Name <span class="kwrd">AS</span> <span class="str">'summary'</span>
        <span class="kwrd">FROM</span> tblCustomer cu
        <span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'entry'</span>),type  )
<span class="kwrd">FOR</span> XML <span class="kwrd">PATH</span>(<span class="str">'feed'</span>)</pre>
</div>
<p>&#160;</p>
<p>Ok, so it is not pretty, but with a few T-SQL functions it could be cleaned up quite a bit.&#160; This query produces an atom feed that validates at validator.w3.org/feed and it does it in 8ms on my cheapo server with 20 entries .</p>
<p>The trickiest part of the above query was creating the two link elements.&#160; When you try and create two child elements with the same name, by default SQL Server will attempt to merge the two elements.&#160; By using the UNION and a sub query I was able to create the two separate elements.</p>
<p>So you really can create real world XML documents using FOR XML PATH. I believe this is a useful tool to have under your belt when you are trying to quickly get data out of a database down to a client tier.&#160; It would also be really nice if other database vendors picked up on this feature and implemented in their engines.&#160; One area that I didn’t cover but that is also very useful is that you can create T-SQL Functions that return XML and then call them recursively.&#160; This allows you to <strong>build hierarchical XML documents</strong>.&#160;&#160; My tests so far have also shown that building trees this way is very quick.</p>
<p>I’m hoping to do a follow up article that shows how you can use the XML from FOR XML PATH as input to XSLT to do all sorts of other interesting things like create audit triggers, data import scripts, create HTML pages, XAML&#160; and JSON documents.&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/01/18/for-xml-path-and-cqrs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Woe is me, the WOA unmanifesto</title>
		<link>http://www.bizcoder.com/index.php/2009/12/14/woe-is-me-the-woa-unmanifesto/</link>
		<comments>http://www.bizcoder.com/index.php/2009/12/14/woe-is-me-the-woa-unmanifesto/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 21:53:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2009/12/14/woe-is-me-the-woa-unmanifesto/</guid>
		<description><![CDATA[This started as a comment on the blog post here, but it got too long. I have two questions for Dion and a few comments. 1) Have you read (not just skimmed a few times) Roy&#8217;s dissertation on REST? 2) Have you written both a REST service and a REST client that is in production [...]]]></description>
			<content:encoded><![CDATA[<p>This started as a comment on the blog post <a href="http://hinchcliffe.org/archive/2009/12/14/18179.aspx">here</a>, but it got too long.</p>
<p>I have two questions for Dion and a few comments.   <br />1) Have you read (not just skimmed a few times) Roy&#8217;s dissertation on REST?    <br />2) Have you written both a REST service and a REST client that is in production today? </p>
<p>With all due respect, without actually creating REST applications, I don&#8217;t think anyone is qualified to attempt to define principles relating to REST and based on your Twitter bio: </p>
<blockquote><p>Internationally recognized business strategist, enterprise architect, keynote speaker, author, blogger, and consultant on Web 2.0, SOA, and next-gen business</p>
</blockquote>
<p>you sound like a talker, not a walker.&#160; Forgive me if I am wrong.</p>
<p>Here are my comments on the suggested principles, I’ve tried to be as constructive as I can muster:</p>
<p>Principle #1: I think it is a significant oversimplification to refer to a resource&#160; as data.&#160; </p>
<p>Principle #2: Can you clarify what you mean by &quot;favor granularity and depth in linkage&quot;? </p>
<p>Principle #3: I am pretty sure no-one has ever said that URIs should be self descriptive.&#160; In REST the request message should be self-descriptive, the URI being just one part of the message.&#160;&#160; The statement “URI should indicate what data format is being used and indicate nested elements with URL segmentation” is way too strong, maybe if you replace “should” with “can”.</p>
<p>Principle #4:&#160; This idea that all legacy databases should be exposed as data-oriented REST apis is crazy-talk.&#160; REST is an architectural style for building distributed APPLICATIONS.&#160; I.e. Exposing functionality over the web, not just data. Your example of cloud computing API’s is a perfect example.&#160; The Sun Cloud API is one of the best REST examples out there at the moment, but it exposes functionality for manipulating those cloud applications.&#160; Functions like turning the instances on and off.&#160; It’s far more than just exposing data.</p>
<p>Principle #5:&#160; You seem to be describing benefits rather than a principle.</p>
<p>#6:&#160; Ok</p>
<p>#7: I don’t get this concept at all.&#160; Does this mean we should all be using text/plain if we want the widest audience?</p>
<p>#8: Maybe I don’t want my resources to crawled by an SEO.&#160; Even if I do, conforming to the uniform interface and delivering standard format representations should be sufficient to meet any search engine requirements.</p>
<p>#9:&#160; “higher realized value”?&#160; Are you sure this isn’t another one of those spoof manifestos?</p>
<p>#10: I think you are referring to the idea that a resource should only have one canonical URI.&#160; I see this topic debated regularly and I do not yet see any consensus.</p>
<p>Ok, I give up for the moment, I’m a bit too depressed to continue.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2009/12/14/woe-is-me-the-woa-unmanifesto/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
