<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Christophe Geers&#039; Blog</title>
	<atom:link href="http://cgeers.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://cgeers.com</link>
	<description>Christophe Geers&#039; Blog about .NET programming</description>
	<lastBuildDate>Mon, 23 Jan 2012 07:40:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='cgeers.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Christophe Geers&#039; Blog</title>
		<link>http://cgeers.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://cgeers.com/osd.xml" title="Christophe Geers&#039; Blog" />
	<atom:link rel='hub' href='http://cgeers.com/?pushpress=hub'/>
		<item>
		<title>Dropbox REST API Part 2: API Requests</title>
		<link>http://cgeers.com/2012/01/08/dropbox-rest-api-part-2-api-requests/</link>
		<comments>http://cgeers.com/2012/01/08/dropbox-rest-api-part-2-api-requests/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 11:58:55 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dropbox]]></category>
		<category><![CDATA[Dropbox API]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3757</guid>
		<description><![CDATA[Introduction In the previous article, Dropbox REST API Part 1: Authentication, I showed you how you can obtain an access token using the Dropbox REST API and OAuth. Once you have an access token, you can use it to access the main Dropbox REST API. Let&#8217;s demonstrate this by using some of the API&#8217;s requests [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3757&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2011/12/logo1.png"><img src="http://cgeers.files.wordpress.com/2011/12/logo1.png?w=480" alt="DropBox Logo" title="DropBox Logo"   class="alignright size-full wp-image-3688" /></a></p>
<p>In the previous article, <a href="http://cgeers.com/2011/12/29/dropbox-rest-api-part-1-authentication/" target="_blank">Dropbox REST API Part 1: Authentication</a>, I showed you how you can obtain an access token using the Dropbox REST API and <a href="http://oauth.net/" target="_blank">OAuth</a>. </p>
<p>Once you have an access token, you can use it to access the main Dropbox REST API. Let&#8217;s demonstrate this by using some of the API&#8217;s requests such as retrieving account information and file (and directory) metadata. </p>
<p>It&#8217;s actually surprisingly easy. In the next part we&#8217;ll explore other options such as creating, deleting and moving folders.</p>
<p>Let&#8217;s get started&#8230;</p>
<p><span id="more-3757"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#account">Account</a></li>
<li><a href="#metadata">Metadata</a></li>
</ul>
<p><a title="account" name="account"></a><strong>Account</strong></p>
<p>I took the <a href="http://cgeers.com/download/" target="_blank">source code</a> from the first article (#62) in this series and structured it a bit differently, but in essence it still performs the same functionality. In this post I&#8217;ll only list the source code necessary to retrieve account information and file/folder metadata. You can check out how to retrieve an access token by reading the previous article and/or checking out the source code of this post.</p>
<p>Using the refactored code retrieving account information is very simple.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> accessToken = ...;
<span class="kwrd">var</span> api = <span class="kwrd">new</span> DropboxApi(<span class="str">"your API key"</span>, <span class="str">"your API secret"</span>, accessToken);
<span class="kwrd">var</span> account = api.GetAccountInfo();</pre>
</div>
<p>I created a class called DropboxApi. When creating an instance of this class you pass it your API key and secret (consumer key and secret) and an access token. By calling the GetAccountInfo() method you can retrieve information about the user&#8217;s Dropbox account.</p>
<p>The GetAccountInfo() method executes the following code:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> Account GetAccountInfo()
{
    <span class="kwrd">var</span> uri = <span class="kwrd">new</span> Uri(<span class="kwrd">new</span> Uri(DropboxRestApi.BaseUri), <span class="str">"account/info"</span>);
    <span class="kwrd">var</span> json = GetResponse(uri);
    <span class="kwrd">return</span> ParseJson&lt;Account&gt;(json);
}</pre>
</div>
<p>The DropboxRestApi.BaseUri returns the base URL for the REST API, namely https://api.dropbox.com/1. To retrieve the account information you need to append account/info to it. Thus behind the scenes a request is sent to:</p>
<p><a href="https://api.dropbox.com/1/account/info" target="_blank">https://api.dropbox.com/1/account/info</a></p>
<p>You need to sign this request using your consumer key, secret and access token. If you don&#8217;t sign the request you&#8217;ll receive the error &#8220;Invalid OAuth request&#8221;. </p>
<p>During the authentication phase you already saw how to sign a request using OAuth. Well&#8230;you can reuse that same code. Just check out the <a href="http://cgeers.com/2011/12/29/dropbox-rest-api-part-1-authentication/" target="_blank">previous article</a> to see how signing requests works.</p>
<p>To make it easy I moved this code into its own class called OAuth. Using this class you can sign a request using just two lines of code:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> oauth = <span class="kwrd">new</span> OAuth();
<span class="kwrd">var</span> requestUri = oauth.SignRequest(
    uri, <span class="str">"API key"</span>, <span class="str">"API secret"</span>, accessToken);
</pre>
</div>
<p>Just create a new instance of the OAuth class and call the SignRequest(&#8230;) method. Pass in the URI you wish to sign, your API key and secret and your access token. </p>
<p>This will transform:</p>
<p><a href="https://api.dropbox.com/1/account/info" target="_blank">https://api.dropbox.com/1/account/info</a></p>
<p>into something like this:</p>
<p><a href="https://api.dropbox.com/1/account/info?oauth_consumer_key=YourAPIKey&amp;oauth_token=YourToken&amp;oauth_nonce=6880853&amp;oauth_timestamp=1326020204&amp;oauth_signature_method=HMAC-SHA1&amp;oauth_version=1.0&amp;oauth_signature=9ukNkB/FZx3gHTT5TWP0hIkNe9z=" target="_blank">https://api.dropbox.com/1/account/info?oauth_consumer_key=YourAPIKey&amp;oauth_token=YourToken&amp;oauth_nonce=6880853&amp; oauth_timestamp=1326020204&amp;oauth_signature_method=HMAC-SHA1&amp;oauth_version=1.0&amp;oauth_signature=9ukNkB/FZx3gHTT5TWP0hIkNe9z=</a></p>
<p>The GetAccountInfo() method does this by calling the GetResponse(&#8230;) method. This method signs the request, sends it and returns the response.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">string</span> GetResponse(Uri uri)
{
    <span class="kwrd">var</span> oauth = <span class="kwrd">new</span> OAuth();
    <span class="kwrd">var</span> requestUri = oauth.SignRequest(
        uri, _consumerKey, _consumerSecret, _accessToken);
    <span class="kwrd">var</span> request = (HttpWebRequest) WebRequest.Create(requestUri);
    request.Method = WebRequestMethods.Http.Get;
    <span class="kwrd">var</span> response = request.GetResponse();
    <span class="kwrd">var</span> reader = <span class="kwrd">new</span> StreamReader(response.GetResponseStream());
    <span class="kwrd">return</span> reader.ReadToEnd();
}</pre>
</div>
<p>The Dropbox REST API returns it responses in JSON format. Here&#8217;s an example response containing account information:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
{
    "referral_link": "https://www.dropbox.com/referrals/r1a2n3d4m5s6t7",
    "display_name": "John P. User",
    "uid": 12345678,
    "country": "US",
    "quota_info": {
        "shared": 253738410565,
        "quota": 107374182400000,
        "normal": 680031877871
    },
    "email": "john@example.com"
}</pre>
</div>
<p>It contains some general information about the user (id, name, e-mail address&#8230;) and his allocated quota. Using the <a href="http://james.newtonking.com/projects/json-net.aspx" target="_blank">Json.NET library</a> we can easily deserialize this data into a .NET object. Let&#8217;s create a simple Account class into which we can deserialize this data.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> Account
{
    [JsonProperty(PropertyName = <span class="str">"uid"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> Id { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"referral_link"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> ReferralLink { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"display_name"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> DisplayName { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"email"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Email { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"country"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Country { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"quota_info"</span>)]
    <span class="kwrd">public</span> Quota Quota { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }
}</pre>
</div>
<p>The Quota type is equally simple.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> Quota
{
    [JsonProperty(PropertyName = <span class="str">"quota"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">long</span> Total { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"shared"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">long</span> Shared { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"normal"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">long</span> Normal { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }
}</pre>
</div>
<p>Don&#8217;t forget to install <a href="http://www.nuget.org/" target="_blank">NuGet</a> and to download the <a href="http://james.newtonking.com/projects/json-net.aspx" target="_blank">Json.NET library</a>.</p>
<p>The last line of code of the GetAccountInfo() method deserializes the JSON data by calling the ParseJson(&#8230;) method;</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">static</span> T ParseJson&lt;T&gt;(<span class="kwrd">string</span> json) where T : <span class="kwrd">class</span>, <span class="kwrd">new</span>()
{
    <span class="kwrd">var</span> jobject = JObject.Parse(json);
    <span class="kwrd">return</span> JsonConvert.DeserializeObject&lt;T&gt;(jobject.ToString());
}</pre>
</div>
<p>Just parse the JSON data and use the JsonConvert type to deserialize it into the type specified by the generic T parameter. As long as the type specified by T has been decorated with the correct Json.NET attributes it will deserialize without a problem.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="metadata" name="metadata"></a><strong>Metadata</strong></p>
<p>By now you&#8217;ve seen how to retrieve the account information. It&#8217;s consists out of 3 steps, namely:</p>
<ol>
<li>Compose the URI for the request</li>
<li>Sign and send the request</li>
<li>Parse the response (JSON) into a .NET object</li>
</ol>
<p>Most (if not all) of the Dropbox API requests can be dealt with in the same fashion. For instance, retrieving a list of files/folders that are stored in our Dropbox can be done in the same way.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> api = <span class="kwrd">new</span> DropboxApi(ConsumerKey, ConsumerSecret, accessToken);
<span class="kwrd">var</span> publicFolder = api.GetFiles(<span class="str">"dropbox"</span>, <span class="str">"Public"</span>);
<span class="kwrd">foreach</span> (<span class="kwrd">var</span> file <span class="kwrd">in</span> publicFolder.Contents)
{
    Console.WriteLine(file.Path);
}</pre>
</div>
<p>Here I retrieve a list of files/folders that are stored in my public Dropbox folder. The first parameter specified the root. Valid values are sandbox and dropbox. The second parameter specifies the path of the file or folder relative to the root.</p>
<p>Retrieving a list of files/folders supports many more parameters, but to keep things simple I&#8217;ve chosen to only support these two parameters. For a complete list check out the Dropbox REST API documentation:</p>
<p><a href="https://www.dropbox.com/developers/reference/api#metadata" target="_blank">https://www.dropbox.com/developers/reference/api#metadata</a></p>
<p>Apart from the URI and the return value (T) the GetFiles(&#8230;) methods looks identical to the GetAccountInfo() method.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> File GetFiles(<span class="kwrd">string</span> root, <span class="kwrd">string</span> path)
{
    <span class="kwrd">var</span> uri = <span class="kwrd">new</span> Uri(<span class="kwrd">new</span> Uri(DropboxRestApi.BaseUri),
        String.Format(<span class="str">"metadata/{0}/{1}"</span>, root, path));
    <span class="kwrd">var</span> json = GetResponse(uri);
    <span class="kwrd">return</span> ParseJson&lt;File&gt;(json);
}</pre>
</div>
<p>The URI is composed, then the request is signed and send. Last, but not least the response (JSON) is parsed and converted to a .NET object of the type File.</p>
<p>The following listing contains a small part of the File type. It contains the metadata for a file or folder at a given path. If it is a directory (IsDirectory property) then the metadata will also include a listing of metadata for the folder&#8217;s contents (Contents property).</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> File
{
    [JsonProperty(PropertyName = <span class="str">"size"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Size { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"rev"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Revision { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"is_dir"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">bool</span> IsDirectory { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"root"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Root { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"path"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Path { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"contents"</span>)]
    <span class="kwrd">public</span> IEnumerable&lt;File&gt; Contents { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    <span class="rem">//...</span>
}</pre>
</div>
<p>Example output:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/output.png"><img src="http://cgeers.files.wordpress.com/2012/01/output.png?w=480&#038;h=242" alt="File/Folder Metadata" title="File/Folder Metadata" width="480" height="242" class="aligncenter size-full wp-image-3812" /></a></p>
<p>Retrieving metadata works in exactly the same way as retrieving account information. With this code you are now armed to implement other Dropbox API requests. In the next part of this series I&#8217;ll explore some other requests concerning file operations (create, move and delete a folder). </p>
<p>Check out the Dropbox REST API documentation if you want to explore it further.</p>
<p><a href="https://www.dropbox.com/developers/reference/api" target="_blank">https://www.dropbox.com/developers/reference/api</a></p>
<p>You can download the source code accompanying this article from the <a href="http://cgeers.com/download/" target="_blank">download page</a>. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/dropbox/'>Dropbox</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3757/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3757&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/01/08/dropbox-rest-api-part-2-api-requests/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/logo1.png" medium="image">
			<media:title type="html">DropBox Logo</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/output.png" medium="image">
			<media:title type="html">File/Folder Metadata</media:title>
		</media:content>
	</item>
		<item>
		<title>Dropbox REST API Part 1: Authentication</title>
		<link>http://cgeers.com/2011/12/29/dropbox-rest-api-part-1-authentication/</link>
		<comments>http://cgeers.com/2011/12/29/dropbox-rest-api-part-1-authentication/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 08:47:17 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Dropbox]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[OAuth]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3681</guid>
		<description><![CDATA[Introduction I&#8217;ve been using Dropbox for about 6 months now. Before that I relied on Google Documents to share my files between the computers I use. Of course I had to login first and then I had to download them. Kind of a drag, certainly with big files. With Dropbox that&#8217;s a thing of the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3681&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2011/12/logo1.png"><img src="http://cgeers.files.wordpress.com/2011/12/logo1.png?w=480" alt="DropBox Logo" title="DropBox Logo"   class="alignright size-full wp-image-3688" /></a></p>
<p>I&#8217;ve been using Dropbox for about 6 months now. Before that I relied on Google Documents to share my files between the computers I use. Of course I had to login first and then I had to download them. Kind of a drag, certainly with big files. </p>
<p>With Dropbox that&#8217;s a thing of the past. Just install the client software and it will synchronize all of your files automatically. They are neatly downloaded into a local Dropbox folder on each of your computers. And only the parts of the file that actually changed are transferred, greatly reducing the download time.</p>
<p>Another neat feature is that other applications can use your Dropbox folder to store their data. For instance, I use a password manager (<a href="https://agilebits.com/onepassword" target="_blank">AgileBit&#8217;s 1Password</a>) to securely save my login accounts. If I create a new account for a site on my laptop, then when I start my desktop it will automatically be known there once Dropbox has synched 1Password&#8217;s files (which is nearly instantanously).</p>
<p>This is made possible thanks to the <a href="https://www.dropbox.com/developers/reference/api" target="_blank">Dropbox REST API</a>. Let&#8217;s find out how we can use it&#8230;</p>
<p><span id="more-3681"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#myapps">My Apps</a></li>
<li><a href="#requesttoken">Request Token</a></li>
<li><a href="#authorize">Authorize</a></li>
<li><a href="#accesstoken">Access Token</a></li>
</ul>
<p><a title="myapps" name="myapps"></a><strong>My Apps</strong></p>
<p>Before you can start, you first need to register your application with Dropbox. To do so, please follow these steps:</p>
<ul>
<li>Login to Dropbox</li>
<li>Click on the link &#8220;<a href="https://www.dropbox.com/developers" target="_blank">Developers</a>&#8221; which is displayed on the bottom (center) of the page</li>
<li>Click on the link &#8220;<a href="https://www.dropbox.com/developers/apps" target="_blank">My Apps</a>&#8221; displayed in the menu on the left side</li>
<li>Now click on the button &#8220;Create an App&#8221;</li>
</ul>
<p><a href="http://cgeers.files.wordpress.com/2011/12/dropbox1.png"><img src="http://cgeers.files.wordpress.com/2011/12/dropbox1.png?w=480" alt="Create an App" title="Create an App"   class="aligncenter size-full wp-image-3700" /></a></p>
<p>Choose a unique name for your application and select the appropriate access rights. You can lock your application in its own folder or you can grant it access to your entire Dropbox folder. Usually users don&#8217;t want to grant third-party applications access to their entire Dropbox folder so it&#8217;s best to choose the &#8220;App folder&#8221; option. However, since this is a demo I&#8217;ve choosen the &#8220;Full Dropbox&#8221; option. It will come in handy for later parts of this series.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/dropbox2.png"><img src="http://cgeers.files.wordpress.com/2011/12/dropbox2.png?w=480&#038;h=347" alt="Dropbox Application" title="Dropbox Application" width="480" height="347" class="aligncenter size-full wp-image-3702" /></a></p>
<p>Click Create to register your application. After you have created an application you&#8217;ll get two tokens, namely an app key and a secret. Here are mine (don&#8217;t worry&#8230;I&#8217;ve already deleted my app when you are reading this).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/dropbox3.png"><img src="http://cgeers.files.wordpress.com/2011/12/dropbox3.png?w=480&#038;h=179" alt="App Key and Secret" title="App Key and Secret" width="480" height="179" class="aligncenter size-full wp-image-3704" /></a></p>
<p>Keep those tokens nearby. You&#8217;ll need them when signing in to Dropbox.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="requesttoken" name="requesttoken"></a><strong>Request Token</strong></p>
<p>Dropbox offers several <a href="https://www.dropbox.com/developers/reference/sdk" target="_blank">SDKs</a> for their REST API. Android, iOS, Java, Python and Ruby are all supported. Unfortunately there is no SDK for the .NET framework. Odd if you ask me, but not that big of an issue. There are some third party SDKs available, but let&#8217;s do the basic plumbling ourselves. A bit more work to do, but we&#8217;ll get there.</p>
<p>Before you can use the REST API you need to go through the authentication process. Dropbox requires that all requests are done over SSL and it uses <a href="http://oauth.net/" target="_blank">OAuth</a> to authenticate all of the API requests.</p>
<p>After you have completed the authentication process you&#8217;ll have an access token and access token secret. You can then use the access token for all the other requests. The authentication process consists out of three steps:</p>
<ol>
<li><strong>Request token</strong>: Obtain an OAuth request token to be used for the rest of the authentication process.</li>
<li><strong>Authorize</strong>: The user must grant your application access to their Dropbox.</li>
<li><strong>Access token</strong>: Once your application is authorized you can acquire an access token.</li>
</ol>
<p>Let&#8217;s start by obtaining an OAuth request token. Start Visual Studio 2010 and create a new blank solution called Dropbox. Next add a console application to the solution titled ConsoleApplication. Coming up with original names, it&#8217;s important.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/dropbox4.png"><img src="http://cgeers.files.wordpress.com/2011/12/dropbox4.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3717" /></a></p>
<p>To quickly support OAuth I&#8217;ve downloaded a small, usefull library called <a href="http://code.google.com/p/oauth/" target="_blank">OAuth</a>. You can download it here:</p>
<p><a href="http://code.google.com/p/oauth/" target="_blank">http://code.google.com/p/oauth/</a></p>
<p>Download the C# version, it&#8217;s a single file (OAuthBase.cs) and add it to the console application project.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/dropbox5.png"><img src="http://cgeers.files.wordpress.com/2011/12/dropbox5.png?w=480" alt="OAuthBase.cs" title="OAuthBase.cs"   class="aligncenter size-full wp-image-3718" /></a></p>
<p>To request an OAuth request token you need to send a request to <a href="https://api.dropbox.com/1/oauth/request_token" target="_blank">https://api.dropbox.com/1/oauth/request_token</a>. You need to include the following parameters:</p>
<ul>
<li><strong>oauth_consumer_key</strong>: Your API key</li>
<li><strong>oauth_nonce</strong>: A number used only once</li>
<li><strong>oauth_timestamp</strong>: Timestamp of the request</li>
<li><strong>oauth_signature_method</strong>: Signature method</li>
<li><strong>oauth_signature</strong>: Signature of the request. A hash to sign the request based on a couple of parameters.</li>
<li><strong>oauth_version</strong>: OAuth version used</li>
</ul>
<p>There are no Dropbox specific parameters required for this request. Using the OAuth library you downloaded earlier this is pretty straightforward. First let&#8217;s generate a signature for the request.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> consumerKey = <span class="str">"your api key"</span>;
<span class="kwrd">var</span> consumerSecret = <span class="str">"your api secret"</span>;

<span class="kwrd">var</span> uri = <span class="kwrd">new</span> Uri(<span class="str">"https://api.dropbox.com/1/oauth/request_token"</span>);

<span class="rem">// Generate a signature</span>
OAuthBase oAuth = <span class="kwrd">new</span> OAuthBase();
<span class="kwrd">string</span> nonce = oAuth.GenerateNonce();
<span class="kwrd">string</span> timeStamp = oAuth.GenerateTimeStamp();
<span class="kwrd">string</span> parameters;
<span class="kwrd">string</span> normalizedUrl;
<span class="kwrd">string</span> signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret,
    String.Empty, String.Empty, <span class="str">"GET"</span>, timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
    <span class="kwrd">out</span> normalizedUrl, <span class="kwrd">out</span> parameters);

signature = HttpUtility.UrlEncode(signature);</pre>
</div>
<p>You&#8217;ll wind up with a weird looking string like zwct8VZ469%2bLpmi9C8%2fVpghpk7w%3d. Now let&#8217;s issue the actual request. </p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
StringBuilder requestUri = <span class="kwrd">new</span> StringBuilder(uri.ToString());
requestUri.AppendFormat(<span class="str">"?oauth_consumer_key={0}&amp;"</span>, consumerKey);
requestUri.AppendFormat(<span class="str">"oauth_nonce={0}&amp;"</span>, nonce);
requestUri.AppendFormat(<span class="str">"oauth_timestamp={0}&amp;"</span>, timeStamp);
requestUri.AppendFormat(<span class="str">"oauth_signature_method={0}&amp;"</span>, <span class="str">"HMAC-SHA1"</span>);
requestUri.AppendFormat(<span class="str">"oauth_version={0}&amp;"</span>, <span class="str">"1.0"</span>);
requestUri.AppendFormat(<span class="str">"oauth_signature={0}"</span>, signature);

<span class="kwrd">var</span> request = (HttpWebRequest) WebRequest.Create(<span class="kwrd">new</span> Uri(requestUri.ToString()));
request.Method = WebRequestMethods.Http.Get;

<span class="kwrd">var</span> response = request.GetResponse();</pre>
</div>
<p>Here we compose the URL including all the parameters (query string) and then we issue the request. Your URL should resemble the following pattern:</p>
<p><a href="https://api.dropbox.com/1/oauth/request_token?oauth_consumer_key=your api key&amp;oauth_nonce=9328214&amp;oauth_timestamp=1325081302&amp;oauth_signature_method=HMAC-SHA1&amp;oauth_version=1.0&amp;oauth_signature=OskIFg2iOhcVJ2qHGDN6VDXxUik%3d" target="_blank">https://api.dropbox.com/1/oauth/request_token?oauth_consumer_key=your api key&amp;oauth_nonce=9328214&amp;oauth_timestamp=1325081302&amp;oauth_signature_method=HMAC-SHA1&amp;oauth_version=1.0&amp;oauth_signature=OskIFg2iOhcVJ2qHGDN6VDXxUik%3d</a></p>
<p>Just make sure to use your own API (or consumer) key and secret. Let&#8217;s parse the response which includes a request token and request token secret. For instance:</p>
<p><strong>oauth_token_secret=bdifrgl4si3if8w&amp;oauth_token=cny4z2vkqpbqd6k</strong></p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> response = request.GetResponse();

<span class="kwrd">var</span> queryString = <span class="kwrd">new</span> StreamReader(response.GetResponseStream()).ReadToEnd();

<span class="kwrd">var</span> parts = queryString.Split(<span class="str">'&amp;'</span>);
<span class="kwrd">var</span> token = parts[1].Substring(parts[1].IndexOf(<span class="str">'='</span>) + 1);
<span class="kwrd">var</span> tokenSecret = parts[0].Substring(parts[0].IndexOf(<span class="str">'='</span>) + 1);</pre>
</div>
<p>Voila, using this crude &#8220;Hello, World&#8221;-ish code you can now complete step 1 of the authentication process. You now have a token and token secret which you can use to complete the authentication process.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="authorize" name="authorize"></a><strong>Authorize</strong></p>
<p>Once you have an OAuth request token and secret it&#8217;s very simple to authorize your application. You only need to send a request to:</p>
<p><a href="https://www.dropbox.com/1/oauth/authorize" target="_blank">https://www.dropbox.com/1/oauth/authorize</a></p>
<p>This request only requires two parameters, namely the request token and secret you obtained earlier.</p>
<ul>
<li><strong>oauth_token</strong>: the OAuth request token</li>
<li><strong>oauth_token_secret</strong>: the OAuth token secret</li>
</ul>
<p>Resulting in a URL which looks like this:</p>
<p><a href="https://www.dropbox.com/1/oauth/authorize?oauth_token_secret=yoursecret&amp;oauth_token=yourtoken" target="_blank">https://www.dropbox.com/1/oauth/authorize?oauth_token_secret=yoursecret&amp;oauth_token=yourtoken</a></p>
<p>Let&#8217;s start the authorization process:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> queryString = String.Format(<span class="str">"oauth_token_secret={0}&amp;oauth_token={1}"</span>, secret, token);
<span class="kwrd">var</span> authorizeUrl = <span class="str">"https://www.dropbox.com/1/oauth/authorize?"</span> + queryString;
Process.Start(authorizeUrl);</pre>
</div>
<p>This will open a new browser window. You&#8217;ll be asked to login to Dropbox. Once you have done so you can choose if you want to grant (authorize) your first Dropbox application access to your Dropbox folder.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/dropbox6.png"><img src="http://cgeers.files.wordpress.com/2011/12/dropbox6.png?w=480&#038;h=288" alt="Authorize Dropbox Application" title="Authorize Dropbox Application" width="480" height="288" class="aligncenter size-full wp-image-3735" /></a></p>
<p>Once you click on Allow the application will be added to the list of applications which can access your Dropbox. You can view this list in the My Apps section in your account. You can always revoke the access at a later time.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/dropbox71.png"><img src="http://cgeers.files.wordpress.com/2011/12/dropbox71.png?w=480&#038;h=52" alt="My Apps" title="My Apps" width="480" height="52" class="aligncenter size-full wp-image-3739" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="accesstoken" name="accesstoken"></a><strong>Access Token</strong></p>
<p>By now you have an OAuth access token and you have authorized your application so that it can access your Dropbox folder. Time to finish the authentication process. After the authorization step is complete you can acquire an access token. </p>
<p>This access token is needed to authenticate all the API requests. Once you have obtained such a token you can store it and reuse it later. You don&#8217;t need to go through the authentication process again. Just make sure to store the token securely, because it is required for all access to the user&#8217;s Dropbox folder.</p>
<p>Acquiring an access token is very similar to the first step. You must send a request to <a href="https://api.dropbox.com/1/oauth/access_token" target="_blank">https://api.dropbox.com/1/oauth/access_token</a>, including the following parameters:</p>
<ul>
<li><strong>oauth_consumer_key</strong>: Your API key</li>
<li><strong>oauth_token</strong>: The OAuth token you obtained in step  1</li>
<li><strong>oauth_nonce</strong>: A number used only once</li>
<li><strong>oauth_timestamp</strong>: Timestamp of the request</li>
<li><strong>oauth_signature_method</strong>: Signature method</li>
<li><strong>oauth_signature</strong>: Signature of the request. A hash to sign the request based on a couple of parameters.</li>
<li><strong>oauth_version</strong>: OAuth version used</li>
</ul>
<p>First let&#8217;s generate a signature for this request.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> consumerKey = <span class="str">"your api key"</span>;
<span class="kwrd">var</span> uri = <span class="str">"https://api.dropbox.com/1/oauth/access_token"</span>;

OAuthBase oAuth = <span class="kwrd">new</span> OAuthBase();

<span class="kwrd">var</span> nonce = oAuth.GenerateNonce();
<span class="kwrd">var</span> timeStamp = oAuth.GenerateTimeStamp();
<span class="kwrd">string</span> parameters;
<span class="kwrd">string</span> normalizedUrl;
<span class="kwrd">var</span> signature = oAuth.GenerateSignature(<span class="kwrd">new</span> Uri(uri), consumerKey, consumerSecret,
    oauthToken.Token, oauthToken.Secret, <span class="str">"GET"</span>, timeStamp, nonce,
    OAuthBase.SignatureTypes.HMACSHA1, <span class="kwrd">out</span> normalizedUrl, <span class="kwrd">out</span> parameters);

signature = HttpUtility.UrlEncode(signature);</pre>
</div>
<p>Now you can send the request.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> requestUri = <span class="kwrd">new</span> StringBuilder(uri);
requestUri.AppendFormat(<span class="str">"?oauth_consumer_key={0}&amp;"</span>, consumerKey);
requestUri.AppendFormat(<span class="str">"oauth_token={0}&amp;"</span>, oauthToken.Token);
requestUri.AppendFormat(<span class="str">"oauth_nonce={0}&amp;"</span>, nonce);
requestUri.AppendFormat(<span class="str">"oauth_timestamp={0}&amp;"</span>, timeStamp);
requestUri.AppendFormat(<span class="str">"oauth_signature_method={0}&amp;"</span>, <span class="str">"HMAC-SHA1"</span>);
requestUri.AppendFormat(<span class="str">"oauth_version={0}&amp;"</span>, <span class="str">"1.0"</span>);
requestUri.AppendFormat(<span class="str">"oauth_signature={0}"</span>, signature);

<span class="kwrd">var</span> request = (HttpWebRequest) WebRequest.Create(requestUri.ToString());
request.Method = WebRequestMethods.Http.Get;</pre>
</div>
<p>Parsing the response will give you a return value which resembles this:</p>
<p>oauth_token_secret=95grkd9na7hm&amp;oauth_token=ccl4li5n1q9b</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> response = request.GetResponse();
<span class="kwrd">var</span> reader = <span class="kwrd">new</span> StreamReader(response.GetResponseStream());
<span class="kwrd">var</span> accessToken = reader.ReadToEnd();

<span class="kwrd">var</span> parts = accessToken.Split(<span class="str">'&amp;'</span>);
<span class="kwrd">var</span> token = parts[1].Substring(parts[1].IndexOf(<span class="str">'='</span>) + 1);
<span class="kwrd">var</span> secret = parts[0].Substring(parts[0].IndexOf(<span class="str">'='</span>) + 1);</pre>
</div>
<p>You now have an access token and corresponding access token secret. The authentication process is now complete and you can use the access token and secret to sign requests for the main API calls.</p>
<p><strong>Remark</strong>: Make sure to leave some time between step 2 and 3, so that the authorization step can succeed. You need to redirect the user to Dropbox so that they can authorize your application. You need to wait until the user has completed this step.</p>
<p>In part 2 of this series I&#8217;ll show you some examples of how you can use the acess token and secret to access the main Dropbox REST API. </p>
<p>I&#8217;ll try to get the next part online as soon as possible. You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/dropbox/'>Dropbox</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3681/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3681&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/12/29/dropbox-rest-api-part-1-authentication/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/logo1.png" medium="image">
			<media:title type="html">DropBox Logo</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/dropbox1.png" medium="image">
			<media:title type="html">Create an App</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/dropbox2.png" medium="image">
			<media:title type="html">Dropbox Application</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/dropbox3.png" medium="image">
			<media:title type="html">App Key and Secret</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/dropbox4.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/dropbox5.png" medium="image">
			<media:title type="html">OAuthBase.cs</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/dropbox6.png" medium="image">
			<media:title type="html">Authorize Dropbox Application</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/dropbox71.png" medium="image">
			<media:title type="html">My Apps</media:title>
		</media:content>
	</item>
		<item>
		<title>Programming Windows Phone 7.5 Part 3: Stack Exchange API</title>
		<link>http://cgeers.com/2011/12/03/programming-windows-phone-7-5-part-3-stack-exchange-api/</link>
		<comments>http://cgeers.com/2011/12/03/programming-windows-phone-7-5-part-3-stack-exchange-api/#comments</comments>
		<pubDate>Sat, 03 Dec 2011 16:30:41 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[Mango]]></category>
		<category><![CDATA[Stack Exchange]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3600</guid>
		<description><![CDATA[Introduction Let&#8217;s finish up the Windows Phone programming series I started in October. The first part &#8220;Getting Started&#8221; guides you through the steps you need to follow in order to get up and running with Windows 7.5 (Mango) development. The second part is a quick guide on how you can easily create your own icons [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3600&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2011/10/windows-phone-logo3.jpg?w=480" alt="Windows Phone 7.5 Logo" title="Windows Phone 7.5 Logo"   class="alignright size-full wp-image-3455" /></p>
<p>Let&#8217;s finish up the Windows Phone programming series I started in October. The first part &#8220;<a href="http://cgeers.com/2011/10/16/programming-windows-phone-7-5-part-1-getting-started/" target="_blank">Getting Started</a>&#8221; guides you through the steps you need to follow in order to get up and running with Windows 7.5 (Mango) development. The <a href="http://cgeers.com/2011/10/30/programming-windows-phone-7-5-part-2-icons/" target="_blank">second part</a> is a quick guide on how you can easily create your own icons to brand your application. Please read them first if you haven&#8217;t done so yet.</p>
<p>It&#8217;s about time we actually made the application do something useful. For this I choose to use the small wrapper for the <a href="http://cgeers.com/2011/10/02/stack-exchange-api/" target="_blank">Stack Exchange API</a> I made some time ago. It would be nice if I had a small application which allows me to check my StackOverflow profile. </p>
<p>You can download the code for my StackExchange API wrapper on the <a href="http://cgeers.com/download/" target="_blank">download page</a> (2011: Article #58). As you&#8217;ll notice there are some things we&#8217;ll need to change in the existing code to make it work on a Windows Phone device.</p>
<p>Let&#8217;s get started&#8230;</p>
<p><span id="more-3600"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#application">The Application</a></li>
<li><a href="#solution">The Solution</a></li>
<li><a href="#api">Stack Exchange API</a></li>
<li><a href="#refactoring">Refactoring</a></li>
<li><a href="#ui">User Interface</a></li>
</ul>
<p><a title="application" name="application"></a><strong>The Application</strong></p>
<p>Let&#8217;s have a look at the application we are going to build. It&#8217;s a simple application which only consists out of one page (MainPage.xaml). This page contains a <a href="http://msdn.microsoft.com/en-us/library/ff941098(v=VS.92).aspx" target="_blank">pivot control</a> which is composed out of two pages, namely:</p>
<ul>
<li><strong>Profile page</strong>: Shows your profile (name, reputation, badges&#8230;etc.)</li>
<li><strong>Reputation page</strong>: Lists your reputation updates for the last X days</li>
</ul>
<p>A picture is worth a thousand words, so take a look at the following screenshots.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/application.png"><img src="http://cgeers.files.wordpress.com/2011/12/application.png?w=480&#038;h=400" alt="StackOverflow Application" title="StackOverflow Application" width="480" height="400" class="aligncenter size-full wp-image-3613" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="solution" name="solution"></a><strong>The Solution</strong></p>
<p>Let&#8217;s start Visual Studio 2010 and create a new blank solution called StackOverflow. Next add a new project to it using the Windows Phone Application project template and call it StackOverflow.Phone.UI.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/application2.png"><img src="http://cgeers.files.wordpress.com/2011/12/application2.png?w=480&#038;h=331" alt="New Project" title="New Project" width="480" height="331" class="aligncenter size-full wp-image-3617" /></a></p>
<p>Make sure you target the Windows Phone 7.1 OS for all the projects in this solution. Visual Studio will ask this automatically when adding a new project.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/application3.png"><img src="http://cgeers.files.wordpress.com/2011/12/application3.png?w=480&#038;h=226" alt="Windows Phone 7.1 OS" title="Windows Phone 7.1 OS" width="480" height="226" class="aligncenter size-full wp-image-3619" /></a></p>
<p>Now you need to add a new Windows Phone Class Library named StackExchange.Api to the project. By now, your solution should resemble the following structure:</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/solution-explorer.png"><img src="http://cgeers.files.wordpress.com/2011/12/solution-explorer.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3621" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="api" name="api"></a><strong>Stack Exchange API</strong></p>
<p>My small Stack Exchange API wrapper allows you to retrieve this data using just a few lines of code. We have to refactor it a bit to make it compatible with <a href="http://www.microsoft.com/silverlight/" target="_blank">Silverlight</a> for Windows Phone before we can use it.</p>
<p>Download the code (article #58: Stack Exchange API) from the <a href="http://cgeers.com/download/" target="_blank">download page</a>. Extract the archive and copy / paste the following files into the directory of the StackOverflow.Api class library.</p>
<ul>
<li>BadgeCount.cs</li>
<li>ExtensionMethods.cs</li>
<li>ReputationChange.cs</li>
<li>StackExchangeApi.cs</li>
<li>UnixDateTimeConverter.cs</li>
<li>User.cs</li>
<li>WrapperObjectAttribute.cs</li>
</ul>
<p>Afterwards include these files in the StackOverflow.Api project.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/se.png"><img src="http://cgeers.files.wordpress.com/2011/12/se.png?w=480" alt="Stack Exchange API Files" title="Stack Exchange API Files"   class="aligncenter size-full wp-image-3625" /></a></p>
<p>Next you need to add the Json.NET and SharpCompress NuGet packages to this class library. </p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/packages1.png"><img src="http://cgeers.files.wordpress.com/2011/12/packages1.png?w=480" alt="NuGet Packages" title="NuGet Packages"   class="aligncenter size-full wp-image-3630" /></a></p>
<p>Download and install the <a href="http://nuget.org/" target="_blank">NuGet extension</a> first if you don&#8217;t have it already. You need the Json.NET package because the Stack Exchange API wrapper uses it to serialize / deserialize the data and the SharpCompress provides GZip support for Silverlight. There is no native GZip (GZipStream) support in Silverlight.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="refactoring" name="refactoring"></a><strong>Refactoring</strong></p>
<p>If you build the StackOverflow.Api project the compiler will throw some errors. Let&#8217;s fix them. By adding a reference to the SharpCompress assemblies you already fixed the missing GZipStream support. Just make sure you include the necessary namespaces in the StackExchangeApi.cs code file.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">using</span> SharpCompress.Compressor;
<span class="kwrd">using</span> SharpCompress.Compressor.Deflate;</pre>
</div>
<p>Also remove the reference to the System.IO.Compression namespace.</p>
<p>The major issue with the current implementation is that everything is done synchronously such as retrieval of a user&#8217;s profile and his reputation changes. Silverlight requires you to do a lot things asynchronously. Retrieving a user&#8217;s profile in the following manner will not work anymore:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var api = <span class="kwrd">new</span> StackExchangeApi(<span class="str">"your api key"</span>);
var user = api.GetUser(893099);</pre>
</div>
<p>Let&#8217;s fix it. Open the StackExchangeApi file and add the following delegate to the StackExchangeApi class.  </p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">void</span> StackExchangeApiCallback&lt;T&gt;(T data) <span class="kwrd">where</span> T : <span class="kwrd">class</span>, <span class="kwrd">new</span>();</pre>
</div>
<p>Now change the signature of the GetUser(&#8230;) method as follows:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">void</span> GetUser(<span class="kwrd">int</span> userId, StackExchangeApiCallback&lt;User&gt; callback)
{
    GetStackExchangeObject(String.Format(<span class="str">"/users/{0}"</span>, userId), callback);
}</pre>
</div>
<p>When retrieving a user&#8217;s profile you&#8217;ll notice that we no longer expect the method to return a value. Instead we pass it a callback (our StackExchangeApiCallback delegate). This callback will be triggered when the user&#8217;s profile has been retrieved. We won&#8217;t wait for it anymore. We expect to be informed of this event. </p>
<p>The GetUser(&#8230;) method passes the callback to the refactored GetStackExchangeObject(&#8230;) method. Let&#8217;s see how this method has been refactored to support asynchronous operations.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">void</span> GetStackExchangeObject&lt;T&gt;(<span class="kwrd">string</span> path, StackExchangeApiCallback&lt;T&gt; callback)
    <span class="kwrd">where</span> T : <span class="kwrd">class</span>, <span class="kwrd">new</span>()
{
    var requestUri = ComposeUri(path);
    GetSingleObject(requestUri, callback);
}

<span class="kwrd">private</span> <span class="kwrd">void</span> GetSingleObject&lt;T&gt;(<span class="kwrd">string</span> requestUri, StackExchangeApiCallback&lt;T&gt; callback)
    <span class="kwrd">where</span> T : <span class="kwrd">class</span>, <span class="kwrd">new</span>()
{
    var request = (HttpWebRequest) WebRequest.Create(requestUri);
    request.Method = <span class="str">"GET"</span>;
    request.Accept = <span class="str">"application/json"</span>;

    request.BeginGetResponse(
        ar =&gt;
            {
                var response = (HttpWebResponse)request.EndGetResponse(ar);
                var json = ExtractJsonResponse(response);
                var data = ParseJson&lt;T&gt;(json).FirstOrDefault();
                callback(data);
            },
        <span class="kwrd">null</span>);
}</pre>
</div>
<p>First the URL to the Stack Exchange resource is determined and then the GetSingleObject(&#8230;) method retrieves the data asynchronously. When the data arrives it is parsed and deserialized and our callback is triggered.</p>
<p>Last but not least remove or comment the private GetResponse(&#8230;) method. It is no longer needed.</p>
<p>You can now retrieve a user&#8217;s profile in the following manner:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">void</span> UserRetrieved(User user)
{
    <span class="rem">//...</span>
}

var api = <span class="kwrd">new</span> StackExchangeApi(<span class="str">"your api key"</span>);
var callback = <span class="kwrd">new</span> StackExchangeApi.StackExchangeApiCallback&lt;User&gt;(UserRetrieved);
api.GetUser(893099, callback);</pre>
</div>
<p>When the user&#8217;s profile has been retrieved the UserRetrieved(&#8230;) callback will be triggered. It retrieves an instance of the User type which contains the user&#8217;s profile.</p>
<p>The same problem (sync Vs async) exists for retrieving a user&#8217;s reputation changes, but the solution is similar to the fix for retrieving a profile. I won&#8217;t list it here, just take a look at the source code accompanying this article. I also expanded the wrapper a little bit so that it returns a bit more data for the user&#8217;s profile, reputation&#8230;etc. You can start from the old code and refactor it or you can just download the finished code. Here I just showed how you can refactor it. Just repeat it for the reputation updates and it&#8217;s done.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="ui" name="ui"></a><strong>User Interface</strong></p>
<p>I&#8217;m not going to focus much on the actual user interface. As you can see in the screenshots above it&#8217;s a very simple interface. One page containing a pivot control which has two pages. One to display the user&#8217;s profile and another one to list his reputation updates. </p>
<p>The profile page contains a grid which lists the user&#8217;s name, reputation, views, age, badge count&#8230;etc. The reputation page contains a ListBox which lists the user&#8217;s reputation updates. Download the source and take a look at the XAML code if you want to explore it, but&#8217;s its really basic.</p>
<p>The application also contains an <a href="http://msdn.microsoft.com/en-us/library/ff431801(v=vs.92).aspx" target="_blank">ApplicationBar</a> which contains two icons. A refresh icon and a settings icon. I did not implement a settings page, I&#8217;ll leave that to you as an exercise. It&#8217;s just meant to be a simple settings page where you can enter your Stack Overflow user id. The sample code uses a hardcoded id. Feel free to improve on that and implement a settings page.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/12/application-bar.png"><img src="http://cgeers.files.wordpress.com/2011/12/application-bar.png?w=480" alt="Application Bar" title="Application Bar"   class="aligncenter size-full wp-image-3646" /></a></p>
<p>The code for the application is pretty simple. Just add a reference to the StackOverflow.Api library from the UI project. Just create an instance of the StackExchangeApi class.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> MainPage : PhoneApplicationPage
{
    <span class="kwrd">private</span> StackExchangeApi _api;

    <span class="rem">// Constructor</span>
    <span class="kwrd">public</span> MainPage()
    {
        InitializeComponent();

        <span class="kwrd">this</span>._api = <span class="kwrd">new</span> StackExchangeApi(<span class="str">"your api key"</span>);

        Loaded += MainPage_Loaded;
    }

    <span class="rem">//...</span>
}</pre>
</div>
<p>Afterwards it&#8217;s really simple to load the data. Just create a callback and call the GetUser(&#8230;) method.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">void</span> MainPage_Loaded(<span class="kwrd">object</span> sender, System.Windows.RoutedEventArgs e)
{
    var callback = <span class="kwrd">new</span> StackExchangeApi.StackExchangeApiCallback&lt;User&gt;(UserRetrieved);
    <span class="kwrd">this</span>._api.GetUser(893099, callback);

}

<span class="kwrd">void</span> UserRetrieved(User user)
{
    Dispatcher.BeginInvoke(() =&gt;
                                {
                                    DisplayName.Text = user.DisplayName;
                                    <span class="rem">// ...</span>
                                    BronzeBadges.Text = user.BadgeCounts.Bronze.ToString();
                                });
}</pre>
</div>
<p>Just make sure to access the controls on the UI thread, hence the Dispatcher.BeginInvoke(&#8230;) call.</p>
<p>That&#8217;s about all it takes to quickly create a sample Windows Phone demo application using the Stack Exchange API. If you want more information on how this API was use please read the <a href="http://cgeers.com/2011/10/02/stack-exchange-api/" target="_blank">Stack Exchange API</a> which I wrote a couple of months ago.</p>
<p>You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>, <a href='http://cgeers.com/category/programming/windows-phone/'>Windows Phone</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3600/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3600/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3600/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3600&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/12/03/programming-windows-phone-7-5-part-3-stack-exchange-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/windows-phone-logo3.jpg" medium="image">
			<media:title type="html">Windows Phone 7.5 Logo</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/application.png" medium="image">
			<media:title type="html">StackOverflow Application</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/application2.png" medium="image">
			<media:title type="html">New Project</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/application3.png" medium="image">
			<media:title type="html">Windows Phone 7.1 OS</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/solution-explorer.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/se.png" medium="image">
			<media:title type="html">Stack Exchange API Files</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/packages1.png" medium="image">
			<media:title type="html">NuGet Packages</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/12/application-bar.png" medium="image">
			<media:title type="html">Application Bar</media:title>
		</media:content>
	</item>
		<item>
		<title>Programming Windows Phone 7.5 Part 2: Icons</title>
		<link>http://cgeers.com/2011/10/30/programming-windows-phone-7-5-part-2-icons/</link>
		<comments>http://cgeers.com/2011/10/30/programming-windows-phone-7-5-part-2-icons/#comments</comments>
		<pubDate>Sun, 30 Oct 2011 18:20:44 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[Mango]]></category>
		<category><![CDATA[Stack Exchange]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3521</guid>
		<description><![CDATA[Introduction In the previous part of this series I mentioned that the next one would be about creating some icons for your Windows Phone application. Took me about two weeks to get around to it. Been busy, switched employers and am now working for a client in Brussels. Happened to lose my phone on the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3521&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2011/10/windows-phone-logo3.jpg?w=480" alt="Windows Phone 7.5 Logo" title="Windows Phone 7.5 Logo"   class="alignright size-full wp-image-3455" /></p>
<p>In the <a href="http://cgeers.com/2011/10/16/programming-windows-phone-7-5-part-1-getting-started/" target="_blank">previous part</a> of this series I mentioned that the next one would be about creating some icons for your Windows Phone application. </p>
<p>Took me about two weeks to get around to it. Been busy, switched employers and am now working for a client in Brussels. Happened to lose my phone on the train last Friday or it was stolen. I was in a Zombie-like state (it was early), so I don&#8217;t know. Remember putting it away, but when I did the 3 tap check [wallet - keys - phone] on the escalator it was gone &#8230; and so was my train by that time. I guess I won&#8217;t be deploying my apps any time soon. </p>
<p>Enough about me. Let&#8217;s create some icons. For a Windows Phone application you&#8217;ll need the following icons:</p>
<ol>
<li>Application Icon (62 x 62)</li>
<li>Application Tile Image (173 x 173)</li>
<li>Marketplace catalog icon (small) (99 x 99)</li>
<li>Marketplate catalog icon (large) (173 x 173)</li>
<li>Desktop application icon (200 x 200)</li>
</ol>
<p>Luckily we&#8217;ll be using the PNG format for all of them. Let&#8217;s get started.</p>
<p><span id="more-3521"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#preparation">Preparation</a></li>
<li><a href="#baselayer">Base Layer</a></li>
<li><a href="#placeholder">Icon Placeholder</a></li>
<li><a href="#icon">The Icon</a></li>
<li><a href="#slices">Slices</a></li>
<li><a href="#usage">Using The Icons</a></li>
</ul>
<p><a title="preparation" name="preparation"></a><strong>Preparation</strong></p>
<p>Since we are creating a small StackOverflow application it seems fitting to use their icon.</p>
<p><a href="http://stackoverflow.quickmediasolutions.com/images/stackoverflow.png" target="_blank"><img alt="StackOverflow" src="http://stackoverflow.quickmediasolutions.com/images/stackoverflow.png" title="StackOverflow" class="aligncenter" width="64" height="64" /></a></p>
<p>Hrm, it&#8217;s mostly gray and orange. That won&#8217;t display so nicely if you choose a conflicting theme color. For instance, here&#8217;s the icon with the Mango theme.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/mango.png"><img src="http://cgeers.files.wordpress.com/2011/10/mango.png?w=480" alt="Mango Theme" title="Mango Theme"   class="aligncenter size-full wp-image-3537" /></a></p>
<p>Urgh. Let&#8217;s make life easy and choose a color that works well with <del datetime="2011-10-30T14:08:52+00:00">most </del> all themes. Microsoft seems to prefer white, so let&#8217;s adjust our icon a bit. I used Photoshop CS2 for this purpose, but feel free to use any other graphics editing application. I just used what I know. </p>
<p>The easiest way in Photoshop, provided you have a good transparent image to work from is the following:</p>
<ol>
<li>Start Photoshop</li>
<li>Open the image</li>
<li>Select everything and copy it to the clipboard</li>
<li>Create a new Photoshop file (make sure the background is transparent)</li>
<li>Paste</li>
<li>Double click the layer in the layers palette to select everthing in the layer</li>
<li>Press the &#8216;d&#8217;-key to reset the fore -and background colors to black and white</li>
<li>Press CTRL+Backspace to fill the selection with white</li>
</ol>
<p>Voila, you now have a nice white Stackoverflow icon.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/photoshop.png"><img src="http://cgeers.files.wordpress.com/2011/10/photoshop.png?w=480" alt="Photoshopped Stackoverflow Icon" title="Photoshopped Stackoverflow Icon"   class="aligncenter size-full wp-image-3542" /></a></p>
<p>(Displayed here with a black background for contrast purposes.)</p>
<p>Go ahead and save the image as a PNG file. Make sure the background is transparent.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="baselayer" name="baselayer"></a><strong>Base Layer</strong></p>
<p>The Photoshop work is done. Time to move to another graphics editing application. Go ahead and download the 60-day trial of <a href="http://www.microsoft.com/expression/try-it/Default.aspx#PageTop" target="_blank">Expression Studio 4</a> if you don&#8217;t have it installed.</p>
<p>Once installed, start it up and create a new document (File &gt; New&#8230;) of 1024 x 1024 pixels. Sure the icon is smaller, but we&#8217;ll resize it later. It&#8217;s just handier to work with this way.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression1.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression1.png?w=480" alt="New Document" title="New Document"   class="aligncenter size-full wp-image-3545" /></a></p>
<p>Draw a rectangle anywhere on the surface.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression2.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression2.png?w=480" alt="Rectangle Tool" title="Rectangle Tool"   class="aligncenter size-full wp-image-3547" /></a></p>
<p>Then select a color from the Properties window in order to fill the rectangle. It doesn&#8217;t matter which color.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression3.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression3.png?w=480" alt="Appearance" title="Appearance"   class="aligncenter size-full wp-image-3548" /></a></p>
<p>Now select the Selection tool (V) and resize the rectangle so that it fills the entire surface (1024 x 1024 pixels). Afterwards select the layer from the Layers palette and click the padlock icon to lock it. No more further modifications can be made to the layer while its locked.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression5.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression5.png?w=480" alt="Lock Layer" title="Lock Layer"   class="aligncenter size-full wp-image-3551" /></a></p>
<p>Voila, you now have a 1024 x 1024 base layer. It&#8217;s almost like painting IRL.</p>
<p>In my case I ended up with a big red square.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression6.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression6.png?w=480" alt="Big Red Square" title="Big Red Square"   class="aligncenter size-full wp-image-3553" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="placeholder" name="placeholder"></a><strong>Icon Placeholder</strong></p>
<p>Create a new layer. Click the cogwheel symbol in the layers palette and choose the option &#8220;New Layer&#8221;.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression7.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression7.png?w=480" alt="New Layer" title="New Layer"   class="aligncenter size-full wp-image-3556" /></a></p>
<p>Draw a rectangle on the new layer and fill it with a color that contrasts well with the background layer. Once you&#8217;ve done this, you need to resize the rectangle (600 x 600) and center it. </p>
<p>Just select the rectangle and enter the following values in the transform options, which are displayed at the bottom of your screen.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression81.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression81.png?w=480&#038;h=21" alt="Transform Options" title="Transform Options" width="480" height="21" class="aligncenter size-full wp-image-3563" /></a></p>
<p>First unlink the height and width (constrain ratio) by clicking upon the chain icon. Then set the W(idth) and H(eight) settings to 600. To center it set the X and Y-axis properties to 512. </p>
<p>Voila, you now have a placeholder in which you can put your icon. You should wind up with a design surface which looks like this (apart from the colors):</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression9.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression9.png?w=480" alt="Square in a Square" title="Square in a Square"   class="aligncenter size-full wp-image-3565" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="icon" name="icon"></a><strong>The Icon</strong></p>
<p>Time to put the actual icon in place. In Expression Design open (File &gt; Open&#8230;) the file you created earlier with Photoshop (or your favorite graphical application). Once opened, select everything and copy the selection to the clipboard. </p>
<p>Close the file and go back to your icon design surface. Add a new layer and paste the icon. Now you need to resize and center it, just like you did with the icon placeholder.</p>
<ul>
<li>Unlink the width and height</li>
<li>Set the width and height to 600</li>
<li>Set the X and Y properties to 512</li>
</ul>
<p>Your icon should now be neatly positioned within the icon placeholder.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression10.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression10.png?w=480" alt="Centered Icon" title="Centered Icon"   class="aligncenter size-full wp-image-3569" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="slices" name="slices"></a><strong>Slices</strong></p>
<p>As mentioned before, you have to create 5 different icons. Let&#8217;s reuse the same icon! Time to create a slice for every type of icon needed.</p>
<p>First you need to adjust the layer which serves as the icon&#8217;s place holder. Set its opacity to 0%.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression11.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression11.png?w=480" alt="Opacity" title="Opacity"   class="aligncenter size-full wp-image-3572" /></a></p>
<p>Now select the Selection tool (V) and drag a selection around the icon.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression12.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression12.png?w=480" alt="Icon Selection" title="Icon Selection"   class="aligncenter size-full wp-image-3574" /></a></p>
<p>Time to create our first slice. Go to the Object menu and select the option &#8220;Create Slice from Selection&#8221;.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression13.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression13.png?w=480" alt="Create Slice from Selection" title="Create Slice from Selection"   class="aligncenter size-full wp-image-3575" /></a></p>
<p>In the properties window that is displayed give the slice an appropriate name (e.g. Application Tile Image) and set its resize properties (e.g. 173 x 173).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression14.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression14.png?w=480" alt="Slice Properties" title="Slice Properties"   class="aligncenter size-full wp-image-3577" /></a></p>
<p>Repeat this and create a slice for each of the different icons that you need. </p>
<p><strong>Remark</strong>: When you create your first slice a new layer will be created (Slice Layer). Before creating a new slice be sure to turn off the visibility of the slices or otherwise they will be included in the new slice. You can toggle the visibility by clicking on the eye icon next to the layer in the layers palette.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression15.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression15.png?w=480" alt="Layer Visibility" title="Layer Visibility"   class="aligncenter size-full wp-image-3579" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="using" name="using"></a><strong>Using The Icons</strong></p>
<p>OK, you are almost there. Time to export your work so that you can use the icon in Visual Studio. Click &#8220;File &gt; Export&#8230;&#8221;. Select the slice you want to export and save them to a directory (e.g. the root of your project).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression16.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression16.png?w=480&#038;h=312" alt="Export Slices" title="Export Slices" width="480" height="312" class="aligncenter size-full wp-image-3583" /></a></p>
<p>Once saved, go to Visual Studio and include the images in your Windows Phone project.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression171.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression171.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3587" /></a></p>
<p>Then right-click on your project in the Solution Explorer, select properties and go to the Application tab. Here you can select which icon should be used for the application list and for the tile.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression18.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression18.png?w=480&#038;h=278" alt="Application Properties" title="Application Properties" width="480" height="278" class="aligncenter size-full wp-image-3588" /></a></p>
<p>Voila, if you run your application now your custom icons will be displayed.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/expression20.png"><img src="http://cgeers.files.wordpress.com/2011/10/expression20.png?w=480&#038;h=438" alt="Application Icons" title="Application Icons" width="480" height="438" class="aligncenter size-full wp-image-3590" /></a></p>
<p>I learned this approach to creating Windows Phone icons from <a href="http://expression.microsoft.com/en-us/gg317447" target="_blank">an article by Rick Engle</a>. I customized it so it would fit my SO series, but you can find more information there. Certainly on how to create a better looking icon. But if you are creating an application for which icons are already available then this is a quick solution. Just create a white version of the icon and slice it up.</p>
<p><strong>Remark</strong>: By default the title of the application is displayed on the application&#8217;s tile. When creating that slice you might want to resize the icon a bit so that you&#8217;ll a bit of room for the title to be displayed or it will be displayed across the icon.</p>
<p>If you want to skip this step, then just download the icons I prepared on the download page. It also includes the icons for the marketplace. Any suggestions or comments, feel free to contact me.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>, <a href='http://cgeers.com/category/programming/windows-phone/'>Windows Phone</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3521/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3521&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/10/30/programming-windows-phone-7-5-part-2-icons/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/windows-phone-logo3.jpg" medium="image">
			<media:title type="html">Windows Phone 7.5 Logo</media:title>
		</media:content>

		<media:content url="http://stackoverflow.quickmediasolutions.com/images/stackoverflow.png" medium="image">
			<media:title type="html">StackOverflow</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/mango.png" medium="image">
			<media:title type="html">Mango Theme</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/photoshop.png" medium="image">
			<media:title type="html">Photoshopped Stackoverflow Icon</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression1.png" medium="image">
			<media:title type="html">New Document</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression2.png" medium="image">
			<media:title type="html">Rectangle Tool</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression3.png" medium="image">
			<media:title type="html">Appearance</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression5.png" medium="image">
			<media:title type="html">Lock Layer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression6.png" medium="image">
			<media:title type="html">Big Red Square</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression7.png" medium="image">
			<media:title type="html">New Layer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression81.png" medium="image">
			<media:title type="html">Transform Options</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression9.png" medium="image">
			<media:title type="html">Square in a Square</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression10.png" medium="image">
			<media:title type="html">Centered Icon</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression11.png" medium="image">
			<media:title type="html">Opacity</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression12.png" medium="image">
			<media:title type="html">Icon Selection</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression13.png" medium="image">
			<media:title type="html">Create Slice from Selection</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression14.png" medium="image">
			<media:title type="html">Slice Properties</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression15.png" medium="image">
			<media:title type="html">Layer Visibility</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression16.png" medium="image">
			<media:title type="html">Export Slices</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression171.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression18.png" medium="image">
			<media:title type="html">Application Properties</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/expression20.png" medium="image">
			<media:title type="html">Application Icons</media:title>
		</media:content>
	</item>
		<item>
		<title>Programming Windows Phone 7.5 Part 1: Getting Started</title>
		<link>http://cgeers.com/2011/10/16/programming-windows-phone-7-5-part-1-getting-started/</link>
		<comments>http://cgeers.com/2011/10/16/programming-windows-phone-7-5-part-1-getting-started/#comments</comments>
		<pubDate>Sun, 16 Oct 2011 12:48:58 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[Mango]]></category>
		<category><![CDATA[Stack Exchange]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3444</guid>
		<description><![CDATA[Introduction Two weeks ago I wrote an article about using the Stack Exchange API. Turns out it got featured on Channel 9 last week. Cool. In the video they wonder if there&#8217;s such a thing as a Stack Exchange application for the Windows Phone. There a few available, but it got me thinking if I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3444&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2011/10/windows-phone-logo3.jpg?w=480" alt="Windows Phone 7.5 Logo" title="Windows Phone 7.5 Logo"   class="alignright size-full wp-image-3455" /></p>
<p>Two weeks ago I wrote an article about using the <a href="http://cgeers.com/2011/10/02/stack-exchange-api/" target="_blank">Stack Exchange API</a>. Turns out it got featured on <a href="http://channel9.msdn.com/Shows/This+Week+On+Channel+9/TWC9-Oct-7-2011" target="_blank">Channel 9</a> last week. Cool.</p>
<p>In the video they wonder if there&#8217;s such a thing as a <a href="http://www.windowsphone.com/en-US/search?q=stack+exchange" target="_blank">Stack Exchange application for the Windows Phone</a>. There a few available, but it got me thinking if I could easily port the code to run on my Windows Phone. </p>
<p>I myself, haven&#8217;t developed much on the Windows Phone yet, apart from a few &#8220;Hello, World&#8221;-isch applications. Now that Mango (WP 7.5) has been officially released and I just reinstalled my PC, I figured this would be a good opportunity to get started with Windows Phone development.</p>
<p><span id="more-3444"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#mango">Mango Update</a></li>
<li><a href="#api">Windows Phone SDK 7.1</a></li>
<li><a href="#helloworld">Hello, World</a></li>
<li><a href="#device">Deploy To Device</a></li>
<li><a href="#part2">Up next, part 2</a></li>
</ul>
<p><a title="mango" name="mango"></a><strong>Mango Update</strong></p>
<p>Maybe you haven&#8217;t updated your Windows Phone yet because the Mango update is not available for your region and/or carrier? Well, there&#8217;s a simple trick you can use to circumvent this. Who wants to wait weeks for new toys? Nobody! Just follow these steps:</p>
<ol>
<li>Start Zune</li>
<li>Connect your phone to your PC</li>
<li>Have Zune check for an update for your phone</li>
<li>Disconnect your internet connection while Zune is checking for an update</li>
</ol>
<p>First Zune will check if there is an update (Yes), and then it will perform a second check to see if you are permitted to install this update (region, carrier&#8230;etc. restrictions). Guess what happens if you disconnect from the internet between these two checks?</p>
<p>It may take a few tries, you have to be a bit lucky when you disconnect your internet connection. But if you hit the sweet spot, the second check will timeout and Zune will just report that there&#8217;s an update. If so, just connect back to the internet and proceed with the update.</p>
<p>Voila, that&#8217;s it. Worked for me on the first try (HTC Trophy). Be warned, updating your phone will take a long time. Get some coffee, sit back and relax.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="sdk" name="sdk"></a><strong>Windows Phone SDK 7.1</strong></p>
<p>OK, we&#8217;re running Mango now. Now let&#8217;s make sure our development tools are also up to date. Open <del datetime="2011-10-16T10:24:43+00:00">Chrome</del> your favorite browser and navigate to <a href="http://create.msdn.com/en-US/" target="_blank">http://create.msdn.com/en-US/</a>. Next click on the &#8220;Download the free tools button&#8221;. You can&#8217;t miss it, it&#8217;s really big.</p>
<p><a href="http://create.msdn.com/en-us/home/getting_started" target="_blank"><img src="http://cgeers.files.wordpress.com/2011/10/download-the-free-tools.png?w=480" alt="Download The Free Tools" title="Download The Free Tools"   class="aligncenter size-full wp-image-3467" /></a></p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/tools.png"><img src="http://cgeers.files.wordpress.com/2011/10/tools.png?w=480" alt="Tools" title="Tools"   class="alignright size-full wp-image-3470" /></a>On the following page you can download the <a href="http://go.microsoft.com/?linkid=9772716" target="_blank">Windows Phone SDK 7.1</a> (Windows Phone 7.5/Mango = OS version 7.10.7720.68). The download (vm_web2.exe) is only 3 Mb. Once downloaded, start the setup and follow the wizard. Just click the big &#8220;Install Now&#8221; button.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/sdk1.png"><img src="http://cgeers.files.wordpress.com/2011/10/sdk1.png?w=480&#038;h=431" alt="SDK 7.1 Installation" title="SDK 7.1 Installation" width="480" height="431" class="aligncenter size-full wp-image-3473" /></a></p>
<p>Big buttons, its a key ingredient of the WP experience.</p>
<p>The setup will download about +/- 530 Megabytes of installation files. If you have a good broadband connection, the entire setup will take about 10 minutes or so. Afterwards you can find the installed tools in the Start menu (Start &gt; All Programs).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/sdk6.png"><img src="http://cgeers.files.wordpress.com/2011/10/sdk6.png?w=480" alt="All Programs" title="All Programs"   class="aligncenter size-full wp-image-3477" /></a></p>
<p><strong>Remark</strong>: Make sure you have the <a href="http://www.microsoft.com/download/en/details.aspx?id=23691" target="_blank">Visual Studio 2010 Service Pack 1</a> installed! You cannot install the Windows Phone SDK 7.1 without it!</p>
<p><a href="#top">Top of page</a></p>
<p><a title="helloworld" name="helloworld"></a><strong>Hello, World!</strong></p>
<p>We&#8217;re ready to go. Let&#8217;s create a &#8220;<a href="http://en.wikipedia.org/wiki/Hello_world_program" target="_blank">Hello, World!</a>&#8221; application as a sort of a test drive. Start up Visual Studio 2010, create a new blank solution called WindowsPhone and add a new Windows Phone Application project titled HelloWorld to it.</p>
<p>You can find the Windows Phone Application project template in the &#8220;Silverlight for Windows Phone&#8221; folder (File &gt; New Project).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/wp8.png"><img src="http://cgeers.files.wordpress.com/2011/10/wp8.png?w=480&#038;h=331" alt="Windows Phone Application Project Template" title="Windows Phone Application Project Template" width="480" height="331" class="aligncenter size-full wp-image-3483" /></a></p>
<p>When creating the project Visual Studio will ask which SDK (7.0 or 7.1) you want to target.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/wp2.png"><img src="http://cgeers.files.wordpress.com/2011/10/wp2.png?w=480&#038;h=226" alt="Windows Phone OS SDK Version" title="Windows Phone OS SDK Version" width="480" height="226" class="aligncenter size-full wp-image-3485" /></a></p>
<p>Select &#8220;Windows Phone OS 7.1&#8243; and click OK.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/wp91.png"><img src="http://cgeers.files.wordpress.com/2011/10/wp91.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3489" /></a></p>
<p>The default project template contains one Windows Phone page (<a href="http://msdn.microsoft.com/en-us/library/ff402539(VS.92).aspx" target="_blank">PhoneApplicationPage</a>), called MainPage as you can see in the above screenshot.</p>
<p>You can compare it a bit to ASP.NET. It is composed out of two files, a XAML file (the layout) and a C# (.xaml.cs) file which contains the code behind. If you open the XAML file you&#8217;ll get a split screen layout. One part shows the XAML while the other part shows the rendered layout.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/wp101.png"><img src="http://cgeers.files.wordpress.com/2011/10/wp101.png?w=480&#038;h=377" alt="Designer" title="Designer" width="480" height="377" class="aligncenter size-full wp-image-3495" /></a></p>
<p>You can clearly see that the main page is divided into two sections. One section for the title and one for the body (marked with the red rectangle). Go to the toolbox and drag a <a href="http://msdn.microsoft.com/en-us/library/hh487169(v=VS.92).aspx" target="_blank">Button</a> and a <a href="http://msdn.microsoft.com/en-us/library/hh202894(v=VS.92).aspx" target="_blank">TextBlock</a> control to the body.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/wp11.png"><img src="http://cgeers.files.wordpress.com/2011/10/wp11.png?w=480" alt="MainPage Controls" title="MainPage Controls"   class="aligncenter size-full wp-image-3498" /></a></p>
<p>Give the controls some easy to remember names (e.g. MyButton, MyTextBlock).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/properties.png"><img src="http://cgeers.files.wordpress.com/2011/10/properties.png?w=480" alt="Properties" title="Properties"   class="aligncenter size-full wp-image-3499" /></a></p>
<p>Double click on the button control to generate a click event handler in the code behind file. Add the following code to the event handler.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">void</span> MyButton_Click(<span class="kwrd">object</span> sender, RoutedEventArgs e)
{
    MyTextBlock.Text = <span class="str">"Hello, World!"</span>;
}</pre>
</div>
<p>There, you just create your first Windows Phone application. Hit F5 to run the application. By default Visual Studio will start the Windows Phone emulator and deploy your application to it. Give it some time and your application will automatically start. Click on the button to change the TextBlock&#8217;s text.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/wp12.png"><img src="http://cgeers.files.wordpress.com/2011/10/wp12.png?w=480" alt="Hello, World!" title="Hello, World!"   class="aligncenter size-full wp-image-3502" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="device" name="device"></a><strong>Deploy To Device</strong></p>
<p>The emulator runs the same software as your Windows Phone device. Of course it cannot mimic certain hardware specific features (compass, gps, accelerometer&#8230;etc.), but for development purposes its a handy tool. However, Visual Studio lets you choose to where you want to deploy your application. The emulator or an actual device.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/target.png"><img src="http://cgeers.files.wordpress.com/2011/10/target.png?w=480" alt="Deploy To" title="Deploy To"   class="aligncenter size-full wp-image-3504" /></a></p>
<p>So, start the Zune software, hook up your device and unlock the wallpaper. Next choose the option &#8220;Windows Phone Device&#8221; in Visual Studio and run your project. </p>
<p>The exception &#8220;Failed to connect to device as it is developer locked. For details on developer unlock, visit <a href="http://go.microsoft.com/fwlink/?LinkId=195284" target="_blank">http://go.microsoft.com/fwlink/?LinkId=195284</a>.&#8221; will now be thrown.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/wp14.png"><img src="http://cgeers.files.wordpress.com/2011/10/wp14.png?w=480&#038;h=78" alt="Unregistered Windows Phone Device" title="Unregistered Windows Phone Device" width="480" height="78" class="aligncenter size-full wp-image-3507" /></a></p>
<p>In order to deploy to an actual device you need to unlock it. You need to create an <a href="http://create.msdn.com/en-us/home/membership" target="_blank">App Hub account</a>. Unfortunately this costs 99$/year, but for this price you can unlock up to 3 devices and also deploy your application to the market place. </p>
<p>After you&#8217;ve created an App Hub account you need to use the &#8220;Phone Developer Registration&#8221; tool. You can find this in the folder into which the Windows Phone SDK was installed (C:\Program Files\Microsoft SDKs\Windows Phone\v7.1\Tools\Phone Registration).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/developer-phone-registration.png"><img src="http://cgeers.files.wordpress.com/2011/10/developer-phone-registration.png?w=480&#038;h=432" alt="Developer Phone Registration" title="Developer Phone Registration" width="480" height="432" class="aligncenter size-full wp-image-3511" /></a></p>
<p>Afterwards you can deploy your applications to your device(s). This process does not actually modify anything on your device. It just registers in the cloud that it is now registered as a developer phone.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="part2" name="part2"></a><strong>Up next, part 2</strong></p>
<p>During this series we are going to develop a small application which uses the Stack Exchange API to retrieve a user&#8217;s <a href="http://stackoverflow.com/users/893099/christophe-geers" target="_blank">Stack Overflow profile</a> (profile, badges and reputation). In the next part of this series, we&#8217;ll create some icons which we can use to brand our application.</p>
<p>For example:</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/icon.png"><img src="http://cgeers.files.wordpress.com/2011/10/icon.png?w=480" alt="Stack Overflow Icon" title="Stack Overflow Icon"   class="aligncenter size-full wp-image-3514" /></a></p>
<p>I&#8217;ll try to get the next part online as soon as time permits. You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>, <a href='http://cgeers.com/category/programming/windows-phone/'>Windows Phone</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3444/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3444/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3444/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3444&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/10/16/programming-windows-phone-7-5-part-1-getting-started/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/windows-phone-logo3.jpg" medium="image">
			<media:title type="html">Windows Phone 7.5 Logo</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/download-the-free-tools.png" medium="image">
			<media:title type="html">Download The Free Tools</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/tools.png" medium="image">
			<media:title type="html">Tools</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/sdk1.png" medium="image">
			<media:title type="html">SDK 7.1 Installation</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/sdk6.png" medium="image">
			<media:title type="html">All Programs</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/wp8.png" medium="image">
			<media:title type="html">Windows Phone Application Project Template</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/wp2.png" medium="image">
			<media:title type="html">Windows Phone OS SDK Version</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/wp91.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/wp101.png" medium="image">
			<media:title type="html">Designer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/wp11.png" medium="image">
			<media:title type="html">MainPage Controls</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/properties.png" medium="image">
			<media:title type="html">Properties</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/wp12.png" medium="image">
			<media:title type="html">Hello, World!</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/target.png" medium="image">
			<media:title type="html">Deploy To</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/wp14.png" medium="image">
			<media:title type="html">Unregistered Windows Phone Device</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/developer-phone-registration.png" medium="image">
			<media:title type="html">Developer Phone Registration</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/icon.png" medium="image">
			<media:title type="html">Stack Overflow Icon</media:title>
		</media:content>
	</item>
		<item>
		<title>Stack Exchange API</title>
		<link>http://cgeers.com/2011/10/02/stack-exchange-api/</link>
		<comments>http://cgeers.com/2011/10/02/stack-exchange-api/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 11:03:03 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Json.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Stack Exchange API]]></category>
		<category><![CDATA[Stack Overflow]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3375</guid>
		<description><![CDATA[Introduction Two weeks ago I was playing around with the Stack Exchange API to see if it was easy to build a custom flair application. You know, this little guy: How hard can it be to retrieve a user&#8217;s profile, badge count and reputation updates? Surely, Stack Exchange has an API. And they do&#8230;and it&#8217;s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3375&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2011/10/logo.png?w=150&#038;h=32" alt="" title="logo" width="150" height="32" class="alignright size-thumbnail wp-image-3376" /></p>
<p>Two weeks ago I was playing around with the Stack Exchange API to see if it was easy to build a custom flair application. You know, this little guy:</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/flair.png"><img src="http://cgeers.files.wordpress.com/2011/10/flair.png?w=480" alt="Flair" title="Flair"   class="aligncenter size-full wp-image-3380" /></a></p>
<p>How hard can it be to retrieve a user&#8217;s profile, badge count and reputation updates? Surely, Stack Exchange has an API. And they do&#8230;and it&#8217;s pretty easy to use. Let&#8217;s quickly cobble together a small sample application.</p>
<p><span id="more-3375"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#api">API Usage</a></li>
<li><a href="#profile">User Profile</a></li>
<li><a href="#requests">Sending Requests</a></li>
<li><a href="#reputation">Reputation Changes</a></li>
</ul>
<p><a title="api" name="api"></a><strong>API Usage</strong></p>
<p>You can find the documentation for the Stack Exchange API here:</p>
<p><a href="http://api.stackoverflow.com/" target="_blank">http://api.stackoverflow.com/</a></p>
<p>At the time of writing the latest release is v1.1, but a <a href="http://stackapps.com/questions/2588/draft-specification-for-api-v2-0" target="_blank">draft specification</a> for version 2.0 has just been released.</p>
<p>What do you need to know about the API? </p>
<ul>
<li>It&#8217;s read-only</li>
<li>All API responses are JSON</li>
<li>All responses are GZIP&#8217;d</li>
<li>API usage is throttled by IP address</li>
</ul>
<p>API usage is throttled? Yup, each IP address gets 300 daily requests (No matter how many applications you run behind this IP address). However, if you <a href="http://stackapps.com/apps/register" target="_blank">register your application</a> you receive an API key and you get 10.000 daily requests. You just need to append this key to each of your requests.</p>
<p>Each response you receive includes your maximum and current limits. Those numbers are stored in the HTTP headers. Let&#8217;s inspect them (X-RateLimit-Max &amp; X-RateLimit-Current).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/rates.png"><img src="http://cgeers.files.wordpress.com/2011/10/rates.png?w=480&#038;h=356" alt="Stack Exchange Rate Limits" title="Stack Exchange Rate Limits" width="480" height="356" class="aligncenter size-full wp-image-3389" /></a></p>
<p>You&#8217;d expect the X-RateLimit-Current count to decrement by 1 with each request, however sometimes you&#8217;ll receive duplicate numbers. I reported this on <a href="http://stackapps.com/questions/2592/current-rate-limit-not-always-decrementing" target="_blank">StackApps</a>, but haven&#8217;t received a reply as to why this happens.</p>
<p>So what do we need to be able to use the API?</p>
<ul>
<li>It talks JSON? Fire up <a href="http://www.nuget.org/" target="_blank">NuGet</a> and get the popular <a href="http://james.newtonking.com/pages/json-net.aspx" target="_blank">Json.NET</a> library.</li>
<li>We&#8217;ll need to issue requests. Let&#8217;s keep it simple and use the <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx" target="_blank">HttpWebRequest class</a></li>
<li>All responses are GZIP&#8217;d? Luckily the .NET framework provides us with the <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx" target="_blank">GZipStream class</a>.</li>
</ul>
<p>Time for action.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="profile" name="profile"></a><strong>User Profile</strong></p>
<p>Let&#8217;s start by retrieving the user&#8217;s profile. You can retrieve it using the &#8220;<a href="http://api.stackoverflow.com/1.1/usage/methods/users-by-ids" target="_blank">users/{id}</a>&#8221; API method. It takes a bunch of parameters, but we are only interested in one parameter, namely the user id (id parameter).</p>
<p>Just type in the following URL in your address bar to see an example response:</p>
<p><a href="http://api.stackoverflow.com/1.1/users/893099" target="_blank">http://api.stackoverflow.com/1.1/users/893099</a></p>
<p>It looks something like this (I&#8217;ve shortened it here for illustrative purposes):</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
{
  "total": 1,
  "page": 1,
  "pagesize": 30,
  "users": [
    {
      "user_id": 893099,
      "user_type": "registered",
      "display_name": "Christophe Geers",
      "reputation": 1581,
      "last_access_date": 1317546569,
      "location": "Belgium",
      "badge_counts": {
        "gold": 0,
        "silver": 1,
        "bronze": 10
      }
    }
  ]
}</pre>
</div>
<p>You can retrieve a profile for one or more users with a single request. Most of the API&#8217;s methods are vectorized. They accept multiple values within a single parameter on a request. You just need to separate them by semi-colons. </p>
<p>The format for a response is alway the same, they are paged. At the root you&#8217;ll find the paging information (total, page, pagesize) and then you&#8217;ll find an array which contains the information you requested. Here this information is contained within the users array. Take a mental note of this, we&#8217;ll get back to it later.</p>
<p>Let&#8217;s create a simple class into which we can deserialize a user&#8217;s profile. It&#8217;s decorated with attributes so we can easily deserialize / serialize it using Json.NET.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[WrapperObject(<span class="str">"users"</span>)]
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> User
{
    [JsonProperty(PropertyName = <span class="str">"user_id"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; <span class="kwrd">internal</span> set; }

    [JsonProperty(PropertyName = <span class="str">"display_name"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> DisplayName { get; <span class="kwrd">internal</span> set; }

    [JsonProperty(PropertyName = <span class="str">"reputation"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> Reputation { get; <span class="kwrd">internal</span> set; }

    [JsonProperty(PropertyName = <span class="str">"badge_counts"</span>)]
    <span class="kwrd">public</span> BadgeCounts BadgeCounts { get; set; }
}</pre>
</div>
<p>The BadgeCount class looks like this:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> BadgeCounts
{
    [JsonProperty(PropertyName = <span class="str">"gold"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> Gold { get; set; }

    [JsonProperty(PropertyName = <span class="str">"silver"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> Silver { get; set; }

    [JsonProperty(PropertyName = <span class="str">"bronze"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> Bronze { get; set; }
}</pre>
</div>
<p>Did you notice the WrapperObject attribute on the User class? This is just a simple attribute that contains the name of the array in the JSON response which contains the data we are interested in. We&#8217;ll need this when deserialing the data.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = <span class="kwrd">false</span>, Inherited = <span class="kwrd">false</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> WrapperObjectAttribute : Attribute
{
    <span class="kwrd">public</span> WrapperObjectAttribute(<span class="kwrd">string</span> wrapperObject)
    {
        <span class="kwrd">this</span>.WrapperObject = wrapperObject;
    }

    <span class="kwrd">public</span> <span class="kwrd">string</span> WrapperObject { get; set; }
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="requests" name="requests"></a><strong>Sending Requests</strong></p>
<p>Ok, we&#8217;ve layed the foundation. Time to send a request which retrieves the user&#8217;s profile. Create a class called StackExchangeApi and add the following code to it.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> StackExchangeApi
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> ApiVersion = <span class="str">"1.1"</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> BaseUri = <span class="str">"http://api.stackoverflow.com/"</span> + ApiVersion;
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> <span class="kwrd">string</span> _apiKey;

    <span class="kwrd">public</span> StackExchangeApi(<span class="kwrd">string</span> apiKey)
    {
        <span class="kwrd">this</span>._apiKey = apiKey;
    }

    <span class="kwrd">public</span> User GetUser(<span class="kwrd">int</span> userId)
    {
        <span class="kwrd">return</span> GetStackExchangeObject&lt;User&gt;(
            String.Format(<span class="str">"/users/{0}"</span>, userId));
    }
}</pre>
</div>
<p>To retrieve a user&#8217;s profile the consumer of this class only has to write two lines of code.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var api = <span class="kwrd">new</span> StackExchangeApi(<span class="str">"your api key"</span>);
var user = api.GetUser(893099);</pre>
</div>
<p>Let&#8217;s complete the StackExchangeApi class. Add the private method GetStackExchangeObject(&#8230;) to this type.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> T GetStackExchangeObject&lt;T&gt;(<span class="kwrd">string</span> path) <span class="kwrd">where</span> T : <span class="kwrd">class</span>, <span class="kwrd">new</span>()
{
    var requestUri = ComposeUri(path);
    var json = GetResponse(requestUri);
    <span class="kwrd">return</span> ParseJson&lt;T&gt;(json).FirstOrDefault();
}</pre>
</div>
<p>The GetStackExchangeObject(&#8230;) method&#8217;s responsibility is to retrieve one object from a response. For the GetUser(&#8230;) method we are only interested in one single user profile.</p>
<p>First it composes the Uri (<a href="http://api.stackoverflow.com/1.1/users/893099" target="_blank">http://api.stackoverflow.com/1.1/users/893099?key=YourApiKey</a>) it needs to call using the ComposeUri(&#8230;) method.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">string</span> ComposeUri(<span class="kwrd">string</span> path)
{
    var uri = String.Format(<span class="str">"{0}{1}"</span>, BaseUri, path);
    <span class="kwrd">if</span> (!String.IsNullOrWhiteSpace(<span class="kwrd">this</span>._apiKey))
    {
        var separator = uri.Contains(<span class="str">"?"</span>) ? <span class="str">"&amp;"</span> : <span class="str">"?"</span>;
        uri = String.Format(<span class="str">"{0}{1}key={2}"</span>, uri, separator, <span class="kwrd">this</span>._apiKey);
    }
    <span class="kwrd">return</span> uri;
}</pre>
</div>
<p>Then it actually sends out the request and parses the response (GetResponse(&#8230;) method). </p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">string</span> GetResponse(<span class="kwrd">string</span> requestUri)
{
    var request = (HttpWebRequest) WebRequest.Create(requestUri);
    request.Method = WebRequestMethods.Http.Get;
    request.Accept = <span class="str">"application/json"</span>;
    var json = ExtractJsonResponse(request.GetResponse());
    <span class="kwrd">return</span> json;
}</pre>
</div>
<p>It uses a simple HttpWebRequest to send the request. Afterwards you need to extract the JSON data from the response. Remember that all the responses are GZIP&#8217;d. Let&#8217;s examine the ExtractJsonRespone(&#8230;) method.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">string</span> ExtractJsonResponse(WebResponse response)
{
    <span class="kwrd">string</span> json;
    <span class="kwrd">using</span> (var outStream = <span class="kwrd">new</span> MemoryStream())
    <span class="kwrd">using</span> (var zipStream = <span class="kwrd">new</span> GZipStream(response.GetResponseStream(),
        CompressionMode.Decompress))
    {
        zipStream.CopyTo(outStream);
        outStream.Seek(0, SeekOrigin.Begin);
        <span class="kwrd">using</span> (var reader = <span class="kwrd">new</span> StreamReader(outStream, Encoding.UTF8))
        {
            json = reader.ReadToEnd();
        }
    }
    <span class="kwrd">return</span> json;
}
</pre>
</div>
<p>The HttpWebRequest instance returns the response in the form of a stream. By wrapping this stream in a GZipStream we can easily unzip the response and get a hold of the JSON data.</p>
<p>OK, we&#8217;ve got the JSON data. Now we need to to deserialize it into a User instance. This is were the generic parameter passed to the GetStackExchangeObject(&#8230;) method comes into play. The GetUser(&#8230;) method passed the User type to it. This is then passed on to the ParseJson(&#8230;) method.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">static</span> IEnumerable&lt;T&gt; ParseJson&lt;T&gt;(<span class="kwrd">string</span> json) <span class="kwrd">where</span> T : <span class="kwrd">class</span>, <span class="kwrd">new</span>()
{
    var type = <span class="kwrd">typeof</span> (T);
    var attribute = type.GetCustomAttributes(
        <span class="kwrd">typeof</span> (WrapperObjectAttribute), <span class="kwrd">false</span>).SingleOrDefault() <span class="kwrd">as</span>
        WrapperObjectAttribute;
    <span class="kwrd">if</span> (attribute == <span class="kwrd">null</span>)
    {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
            String.Format(<span class="str">"{0} type must be decorated with a
            WrapperObjectAttribute."</span>, type.Name));
    }

    var jobject = JObject.Parse(json);
    var collection = JsonConvert.DeserializeObject&lt;List&lt;T&gt;&gt;
        (jobject[attribute.WrapperObject].ToString());
    <span class="kwrd">return</span> collection;
}</pre>
</div>
<p>The ParseJson(&#8230;) method first checks if you decorated the type (T) with a WrapperObjectAttribute. It needs this information so that it knows the name of the array in the JSON response which actually contains the data we are interested in. Then it deserializes this array to a collection of T (List&lt;T&gt;). The GetStackExchangeObject(&#8230;) method then returns the first object contained within this collection. Since we only requested the profile for one user it only contains one object.</p>
<p>It&#8217;s now very easy to retrieve a user&#8217;s profile.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var api = <span class="kwrd">new</span> StackExchangeApi(<span class="str">"your api key"</span>);

var user = api.GetUser(893099);

Console.WriteLine(String.Format(<span class="str">"User id: {0}"</span>, user.Id));
Console.WriteLine(String.Format(<span class="str">"Display name: {0}"</span>, user.DisplayName));
Console.WriteLine(String.Format(<span class="str">"Reputation: {0}"</span>, user.Reputation));
Console.WriteLine(String.Format(<span class="str">"Golden badges: {0}"</span>, user.BadgeCounts.Gold));
Console.WriteLine(String.Format(<span class="str">"Silver badges: {0}"</span>, user.BadgeCounts.Silver));
Console.WriteLine(String.Format(<span class="str">"Bronze badges: {0}"</span>, user.BadgeCounts.Bronze));
Console.WriteLine();</pre>
</div>
<p>The output:</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/user-profile.png"><img src="http://cgeers.files.wordpress.com/2011/10/user-profile.png?w=480&#038;h=131" alt="User Profile" title="User Profile" width="480" height="131" class="aligncenter size-full wp-image-3417" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="reputation" name="reputation"></a><strong>Reputation Changes</strong></p>
<p>Ok, we&#8217;ve got the user&#8217;s profile. Now let&#8217;s get a list of his / her reputation changes (or updates). You can retrieve this information using the &#8220;<a href="http://api.stackoverflow.com/1.1/usage/methods/user-reputation-changes" target="_blank">/users/{id}/reputation</a>&#8221; API method. </p>
<p>A response looks as follows:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
{
 "total": 59,
 "page": 1,
 "pagesize": 30,
 "rep_changes": [
  {
   "user_id": 893099,
   "post_id": 7555096,
   "post_type": "answer",
   "title": "Json.Net - Serialize property name without quotes",
   "positive_rep": 30,
   "negative_rep": 0,
   "on_date": 1317147319
  },
  {
   "user_id": 893099,
   "post_id": 7546079,
   "post_type": "answer",
   "title": "developer manuals",
   "positive_rep": 35,
   "negative_rep": 0,
   "on_date": 1317122274
  }]
}</pre>
</div>
<p>The data we are interested in is stored in the rep_changes array. However, this time were are interested in all the items of this array. Let&#8217;s create a simple C# class in which we can store a reputation change.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[WrapperObject(<span class="str">"rep_changes"</span>)]
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> ReputationChange
{
    [JsonProperty(PropertyName = <span class="str">"user_id"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> UserId { get; set; }

    [JsonProperty(PropertyName = <span class="str">"post_id"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> PostId { get; set; }

    [JsonProperty(PropertyName = <span class="str">"post_type"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> PostType { get; set; }

    [JsonProperty(PropertyName = <span class="str">"title"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Title { get; set; }

    [JsonProperty(PropertyName = <span class="str">"negative_rep"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> NegativeReputation { get; set; }

    [JsonProperty(PropertyName = <span class="str">"positive_rep"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> PossitiveReputation { get; set; }

    [JsonProperty(PropertyName = <span class="str">"on_date"</span>)]
    [JsonConverter(<span class="kwrd">typeof</span>(UnixDateTimeConverter))]
    <span class="kwrd">public</span> DateTime OnDate { get; set; }
}</pre>
</div>
<p><strong>Remark</strong>: The UnixDateTimeConverter type is not a default Json.NET converter. It&#8217;s a custom converter I created that&#8217;s able to deserialize / serialize Unix timestamps. Read my previous post &#8220;<a href="http://cgeers.com/2011/09/25/writing-a-custom-json-net-datetime-converter/" target="_blank">Writing a custom Json.NET DateTime Converter</a>&#8221; to see how it works.</p>
<p>We&#8217;re almost there. Add the following method to the StackExchangeApi class.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> IEnumerable&lt;ReputationChange&gt; GetReputationChanges(<span class="kwrd">int</span> userId,
  DateTime fromDate, DateTime toDate)
{
    var path = String.Format(
        <span class="str">"/users/{0}/reputation?fromdate={1}&amp;todate={2}"</span>, userId,
        fromDate.ToUnixTime(), toDate.ToUnixTime());

    <span class="kwrd">return</span> GetStackExchangeObjects&lt;ReputationChange&gt;(path);
}</pre>
</div>
<p>You can now easily retrieve the user&#8217;s reputation changes. For example, let&#8217;s retrieve the updates for the last two weeks:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var api = <span class="kwrd">new</span> StackExchangeApi(<span class="str">"your api key"</span>);
var reputation = api.GetReputationChanges(893099,
    DateTime.Now.AddDays(-14), DateTime.Now);</pre>
</div>
<p>The private GetStackExchangeObjects(&#8230;) method called by the ReputationChanges method is almost identical to the GetStackExchangeObject(&#8230;) method. It reuses all the code we wrote earlier, but it returns a collection of T instead of a single T.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
private IEnumerable&lt;T&gt; GetStackExchangeObjects&lt;T&gt;(<span class="kwrd">string</span> path) <span class="kwrd">where</span> T : <span class="kwrd">class</span>, <span class="kwrd">new</span>()
{
    var requestUri = ComposeUri(path);
    var json = GetResponse(requestUri);
    <span class="kwrd">return</span> ParseJson&lt;T&gt;(json);
}</pre>
</div>
<p>Voila, that&#8217;s it. You can now retrieve a user&#8217;s reputation changes.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var api = <span class="kwrd">new</span> StackExchangeApi(<span class="str">"your api key"</span>);
var reputation = api.GetReputationChanges(893099,
    DateTime.Now.AddDays(-14), DateTime.Now);
<span class="kwrd">foreach</span>(var change <span class="kwrd">in</span> reputation)
{
    Console.WriteLine(String.Format(<span class="str">"{0}: {1} +{2} -{3}"</span>,
    change.OnDate, change.Title,
    change.PossitiveReputation,
    change.NegativeReputation));
}
</pre>
</div>
<p>The output:</p>
<p><a href="http://cgeers.files.wordpress.com/2011/10/reputation-changes.png"><img src="http://cgeers.files.wordpress.com/2011/10/reputation-changes.png?w=480&#038;h=242" alt="Reputation Changes" title="Reputation Changes" width="480" height="242" class="aligncenter size-full wp-image-3434" /></a></p>
<p>You can now easily retrieve a user&#8217;s profile and reputation changes. You can add support for the remaining API methods if you like. To implement them just follow the same pattern as shown here.</p>
<p>You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/json-net/'>Json.NET</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>, <a href='http://cgeers.com/category/programming/stack-exchange-api/'>Stack Exchange API</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3375/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3375&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/10/02/stack-exchange-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/logo.png?w=150" medium="image">
			<media:title type="html">logo</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/flair.png" medium="image">
			<media:title type="html">Flair</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/rates.png" medium="image">
			<media:title type="html">Stack Exchange Rate Limits</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/user-profile.png" medium="image">
			<media:title type="html">User Profile</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/10/reputation-changes.png" medium="image">
			<media:title type="html">Reputation Changes</media:title>
		</media:content>
	</item>
		<item>
		<title>Writing a custom Json.NET DateTime Converter</title>
		<link>http://cgeers.com/2011/09/25/writing-a-custom-json-net-datetime-converter/</link>
		<comments>http://cgeers.com/2011/09/25/writing-a-custom-json-net-datetime-converter/#comments</comments>
		<pubDate>Sun, 25 Sep 2011 10:30:35 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Json.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Json.NET Converter]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3327</guid>
		<description><![CDATA[Introduction Last weekend I was playing around with the Stack Exchange API. All the API responses are expressed in JSON. So I decided to use the Json.NET library to easily deserialize the JSON responses into simple .NET objects. This library has great support for deserialing JSON into .NET objects and serializing them back into JSON. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3327&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2011/09/json160.gif?w=480" alt="JSON" title="JSON"   class="alignright size-full wp-image-3328" /></p>
<p>Last weekend I was playing around with the <a href="http://api.stackoverflow.com" target="_blank">Stack Exchange API</a>. All the API responses are expressed in <a href="http://en.wikipedia.org/wiki/Json" target="_blank">JSON</a>. So I decided to use the <a href="http://james.newtonking.com/projects/json-net.aspx" target="_blank">Json.NET library</a> to easily deserialize the JSON responses into simple .NET objects. </p>
<p>This library has great support for deserialing JSON into .NET objects and serializing them back into JSON. For example, if you want to serialize an object to a JSON string all you have to do is decorate the type with some attributes.</p>
<p>For example:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> Person
{
  [JsonProperty]
  <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; } 

  [JsonProperty]
  [JsonConverter(<span class="kwrd">typeof</span>(IsoDateTimeConverter))]
  <span class="kwrd">public</span> DateTime BirthDate { get; set; }
}</pre>
</div>
<p>Notice that for the BirthDate property a specific converter is specified (<a href="http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Converters_IsoDateTimeConverter.htm" target="_blank">IsoDateTimeConverter</a>). Sometimes it is not enough to tell Json.NET which properties should be serialized. You need to help it out a bit and inform it how the properties should be serialized / deserialized. Here the IsoDateTimeConverter informs Json.NET that it should serialize the birthdate into an ISO 8601 date format.</p>
<p>The Stack Exchange API uses Unix timestamps to express all of its timestamps. Out of the box Json.NET does not contain a converter that can handle this notation for DateTime properties. But luckily we can create our own. It&#8217;s actually very easy, let&#8217;s see how we can do this&#8230;</p>
<p><span id="more-3327"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#jsonresponse">JSON Response</a></li>
<li><a href="#reputationchange">ReputationChange Class</a></li>
<li><a href="#unix">UnixDateTimeConverter Class</a></li>
<li><a href="#demo">Demo</a></li>
</ul>
<p><a title="jsonresponse" name="jsonresponse"></a><strong>JSON Response</strong></p>
<p>Let&#8217;s use one of the responses from the StackExchange API to test our custom DateTime converter. For one call (/users/{id}/reputation), the StackExchange API returns the following JSON string:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
{
    <span class="str">"user_id"</span>: 893099,
    <span class="str">"post_id"</span>: 7539201,
    <span class="str">"title"</span>: <span class="str">"UserControl custom property grayed?"</span>,
    <span class="str">"positive_rep"</span>: 35,
    <span class="str">"on_date"</span>: 1316873139
}
</pre>
</div>
<p>Notice that the on_date property property is expressed as a Unix timestamp. </p>
<p><strong>Remark</strong>: The actual response is quite a bit longer, and slightly more complicated. I shortened it for this demo. Check ouf the <a href="http://api.stackoverflow.com/1.1/usage/methods/user-reputation-changes" target="_blank">/users/{id}/reputation API method</a> if you are interested in the full response.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="reputationchange" name="reputationchange"></a><strong>ReputationChange Class</strong></p>
<p>Let&#8217;s create a simple class in which we can deserialize this JSON string.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> ReputationChange
{
    [JsonProperty(PropertyName = <span class="str">"user_id"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> UserId { get; set; }

    [JsonProperty(PropertyName = <span class="str">"post_id"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> PostId { get; set; }

    [JsonProperty(PropertyName = <span class="str">"title"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Title { get; set; }

    [JsonProperty(PropertyName = <span class="str">"positive_rep"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> PossitiveReputation { get; set; }

    [JsonProperty(PropertyName = <span class="str">"on_date"</span>)]
    [JsonConverter(<span class="kwrd">typeof</span>(UnixDateTimeConverter))]
    <span class="kwrd">public</span> DateTime OnDate { get; set; }
}</pre>
</div>
<p>As you can see, the OnDate property has been decorated with a new attribute. A new type of converter, namely the UnixDateTimeConverter type. Let&#8217;s see what makes it tick.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="unix" name="unix"></a><strong>UnixDateTimeConverter Class</strong></p>
<p>If you want to create your own Json.NET convertor you must create a new type which descends from the abstract <a href="http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonConverter.htm" target="_blank">JsonConverter</a> type. However, for converting a DateTime to and from JSON the library provides the abstract <a href="http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Converters_DateTimeConverterBase.htm" target="_blank">DateTimeConverterBase</a> type which already does some of the plumbing for you.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> UnixDateTimeConverter : DateTimeConverterBase
{
  <span class="rem">//...</span>
}   </pre>
</div>
<p>To create your own DateTime converter you must override two methods, namely:</p>
<ul>
<li><strong>ReadJson(JsonReader, Type, Object, JsonSerializer)</strong>: Reads the JSON representation of the object.</li>
<li><strong>WriteJson(JsonWriter, Object, JsonSerializer)</strong>: Writes the JSON representation of the object.</li>
</ul>
<p>Let&#8217;s start with parsing the JSON representation of a Unix timestamp into a valid DateIime structure.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> ReadJson(JsonReader reader, Type objectType, <span class="kwrd">object</span> existingValue,
    JsonSerializer serializer)
{
    <span class="kwrd">if</span> (reader.TokenType != JsonToken.Integer)
    {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(
            String.Format(<span class="str">"Unexpected token parsing date. Expected Integer, got {0}."</span>,
            reader.TokenType));
    }

    var ticks = (<span class="kwrd">long</span>) reader.Value;

    var date = <span class="kwrd">new</span> DateTime(1970, 1, 1);
    date = date.AddSeconds(ticks);

    <span class="kwrd">return</span> date;
}</pre>
</div>
<p>The ReadJson(&#8230;) method is called by Json.NET when it needs to parse the JSON string that contains the value for your DateTime. The reader (JsonReader) instance is already correctly positioned.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Unix_time" target="_blank">Unix time</a> contains the number of seconds that elapsed since midnight (UTC) of January 1, 1970. So first we make sure if we are dealing with a valid integer and if so, we add the number of seconds to January 1, 1970.</p>
<p>Now we also need to be able to serialize a DateTime into a valid JSON string. Time ot override the WriteJson(&#8230;) method.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> WriteJson(JsonWriter writer, <span class="kwrd">object</span> <span class="kwrd">value</span>,
    JsonSerializer serializer)
{
    <span class="kwrd">long</span> ticks;
    <span class="kwrd">if</span> (<span class="kwrd">value</span> <span class="kwrd">is</span> DateTime)
    {
        var epoc = <span class="kwrd">new</span> DateTime(1970, 1, 1);
        var delta = ((DateTime) <span class="kwrd">value</span>) - epoc;
        <span class="kwrd">if</span> (delta.TotalSeconds &lt; 0)
        {
            <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentOutOfRangeException(
                <span class="str">"Unix epoc starts January 1st, 1970"</span>);
        }
        ticks = (<span class="kwrd">long</span>) delta.TotalSeconds;
    }
    <span class="kwrd">else</span>
    {
        <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">"Expected date object value."</span>);
    }
    writer.WriteValue(ticks);
}</pre>
</div>
<p>Now we take our DateTime and calculate the amount of seconds that passed since January 1, 1970. Then we write this value out to the JsonWriter instance that the Json.NET library provides to us.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="demo" name="demo"></a><strong>Demo</strong></p>
<p>Let&#8217;s see it in action. I created a simple console application for this and stored some JSON data in a text file instead of directly contacting the StackExchange API.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">// Read JSON data</span>
var json = File.ReadAllText(<span class="str">"json.txt"</span>);
Console.WriteLine(json);
Console.WriteLine();

<span class="rem">// Deserialize JSON into ReputationChange object                        </span>
var reputation = JsonConvert.DeserializeObject&lt;ReputationChange&gt;(json);
Console.WriteLine(reputation.OnDate);
Console.WriteLine();</pre>
</div>
<p>The result:</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/jsonnet.png"><img src="http://cgeers.files.wordpress.com/2011/09/jsonnet.png?w=480&#038;h=157" alt="Deserializing Unix Time with Json.NET" title="Deserializing Unix Time with Json.NET" width="480" height="157" class="aligncenter size-full wp-image-3360" /></a></p>
<p>Let&#8217;s serialize the ReputationChange object back to a JSON string.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">// Serialize ReputationChange object back into JSON</span>
json = JsonConvert.SerializeObject(reputation);
Console.WriteLine(json);</pre>
</div>
<p>The result:</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/jsonnet2.png"><img src="http://cgeers.files.wordpress.com/2011/09/jsonnet2.png?w=480&#038;h=89" alt="Serializing DateTime to JSON" title="Serializing DateTime to JSON" width="480" height="89" class="aligncenter size-full wp-image-3363" /></a></p>
<p>Voila, thanks to the custom UnixDateTimeConverter converter you can easily deserialize a Unix timestamp into a DateTime and serialize it back to a JSON string. That about wraps up this short article. You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><strong>Tip</strong>: A good way to figure out how to write your own converter is to download the <a href="http://json.codeplex.com/" target="_blank">source code of the Json.NET library</a> from CodePlex. Just take a look at how the existing converters were written and start from there. And of course the <a href="http://james.newtonking.com/projects/json/help/" target="_blank">official documentation</a> will also help you out. </p>
<p>Have fun with serializing all the things!</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/serializeallthethings.jpg"><img src="http://cgeers.files.wordpress.com/2011/09/serializeallthethings.jpg?w=480" alt="Serialize All The Things" title="Serialize All The Things"   class="aligncenter size-full wp-image-3367" /></a></p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/json-net/'>Json.NET</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3327/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3327&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/09/25/writing-a-custom-json-net-datetime-converter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/json160.gif" medium="image">
			<media:title type="html">JSON</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/jsonnet.png" medium="image">
			<media:title type="html">Deserializing Unix Time with Json.NET</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/jsonnet2.png" medium="image">
			<media:title type="html">Serializing DateTime to JSON</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/serializeallthethings.jpg" medium="image">
			<media:title type="html">Serialize All The Things</media:title>
		</media:content>
	</item>
		<item>
		<title>Google Data API (GData)</title>
		<link>http://cgeers.com/2011/09/10/google-data-api-gdata/</link>
		<comments>http://cgeers.com/2011/09/10/google-data-api-gdata/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 13:29:49 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[GData]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Google Data API]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3254</guid>
		<description><![CDATA[Introduction Yesterday on StackOverflow I came across a question about using the Google Data API (also called GData) in .NET. Questions about it regularly pop up. Retrieving my Google data in .NET somehow seems appealing to me, but maybe that&#8217;s just me. I never worked with it before, so I took some time to experiment [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3254&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img src="http://cgeers.files.wordpress.com/2011/09/google1.png?w=480" alt="" title="Google"   class="alignright size-full wp-image-3257" /></p>
<p>Yesterday on <a href="http://stackoverflow.com/questions/7360736/c-google-gdata-client-read-email" target="_blank">StackOverflow</a> I came across a question about using the Google Data API (also called GData) in .NET. Questions about it regularly pop up. Retrieving my Google data in .NET somehow seems appealing to me, but maybe that&#8217;s just me. I never worked with it before, so I took some time to experiment with it a bit. Figured I&#8217;d better write it down, before I forget it again. This article is a quick introduction on using the Google Data API with the .NET Framework&#8230;so, let&#8217;s get started&#8230;</p>
<p><span id="more-3254"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#clientlibrary">Google Data .NET Client Library</a></li>
<li><a href="#projecttemplates">Project Templates</a></li>
<li><a href="#googletemplate">Google Project Template</a></li>
<li><a href="#types">Using The Client Library</a></li>
</ul>
<p><a title="clientlibrary" name="clientlibrary"></a><strong>Google Data .NET Client Library</strong></p>
<p>Google offers <a href="http://code.google.com/apis/gdata/faq.html#clientlibs" target="_blank">official client libraries</a> for GData for several programming languages such as Java, .NET, Phyton and Objective-C (they even have a partial library for JavaScript). So the first thing you have to do, is to download the .NET client library from code.google.com.</p>
<p>You can download the .NET client library (+/- 27.7 Mb) here:</p>
<p><a href="http://code.google.com/p/google-gdata/" target="_blank">http://code.google.com/p/google-gdata/</a></p>
<p>At the time of writing the most recent version is 1.9.0.0. Under the downloads section just select the MSI installation wizard package. Installing the SDK is really simple. Just click next three times and close once and you&#8217;re done.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/google2.png"><img src="http://cgeers.files.wordpress.com/2011/09/google2.png?w=480&#038;h=392" alt="Installing Google Data API SDK" title="Installing Google Data API SDK" width="480" height="392" class="aligncenter size-full wp-image-3271" /></a></p>
<p><img src="http://cgeers.files.wordpress.com/2011/09/nuget1.png?w=480" alt="NuGet" title="NuGet"   class="alignleft size-full wp-image-3297" /> <strong>Tip</strong>: Instead of installing the MSI install <a href="http://www.nuget.org" target="_blank">NuGet</a> instead and add a reference to the Google Data API packages. Google Inc. was kind enough to make them available as NuGet packages. Each assembly of the Google Data Client library has been put in a seperate package. <a href="http://www.nuget.org/List/Search?searchTerm=author%3A%20Google%2C%20Inc." target="_blank">You can view a list of these packages here</a>.</p>
<p><strong>Remark</strong>: If you don&#8217;t install the MSI you won&#8217;t get the Visual Studio project templates that come with it. The next two parts of this text discuss these templates, so if you want to follow along, it is best to download and install the MSI. You can always switch to the NuGet packages later.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="projecttemplates" name="projecttemplates"></a><strong>Project Templates</strong></p>
<p>Before you rush off and start Visual Studio 2010 you need to fix a small thing. Open Windows Explorer and navigate to the &#8220;My Documents&#8221; library and open the Visual Studio 2008 project templates folder. In this folder you&#8217;ll notice a new folder called &#8220;Google&#8221;, if you open it you&#8217;ll notice it contains seven new project templates.</p>
<p>My Documents &gt; Visual Studio 2008 &gt; Templates &gt; ProjectTemplates &gt; Visual C# &gt; Google</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/google3.png"><img src="http://cgeers.files.wordpress.com/2011/09/google3.png?w=480" alt="Project Templates" title="Project Templates"   class="aligncenter size-full wp-image-3278" /></a></p>
<p>Now you need to copy the Google folder over to the Visual Studio 2010 project templates folder (My Documents &gt; Visual Studio 2008 &gt; Templates &gt; ProjectTemplates &gt; Visual C# &amp;gt).</p>
<p>If you start Visual Studio 2010 now and create a new project you&#8217;ll notice that it contains the new Google project templates.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/google4.png"><img src="http://cgeers.files.wordpress.com/2011/09/google4.png?w=480&#038;h=325" alt="New Project - Google Project Templates" title="New Project - Google Project Templates" width="480" height="325" class="aligncenter size-full wp-image-3280" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="googletemplate" name="googletemplate"></a><strong>Google Project Template</strong></p>
<p>Let&#8217;s play around with one of the Google project templates. Create a new project and select the Google Contacts project template. Let&#8217;s be *original* and call it &#8220;Google Contacts&#8221;.</p>
<p>Most of the Google project templates contain the same structure. It&#8217;s a simple Windows Forms application that contains two forms. A login form and another one that displays the data (contacts, calender, photos&#8230;) you are querying.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/google5.png"><img src="http://cgeers.files.wordpress.com/2011/09/google5.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3284" /></a></p>
<p>If you start the application it will ask you to enter your Google account details.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/google6.png"><img src="http://cgeers.files.wordpress.com/2011/09/google6.png?w=480" alt="Google Client Login" title="Google Client Login"   class="aligncenter size-full wp-image-3287" /></a></p>
<p>After logging in it will display a simple form that lists the first 25 people found in your contacts list.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/google7.png"><img src="http://cgeers.files.wordpress.com/2011/09/google7.png?w=480" alt="Google Contacts" title="Google Contacts"   class="aligncenter size-full wp-image-3288" /></a></p>
<p><strong>Remark</strong>: I replaced the actual names in my contacts list for this demo. I don&#8217;t really know that many people named &#8220;John Smith&#8221;.</p>
<p>Feel free to explore the other Google Project Templates. They are all very similar.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="types" name="types"></a><strong>Using The Client Library</strong></p>
<p>Querying data with the Google Data API usually consists out of three steps:</p>
<ol>
<li>Setup a connection with the API (Google.GData.Client.Service)</li>
<li>Query the API (Google.GData.Contacts.ContactsQuery)</li>
<li>Iterate the returned data feed (Google.GData.Contacts.ContactsFeed)</li>
</ol>
<p>Let&#8217;s demonstrate how this is done by building a small console application that downloads the contacts just like Google&#8217;s own project template does.</p>
<p>Start up Visual Studio 2010, create a new blank solution called Google and add a new console application project called Contacts.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/google8.png"><img src="http://cgeers.files.wordpress.com/2011/09/google8.png?w=480" alt="Solution Explorer - Google Data API" title="Solution Explorer - Google Data API"   class="aligncenter size-full wp-image-3302" /></a></p>
<p>Add a reference to the following assemblies provided by the Google Data .NET Client library:</p>
<ul>
<li>Google.GData.Client.dll</li>
<li>Google.GData.Contacts.dll</li>
<li>Google.GData.Extensions.dll</li>
</ul>
<p>Or use NuGet to add a reference to the packages that contain these assemblies. The packages are named the same as the assemblies so you can&#8217;t miss them.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/google9.png"><img src="http://cgeers.files.wordpress.com/2011/09/google9.png?w=480&#038;h=320" alt="NuGet Package Manager" title="NuGet Package Manager" width="480" height="320" class="aligncenter size-full wp-image-3303" /></a></p>
<p>First create a new service instance and give it a name (doesn&#8217;t really matter how you name it).</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
Service service = <span class="kwrd">new</span> ContactsService(<span class="str">"My Contacts Application"</span>);</pre>
</div>
<p>Then you must request an authentication token.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
service.setUserCredentials(<span class="str">"your_email_address_here@gmail.com"</span>, <span class="str">"yourpassword"</span>);
var token = service.QueryClientLoginToken();
service.SetAuthenticationToken(token);</pre>
</div>
<p>After you&#8217;re authenticated you can compose a query to request the contact data.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var uri = ContactsQuery.CreateContactsUri(<span class="str">"your_email_address_here@gmail.com"</span>);
var query = <span class="kwrd">new</span> ContactsQuery(uri);</pre>
</div>
<p>Now you are ready to request the data.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
ContactsFeed feed = (ContactsFeed) service.Query(query);
<span class="kwrd">foreach</span>(ContactEntry contact <span class="kwrd">in</span> feed.Entries)
{
    Console.WriteLine(contact.Title.Text);
}</pre>
</div>
<p>The previous code sample requests the first 25 contacts and writes their names to the console output. The Google Data API automatically chunks your data into several pieces. Just check the feed&#8217;s NextChunk property to check if there is more data available. If there is, you can create and execute a new query to retrieve the next chunk of data.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">if</span> (!String.IsNullOrEmpty(feed.NextChunk))
{
    query = <span class="kwrd">new</span> ContactsQuery(feed.NextChunk);
    feed = (ContactsFeed) service.Query(query);
}</pre>
</div>
<p>Voila, you can now download your Google contact data. If you don&#8217;t want to copy/paste these code samples you can always download the source code from the download page. Just alter the code to make sure valid credentials are used. </p>
<p>That wraps it up. If you want to further explore the Google Data .NET Client library be sure to check out the help file (*.chm) which is installed if you use the MSI installation wizard. It contains information on all of the classes, members, constructors, properties&#8230;etc. that are available in the SDK. </p>
<p>Reference docs about the .NET client library are also available online. You can find them here:</p>
<p><a href="http://google-gdata.googlecode.com/svn/docs/Index.html" target="_blank">http://google-gdata.googlecode.com/svn/docs/Index.html</a></p>
<p>If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/gdata/'>GData</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3254/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3254&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/09/10/google-data-api-gdata/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google1.png" medium="image">
			<media:title type="html">Google</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google2.png" medium="image">
			<media:title type="html">Installing Google Data API SDK</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/nuget1.png" medium="image">
			<media:title type="html">NuGet</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google3.png" medium="image">
			<media:title type="html">Project Templates</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google4.png" medium="image">
			<media:title type="html">New Project - Google Project Templates</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google5.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google6.png" medium="image">
			<media:title type="html">Google Client Login</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google7.png" medium="image">
			<media:title type="html">Google Contacts</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google8.png" medium="image">
			<media:title type="html">Solution Explorer - Google Data API</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/google9.png" medium="image">
			<media:title type="html">NuGet Package Manager</media:title>
		</media:content>
	</item>
		<item>
		<title>Replacing the &#8220;You have created a service&#8221; message</title>
		<link>http://cgeers.com/2011/09/04/replacing-the-you-have-created-a-service-message/</link>
		<comments>http://cgeers.com/2011/09/04/replacing-the-you-have-created-a-service-message/#comments</comments>
		<pubDate>Sun, 04 Sep 2011 18:27:46 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3156</guid>
		<description><![CDATA[Introduction You all know the default page you get when you enter a WCF service&#8217;s URL in a browser (e.g. http://localhost/Service.svc). You are greeted by a blue and white (mostly white) screen that informs you that you have just created a service. (Sorry for the Dutch localization in the screenshot.) So apart from informing you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3156&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><img class="alignnone size-medium wp-image-24 alignright" style="float:right;" src="http://cgeers.files.wordpress.com/2008/04/dotnetwcf.gif?w=80&#038;h=80" alt="" width="80" height="80" /></p>
<p>You all know the default page you get when you enter a WCF service&#8217;s URL in a browser (e.g. http://localhost/Service.svc). You are greeted by a blue and white (mostly white) screen that informs you that you have just created a service.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/wcf11.png"><img src="http://cgeers.files.wordpress.com/2011/09/wcf11.png?w=480" alt="You have created a service" title="You have created a service"   class="aligncenter size-full wp-image-3198" /></a></p>
<p>(Sorry for the Dutch localization in the screenshot.)</p>
<p>So apart from informing you that you have created a service (handy if you suffer from alzheimer), it also tells you where you can find the WSDL (just append ?wsdl), how to generate proxy classes and how to use these proxies.</p>
<p>That&#8217;s all fine, but you know all of this stuff already. Besides, you don&#8217;t want to display this message on public-facing services. Time to get rid of it.</p>
<p><span id="more-3156"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#helloworld">Hello, World!</a></li>
<li><a href="#servicemetadata">Service Metadata</a></li>
<li><a href="#unmatched">Unmatched Message Handler</a></li>
<li><a href="#landingpage">Custom Landing Page</a></li>
<li><a href="#servicehost">Service Host</a></li>
<li><a href="#contenttype">Content Type</a></li>
<li><a href="#customization">Further Customization</a></li>
</ul>
<p><a title="helloworld" name="helloworld"></a><strong>Hello, World!</strong></p>
<p>Instead of the default generated landing page which is displayed when you enter the service&#8217;s address in a browser I want to display a custom page. To showcase the custom page I created a simple &#8220;Hello, World!&#8221;-isch service.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[ServiceContract]
<span class="kwrd">public</span> <span class="kwrd">interface</span> IHelloWorld
{
    [OperationContract]
    <span class="kwrd">string</span> SayHi(<span class="kwrd">string</span> name);
}</pre>
</div>
<p>The service&#8217;s implementation could not be any simpler.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> HelloWorld : IHelloWorld
{
    <span class="kwrd">public</span> <span class="kwrd">string</span> SayHi(<span class="kwrd">string</span> name)
    {
        <span class="kwrd">return</span> String.Format(<span class="str">"Hello, {0}."</span>, name);
    }
}</pre>
</div>
<p>Let&#8217;s add some configuration to the application&#8217;s configuration file (Web.config / app.config).</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">system.serviceModel</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">services</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">service</span> <span class="attr">name</span><span class="kwrd">="WcfServiceLibrary.HelloWorld"</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">endpoint</span> <span class="attr">address</span><span class="kwrd">="HelloWorld"</span>
                <span class="attr">binding</span><span class="kwrd">="basicHttpBinding"</span>
                <span class="attr">contract</span><span class="kwrd">="WcfServiceLibrary.IHelloWorld"</span><span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">endpoint</span> <span class="attr">address</span><span class="kwrd">="mex"</span>
                <span class="attr">binding</span><span class="kwrd">="mexHttpBinding"</span>
                <span class="attr">contract</span><span class="kwrd">="IMetadataExchange"</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">host</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">baseAddresses</span><span class="kwrd">&gt;</span>
          <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">baseAddress</span><span class="kwrd">="http://localhost:8732/Service"</span><span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">baseAddresses</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">host</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">service</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">services</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">behaviors</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">serviceBehaviors</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">behavior</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">serviceMetadata</span> <span class="attr">httpGetEnabled</span><span class="kwrd">="true"</span><span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">serviceDebug</span> <span class="attr">includeExceptionDetailInFaults</span><span class="kwrd">="false"</span><span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">behavior</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">serviceBehaviors</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">behaviors</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">system.serviceModel</span><span class="kwrd">&gt;</span></pre>
</div>
<p>If you navigate to the service&#8217;s address (http://localhost:8732/HelloWorld/) you get the default landing page.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/wcf2.png"><img src="http://cgeers.files.wordpress.com/2011/09/wcf2.png?w=480&#038;h=435" alt="WCF Service - Default Landing Page" title="WCF Service - Default Landing Page" width="480" height="435" class="aligncenter size-full wp-image-3194" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="servicemetadata" name="servicemetadata"></a><strong>Service Metadata</strong></p>
<p>Let&#8217;s stop exposing the metadata first. Just set the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicemetadatabehavior.httpgetenabled.aspx" target="_blank">httpGetEnabled property</a> of your service behavior to false.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">configuration</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">system.serviceModel</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">behaviors</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">serviceBehaviors</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">behavior</span> <span class="attr">name</span><span class="kwrd">="..."</span><span class="kwrd">&gt;</span>
          <span class="kwrd">&lt;</span><span class="html">serviceMetadata</span> <span class="attr">httpGetEnabled</span><span class="kwrd">="true"</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">behavior</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">serviceBehaviors</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">behaviors</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">system.serviceModel</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">configuration</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Well, that was easy. If you navigate to the address&#8217; URL now, you&#8217;ll still see the same page, but this time no URL pointing to the service&#8217;s WSDL. &#8220;Ha&#8230;I&#8217;ll manually append &#8216;?wsdl&#8217; to the URL&#8221; you say? Try it, you&#8217;ll get a blank page and nothing more. While you are it, at also remove the metadata exchange (mex) endpoint from the service.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="unmatched" name="unmatched"></a><strong>Unmatched Message Handler</strong></p>
<p>Let&#8217;s create a custom landing page. To do so, you need to create a new service contract called ILandingPage.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[ServiceContract]
<span class="kwrd">public</span> <span class="kwrd">interface</span> ILandingPage
{
    [OperationContract(Action=<span class="str">"*"</span>, ReplyAction=<span class="str">"*"</span>)]
    Message Index();
}</pre>
</div>
<p>This service operation handles all messages that cannot be directed to a service operation. This is done by specifying an asterisk (*) as the value for the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.action.aspx" target="_blank">Action property</a> of the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.aspx" target="_blank">OperationContract attribute</a>. </p>
<p>This is also called an unmatched message handler. One of the conditions is that it can only take a parameter of the type Message and either returns void or also an instance of the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.message.aspx" target="_blank">Message type</a>. Here we&#8217;re only interested in the return message which represents the custom landing page.</p>
<p>The implementation for this new service contract is quite simple. Just have the service for which you want to create a custom landing page implement it.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> HelloWorld : IHelloWorld, ILandingPage
{
    <span class="rem">//...</span>

    <span class="kwrd">public</span> Message Index()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> LandigePageMessage();
    }
}</pre>
</div>
<p>Just have it return a new descendant of the Message type which represents your custom landing page. In this case I called it LandingPageMessage.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="landingpage" name="landingpage"></a><strong>Custom Landing Page</strong></p>
<p>Time to create the custom Message descendant for the custom landing page.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> LandingPageMessage: Message
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> MessageHeaders _headers;
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> MessageProperties _properties;

    <span class="kwrd">public</span> LandigePageMessage()
    {
        <span class="kwrd">this</span>._headers = <span class="kwrd">new</span> MessageHeaders(MessageVersion.None);
        <span class="kwrd">this</span>._properties = <span class="kwrd">new</span> MessageProperties();
    }

    <span class="kwrd">public</span> <span class="kwrd">override</span> MessageHeaders Headers
    {
        get { <span class="kwrd">return</span> <span class="kwrd">this</span>._headers; }
    }

    <span class="kwrd">public</span> <span class="kwrd">override</span> MessageProperties Properties
    {
        get { <span class="kwrd">return</span> <span class="kwrd">this</span>._properties; }
    }

    <span class="kwrd">public</span> <span class="kwrd">override</span> MessageVersion Version
    {
        get { <span class="kwrd">return</span> <span class="kwrd">this</span>._headers.MessageVersion; }
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        writer.WriteStartElement(<span class="str">"HTML"</span>);
        writer.WriteStartElement(<span class="str">"HEAD"</span>);
        writer.WriteStartElement(<span class="str">"BODY"</span>);
        writer.WriteStartElement(<span class="str">"SPAN"</span>);
        writer.WriteString(<span class="str">"This is a test page."</span>);
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndElement();
    }
}</pre>
</div>
<p>The new LandingPageMessage type implements all of the abstract members of the Message type. This is quite straightforward. Only the OnWriteBodyContents(&#8230;) method contains a bit of logic. Here you can generate some HTML output using the <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmldictionarywriter.aspx" target="_blank">XmlDictionaryWriter</a> object which is passed into this method.</p>
<p>Time to update the application&#8217;s configuration file. First add a new endpoint to the service.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">service</span> <span class="attr">name</span><span class="kwrd">="WcfServiceLibrary.HelloWorld"</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">endpoint</span> <span class="attr">address</span><span class="kwrd">="HelloWorld"</span>
            <span class="attr">binding</span><span class="kwrd">="basicHttpBinding"</span>
            <span class="attr">contract</span><span class="kwrd">="WcfServiceLibrary.IHelloWorld"</span><span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">endpoint</span> <span class="attr">address</span><span class="kwrd">=""</span>
            <span class="attr">binding</span><span class="kwrd">="customBinding"</span>
            <span class="attr">bindingConfiguration</span><span class="kwrd">="landingPage"</span>
            <span class="attr">contract</span><span class="kwrd">="WcfServiceLibrary.ILandingPage"</span><span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">host</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">baseAddresses</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">baseAddress</span><span class="kwrd">="http://localhost:8732/Service"</span><span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">baseAddresses</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">host</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">service</span><span class="kwrd">&gt;</span></pre>
</div>
<p>As you can see the new endpoint uses a custom binding, which is declared as follows:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">bindings</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">customBinding</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">binding</span> <span class="attr">name</span><span class="kwrd">="landingPage"</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">textMessageEncoding</span> <span class="attr">messageVersion</span><span class="kwrd">="None"</span><span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">httpTransport</span><span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">binding</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">customBinding</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">bindings</span><span class="kwrd">&gt;</span></pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="servicehost" name="servicehost"></a><strong>Service Host</strong></p>
<p>To test the &#8220;Hello, World!&#8221; service I quickly created a console application to act as the service host. Apart from an application configuration file (App.config) which contains the configuration code listed so far, it only contains the following lines of code:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">class</span> Program
{
    <span class="kwrd">static</span> <span class="kwrd">void</span> Main()
    {
        var service = <span class="kwrd">new</span> ServiceHost(<span class="kwrd">typeof</span> (HelloWorld));
        service.Description.Behaviors.Remove&lt;ServiceDebugBehavior&gt;();
        service.Open();

        Console.WriteLine(<span class="str">"Service started."</span>);
        Console.ReadKey();
    }
}</pre>
</div>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicedebugbehavior.aspx" target="_blank">ServiceDebugBehavior</a> is removed from the behaviors of the service to ensure the custom page will be shown.</p>
<p>After you start the host application and open the service&#8217;s URL (http://localhost:8732/Service) in a browser you&#8217;ll get the following page instead: </p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/wcf3.png"><img src="http://cgeers.files.wordpress.com/2011/09/wcf3.png?w=480&#038;h=114" alt="Custom Landing Page" title="Custom Landing Page" width="480" height="114" class="aligncenter size-full wp-image-3227" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="contenttype" name="contenttype"></a><strong>Content Type</strong></p>
<p>Hrm, why is the custom landing page being treated as an XML document? Let&#8217;s open the page in FireFox and see what FireBug has to tell.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/wcf4.png"><img src="http://cgeers.files.wordpress.com/2011/09/wcf4.png?w=480" alt="FireBug - Response Headers" title="FireBug - Response Headers"   class="aligncenter size-full wp-image-3230" /></a></p>
<p>The content type is &#8220;application/xml; charset=utf-8&#8243;? That&#8217;s not right. Luckily this can easily be fixed using the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.aspx" target="_blank">WebOperationContext</a> helper class. Add a reference to the System.ServiceModel.Web assembly for the project which contains your service and update the implementation of ILandingPage&#8217;s Index method as shown in the following code sample:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> Message Index()
{
    var context = WebOperationContext.Current;
    context.OutgoingResponse.ContentType = <span class="str">"text/html"</span>;
    <span class="kwrd">return</span> <span class="kwrd">new</span> LandingPageMessage();
}</pre>
</div>
<p>Restart the host application and refresh your browser. Now the landing page will be shown correctly because you specified &#8220;text/html&#8221; as the content type instead of defaulting to &#8220;application/xml&#8221;.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/wcf5.png"><img src="http://cgeers.files.wordpress.com/2011/09/wcf5.png?w=480" alt="Correct Landing Page" title="Correct Landing Page"   class="aligncenter size-full wp-image-3235" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="customization" name="customization"></a><strong>Further Customization</strong></p>
<p>Personally I don&#8217;t want to create a HTML page by building it in code using a XmlDictionaryWriter object. Notepad should be enough. So let&#8217;s do just that. Open Notepad and create a simple HTML page.</p>
<p>For example:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">html</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">head</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">title</span><span class="kwrd">&gt;&lt;/</span><span class="html">title</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">head</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">body</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">style</span><span class="kwrd">="background-color: yellow; border: 1px solid black;"</span><span class="kwrd">&gt;</span>
      This is a test.
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">body</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">html</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Save the HTML file (e.g. Default.htm) and add it to the project which contains your WCF service. </p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/wcf6.png"><img src="http://cgeers.files.wordpress.com/2011/09/wcf6.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3240" /></a></p>
<p>Be sure to set its &#8220;Copy to Output Directory&#8221; property to &#8220;Copy Always&#8221;.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/wcf7.png"><img src="http://cgeers.files.wordpress.com/2011/09/wcf7.png?w=480" alt="Copy to Output Directory" title="Copy to Output Directory"   class="aligncenter size-full wp-image-3242" /></a></p>
<p>Next its time to refactor the OnWriteBodyContents(&#8230;) method of the CustomLandingPage type. Just replace the existing code with the following lines of code:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnWriteBodyContents(XmlDictionaryWriter writer)
{
    var document = <span class="kwrd">new</span> HtmlDocument();
    document.Load(<span class="str">"Default.htm"</span>);

    var bodyNode = document.DocumentNode.SelectSingleNode(<span class="str">"//html"</span>);
    writer.WriteStartElement(<span class="str">"HTML"</span>);
    writer.WriteRaw(bodyNode.InnerHtml);
    writer.WriteEndElement();
}</pre>
</div>
<p>Here the HTML document which you created earlier is parsed and its contents are being written to the XmlDictionaryWriter object. If you restart the host application once more and visit the service&#8217;s base URL in a browser you&#8217;ll see that your custom HTML page will be displayed.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/09/wcf8.png"><img src="http://cgeers.files.wordpress.com/2011/09/wcf8.png?w=480" alt="Custom Landing Page" title="Custom Landing Page"   class="aligncenter size-full wp-image-3245" /></a></p>
<p><strong>Remark</strong>: In order to parse the HTML document I used the <a href="http://htmlagilitypack.codeplex.com/" target="_blank">HTML Agility Pack</a> which can be downloaded from CodePlex or <a href="http://nuget.org/List/Packages/HtmlAgilityPack" target="_blank">NuGet</a>.</p>
<p>That about wraps it up. Hope you enjoyed the article. You can download the source code accompanying this article from the <a href="http://cgeers.com/download/" target="_blank">download page</a>. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>, <a href='http://cgeers.com/category/programming/wcf/'>WCF</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/3156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3156/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3156/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3156/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3156&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/09/04/replacing-the-you-have-created-a-service-message/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2008/04/dotnetwcf.gif" medium="image" />

		<media:content url="http://cgeers.files.wordpress.com/2011/09/wcf11.png" medium="image">
			<media:title type="html">You have created a service</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/wcf2.png" medium="image">
			<media:title type="html">WCF Service - Default Landing Page</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/wcf3.png" medium="image">
			<media:title type="html">Custom Landing Page</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/wcf4.png" medium="image">
			<media:title type="html">FireBug - Response Headers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/wcf5.png" medium="image">
			<media:title type="html">Correct Landing Page</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/wcf6.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/wcf7.png" medium="image">
			<media:title type="html">Copy to Output Directory</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/09/wcf8.png" medium="image">
			<media:title type="html">Custom Landing Page</media:title>
		</media:content>
	</item>
		<item>
		<title>Web.config Transformation Using TeamCity</title>
		<link>http://cgeers.com/2011/08/21/web-config-transformation-using-teamcity/</link>
		<comments>http://cgeers.com/2011/08/21/web-config-transformation-using-teamcity/#comments</comments>
		<pubDate>Sun, 21 Aug 2011 19:52:03 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[TeamCity]]></category>
		<category><![CDATA[MSBuild Script]]></category>
		<category><![CDATA[Web.Config Transformation]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=2988</guid>
		<description><![CDATA[Introduction In the previous parts of the TeamCity series I discussed how you can configure the TeamCity CI build server to run unit tests and how you can make this all happen using a MSBuild script. The end goal of this series is to arrive at a build configuration which we can use to automatically [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=2988&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2011/05/teamcity.png"><img src="http://cgeers.files.wordpress.com/2011/05/teamcity.png?w=480" alt="JetBrains TeamCity" title="JetBrains TeamCity"   class="alignright size-full wp-image-2709" /></a></p>
<p>In the previous parts of the <em>TeamCity series</em> I discussed how you can configure the TeamCity <a href="http://en.wikipedia.org/wiki/Continuous_integration" target="_blank">CI</a> build server to <a href="http://cgeers.com/2011/05/28/running-unit-tests-with-teamcity" target="_blank">run unit tests</a> and how you can make this all happen using a <a href="http://cgeers.com/2011/06/04/using-a-msbuild-script-in-teamcity" target="_blank">MSBuild script</a>. </p>
<p>The end goal of this series is to arrive at a build configuration which we can use to automatically deploy an ASP.NET MVC web application. We want a reliable way of deploying an application to a new environment (staging, acceptance, production&#8230;etc.). Manually copying files, editing configuration files, synchronizing servers&#8230;is not a wise course.</p>
<p>You <del datetime="2011-08-20T17:00:57+00:00">want to</del> should avoid manual actions during deployment. Sure, you can get all the steps correct, but in the long run mistakes are unavoidable. And besides, doing all this stuff manually is just plain boring and tedious.</p>
<p>One of the first steps in deploying an ASP.NET / ASP.NET MVC application is to make sure its configuration file (Web.config) is transformed so it fits the environment in which the application will be running. Let&#8217;s see how we can apply <a href="http://msdn.microsoft.com/en-us/library/dd465318.aspx" target="_blank">Web.config transformation</a> using TeamCity.</p>
<p><span id="more-2988"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#demo">Demo Web Application</a></li>
<li><a href="#transformation">The Transformation</a></li>
<li><a href="#buildconfiguration">Basic Build Configuration</a></li>
<li><a href="#target">Deploy Target</a></li>
<li><a href="#transform">Transform Target</a></li>
</ul>
<p><a title="demo" name="demo"></a><strong>Demo Web Application</strong></p>
<p>For testing purposes I created a small ASP.NET MVC 3 web application. The application contains a single web page which allows me to query a list of persons by their last name.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/08/teamcity.png"><img src="http://cgeers.files.wordpress.com/2011/08/teamcity.png?w=480&#038;h=228" alt="MVC 3 Web Application" title="MVC 3 Web Application" width="480" height="228" class="aligncenter size-full wp-image-3109" /></a></p>
<p>It contains a single (local) database which contains one lonely table, namely [Person]. If you don&#8217;t want to create your own sample project, you can download it <a href="http://cgeers.com/download/" target="_blank">here</a>.</p>
<p>The solution in which this project is contained also contains a project to house the unit tests. It only contains one test (NUnit), which tests nothing in particular (Hey, it&#8217;s a demo.). </p>
<p><a href="http://cgeers.files.wordpress.com/2011/08/teamcity2.png"><img src="http://cgeers.files.wordpress.com/2011/08/teamcity2.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3114" /></a></p>
<p>This project was only created to demonstrate that we can create a build configuration which performs:</p>
<ul>
<li>Compilation</li>
<li>Runs unit tests</li>
<li>Transforms configuration files (Web.config)</li>
</ul>
<p><a href="#top">Top of page</a></p>
<p><a title="transformation" name="transformation"></a><strong>The Transformation</strong></p>
<p>The development Web.config file contains a couple of items I want to replace when I create a release build via TeamCity, namely:</p>
<ul>
<li>The debug attribute of the <a href="http://msdn.microsoft.com/en-us/library/s10awwz0.aspx" target="_blank">compilation element</a> must be removed. I want to compile release binaries instead of debug binaries.</li>
<li>I want to replace the application settings.</li>
<li>The connection string(s) must point to another database server, instead of my local development database.</li>
</ul>
<p>A Web.config transformation file for the release build (Web.Release.config) is added to a new ASP.NET MVC project by default. You can add as many transformation files as there are configurations for your project (debug, release&#8230;etc.).</p>
<p><a href="http://cgeers.files.wordpress.com/2011/08/teamcity3.png"><img src="http://cgeers.files.wordpress.com/2011/08/teamcity3.png?w=480" alt="" title="teamcity3"   class="aligncenter size-full wp-image-3126" /></a></p>
<p>I added the following contents to the Web.Release.config transform file which specifies how the Web.config file should be changed when it is deployed. It&#8217;s quite straightforward to read. </p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;?</span><span class="html">xml</span> <span class="attr">version</span><span class="kwrd">="1.0"</span>?<span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">configuration</span> <span class="attr">xmlns:xdt</span><span class="kwrd">="http://schemas.microsoft.com/XML-Document-Transform"</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">system.web</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">compilation</span> <span class="attr">xdt:Transform</span><span class="kwrd">="RemoveAttributes(debug)"</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">system.web</span><span class="kwrd">&gt;</span>

  <span class="kwrd">&lt;</span><span class="html">appSettings</span> <span class="attr">xdt:Transform</span><span class="kwrd">="Replace"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">key</span><span class="kwrd">="webpages:Version"</span> <span class="attr">value</span><span class="kwrd">="2.0.0.0"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">key</span><span class="kwrd">="ClientValidationEnabled"</span> <span class="attr">value</span><span class="kwrd">="false"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">key</span><span class="kwrd">="UnobtrusiveJavaScriptEnabled"</span> <span class="attr">value</span><span class="kwrd">="false"</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">appSettings</span><span class="kwrd">&gt;</span>

  <span class="kwrd">&lt;</span><span class="html">connectionStrings</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">xdt:Transform</span><span class="kwrd">="SetAttributes"</span> <span class="attr">xdt:Locator</span><span class="kwrd">="Match(name)"</span>
         <span class="attr">name</span><span class="kwrd">="DatabaseEntities"</span>
         <span class="attr">connectionString</span><span class="kwrd">="The production connection string goes here."</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">connectionStrings</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">configuration</span><span class="kwrd">&gt;</span></pre>
</div>
<p>You can clearly see that it removes the debug attribute from the compilation element, replaces the appSettings node and replaces the connectionString attribute of the connection string named &#8220;DatabaseEntities&#8221;. </p>
<p>More information on Web.config transformation syntax can be found here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/dd465326.aspx</a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="buildconfiguration" name="buildconfiguration"></a><strong>Basic Build Configuration</strong></p>
<p>Now that we have the sample project setup and the Web.Release.config has been created, we can commence to create a build configuration in TeamCity that automatically transforms the configuration.</p>
<p>Let&#8217;s first setup the project and a basic build configuration that compiles a release build and runs our unit tests. To do so create a new build configuration in TeamCity which contains a single build step. I&#8217;ll quickly go over this as this is explained in the previous two articles of this series. </p>
<ul>
<li><a href="http://cgeers.com/2011/05/28/running-unit-tests-with-teamcity/" target="_blank">Part 1: Running Unit Tests With TeamCity</a></li>
<li><a href="http://cgeers.com/2011/06/04/using-a-msbuild-script-in-teamcity/" target="_blank">Part 2: Using a MSBuild Script in TeamCity</a></li>
</ul>
<p>This build step executes a <a href="http://msdn.microsoft.com/en-us/library/wea2sca5(VS.90).aspx" target="_blank">MSBuild script</a>. The contents of the MSBuild script are displayed below.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">Project</span> <span class="attr">xmlns</span><span class="kwrd">="http://schemas.microsoft.com/developer/msbuild/2003"</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">PropertyGroup</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">WorkingFolder</span><span class="kwrd">&gt;</span>$(MSBuildProjectDirectory)<span class="kwrd">&lt;/</span><span class="html">WorkingFolder</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Configuration</span><span class="kwrd">&gt;</span>Release<span class="kwrd">&lt;/</span><span class="html">Configuration</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">SolutionFile</span><span class="kwrd">&gt;</span>PeopleFinder.sln<span class="kwrd">&lt;/</span><span class="html">SolutionFile</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">NUnitPath</span><span class="kwrd">&gt;</span>$(WorkingFolder)\packages\NUnit.2.5.10.11092\tools<span class="kwrd">&lt;/</span><span class="html">NUnitPath</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">PropertyGroup</span><span class="kwrd">&gt;</span>  

  <span class="kwrd">&lt;</span><span class="html">Target</span> <span class="attr">Name</span><span class="kwrd">="BuildAll"</span> <span class="attr">DependsOnTargets</span><span class="kwrd">="Compile;Test;"</span> <span class="kwrd">/&gt;</span>  

  <span class="kwrd">&lt;</span><span class="html">Target</span> <span class="attr">Name</span><span class="kwrd">="Compile"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Message</span> <span class="attr">Text</span><span class="kwrd">="=== COMPILING $(Configuration) configuration ==="</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">MSBuild</span> <span class="attr">Projects</span><span class="kwrd">="$(SolutionFile)"</span>
             <span class="attr">Properties</span><span class="kwrd">="Configuration=$(Configuration)"</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Target</span><span class="kwrd">&gt;</span>  

  <span class="kwrd">&lt;</span><span class="html">Target</span> <span class="attr">Name</span><span class="kwrd">="Test"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">ItemGroup</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">TestAssemblies</span>
        <span class="attr">Include</span><span class="kwrd">="**\*.Tests.dll"</span>
        <span class="attr">Exclude</span><span class="kwrd">="**\obj\**;**\packages\NUnit.2.5.10.11092\**"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">ItemGroup</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">Message</span> <span class="attr">Text</span><span class="kwrd">="=== RUNNING UNIT TESTS ==="</span><span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">NUnit</span> <span class="attr">Assemblies</span><span class="kwrd">="@(TestAssemblies)"</span> <span class="attr">ToolPath</span><span class="kwrd">="$(NUnitPath)"</span>
          <span class="attr">DisableShadowCopy</span><span class="kwrd">="true"</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Target</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Project</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Make sure that your build step (runner type: MSBuild) executes the target &#8220;BuildAll&#8221;. This target executes the targets <u>Compile</u> and <u>Test</u>. The Compile target creates a release build and the Test target executes the unit tests.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/08/teamcity4.png"><img src="http://cgeers.files.wordpress.com/2011/08/teamcity4.png?w=480&#038;h=362" alt="TeamCity - Build Step" title="TeamCity - Build Step" width="480" height="362" class="aligncenter size-full wp-image-3134" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="target" name="target"></a><strong>Deploy Target</strong></p>
<p>Let&#8217;s add a new target to the MSBuild script called &#8220;Deploy&#8221;. Append the target to the end of the &#8220;DependsOnTargets&#8221; attribute of the &#8220;BuildAll&#8221; target.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">Project</span> <span class="attr">xmlns</span><span class="kwrd">="http://schemas.microsoft.com/developer/msbuild/2003"</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">PropertyGroup</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- ...other properties... --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">DeployPath</span><span class="kwrd">&gt;</span>C:\Projects\build\PeopleFinder<span class="kwrd">&lt;/</span><span class="html">DeployPath</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">PropertyGroup</span><span class="kwrd">&gt;</span>  

  <span class="kwrd">&lt;</span><span class="html">Target</span> <span class="attr">Name</span><span class="kwrd">="BuildAll"</span> <span class="attr">DependsOnTargets</span><span class="kwrd">="Compile;Test;Deploy;"</span> <span class="kwrd">/&gt;</span>  

  <span class="rem">&lt;!-- ...other targets... --&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Target</span> <span class="attr">Name</span><span class="kwrd">="Deploy"</span><span class="kwrd">&gt;</span>
     <span class="kwrd">&lt;</span><span class="html">Message</span> <span class="attr">Text</span><span class="kwrd">="=== DEPLOY LATEST BUILD to $(DeployPath) ==="</span> <span class="kwrd">/&gt;</span>

     <span class="kwrd">&lt;</span><span class="html">RemoveDir</span> <span class="attr">Directories</span><span class="kwrd">="$((DeployPath)"</span> <span class="kwrd">/&gt;</span>
     <span class="kwrd">&lt;</span><span class="html">MakeDir</span> <span class="attr">Directories</span><span class="kwrd">="$(DeployPath)"</span><span class="kwrd">/&gt;</span>

     <span class="kwrd">&lt;</span><span class="html">ItemGroup</span><span class="kwrd">&gt;</span>
       <span class="kwrd">&lt;</span><span class="html">DeployWebFiles</span> <span class="attr">Include</span><span class="kwrd">="PeopleFinder.UI.Web\**\*.*"</span>
                       <span class="attr">Exclude</span><span class="kwrd">="**\*.cs;**\*.csproj;**\*.user;**\obj\**;**\.svn\**;**\*.pdb;"</span> <span class="kwrd">/&gt;</span>
     <span class="kwrd">&lt;/</span><span class="html">ItemGroup</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">Copy</span> <span class="attr">SourceFiles</span><span class="kwrd">="@(DeployWebFiles)"</span>
          <span class="attr">DestinationFiles</span>="@(<span class="attr">DeployWebFiles-</span><span class="kwrd">&gt;</span>'$(DeployPath)\%(RecursiveDir)%(Filename)%(Extension)')" <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Target</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Project</span><span class="kwrd">&gt;</span></pre>
</div>
<p>This new target is responsible for copying the compiled output to a new location ($DeployPath). After you check in the new build file and run the build configuration the Deploy target will copy the compiled output to the directory specified by the $DeployPath property.</p>
<p><a href="http://cgeers.files.wordpress.com/2011/08/teamcity5.png"><img src="http://cgeers.files.wordpress.com/2011/08/teamcity5.png?w=480" alt="Deploy Target Output" title="Deploy Target Output"   class="aligncenter size-full wp-image-3141" /></a></p>
<p>Hrmm, there are still some files in there we are not interested in. Let&#8217;s expand the Exclude attribute of the DeployWebFiles item group.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">DeployWebFiles</span> <span class="attr">Include</span><span class="kwrd">="PeopleFinder.UI.Web\**\*.*"</span>
<span class="attr">Exclude</span><span class="kwrd">="**\*.cs;**\*.csproj;**\*.user;**\obj\**;
         **\.svn\**;**\*.pdb;**\*.edmx;**\packages.config;**\Web.*.config"</span> <span class="kwrd">/&gt;</span>  </pre>
</div>
<p><a href="http://cgeers.files.wordpress.com/2011/08/teamcity6.png"><img src="http://cgeers.files.wordpress.com/2011/08/teamcity6.png?w=480" alt="Deploy Target Output" title="Deploy Target Output"   class="aligncenter size-full wp-image-3144" /></a></p>
<p>That&#8217;s better.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="transform" name="transform"></a><strong>Transform Target</strong></p>
<p>At the moment the MSBuild script compiles the project, runs the unit tests and copies the output to a separate directory ($DeployPath). If you open the Web.config file which resides in this directory you&#8217;ll notice that it is a copy of the development version. The release transformation hasn&#8217;t been applied yet. Time to fix this.</p>
<p>To do so, we need to add another target to the script. For readability&#8217;s sake, I introduced some extra line breaks.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">Project</span> <span class="attr">xmlns</span><span class="kwrd">="http://schemas.microsoft.com/developer/msbuild/2003"</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">PropertyGroup</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- ...other properties... --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">TransformInputFile</span><span class="kwrd">&gt;</span>PeopleFinder.UI.Web\Web.config<span class="kwrd">&lt;/</span><span class="html">TransformInputFile</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">TransformFile</span><span class="kwrd">&gt;</span>PeopleFinder.UI.Web\Web.$(Configuration).config<span class="kwrd">&lt;/</span><span class="html">TransformFile</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">TransformOutputFile</span><span class="kwrd">&gt;</span>$(DeployPath)\Web.config<span class="kwrd">&lt;/</span><span class="html">TransformOutputFile</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">PropertyGroup</span><span class="kwrd">&gt;</span>  

  <span class="kwrd">&lt;</span><span class="html">UsingTask</span> <span class="attr">TaskName</span><span class="kwrd">="TransformXml"</span>
             <span class="attr">AssemblyFile</span><span class="kwrd">="$(MSBuildExtensionsPath)\Microsoft\
                           VisualStudio\v10.0\Web\
                           Microsoft.Web.Publishing.Tasks.dll"</span><span class="kwrd">/&gt;</span>

  <span class="kwrd">&lt;</span><span class="html">Target</span> <span class="attr">Name</span><span class="kwrd">="BuildAll"</span> <span class="attr">DependsOnTargets</span><span class="kwrd">="Compile;Test;Deploy;Transform"</span> <span class="kwrd">/&gt;</span>  

  <span class="rem">&lt;!-- ...other targets... --&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Target</span> <span class="attr">Name</span><span class="kwrd">="Transform"</span><span class="kwrd">&gt;</span>
     <span class="kwrd">&lt;</span><span class="html">Message</span> <span class="attr">Text</span><span class="kwrd">="=== TRANSFER THE CONFIGURATION FILE ==="</span> <span class="kwrd">/&gt;</span>
     <span class="kwrd">&lt;</span><span class="html">TransformXml</span> <span class="attr">Source</span><span class="kwrd">="$(TransformInputFile)"</span>
                   <span class="attr">Transform</span><span class="kwrd">="$(TransformFile)"</span>
                   <span class="attr">Destination</span><span class="kwrd">="$(TransformOutputFile)"</span> <span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Target</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Project</span><span class="kwrd">&gt;</span></pre>
</div>
<p>The BuildAll target now executes the targets Compile, Test, Deploy &amp; Transform. After the output has been copied to the $(DeployPath) the Transform target applies the release (Web.$(Configuration).config) transformation to the Web.config file. </p>
<p>If run the build configuration now you&#8217;ll notice that the Web.config has successfully been updated and now contains the correct settings. No more boring manual editing.</p>
<p><strong>Remark</strong>: Please note that you need to add an <a href="http://msdn.microsoft.com/en-us/library/t41tzex2.aspx" target="_blank">UsingTask element</a> to the MSBuild script to reference the TransformXml task whose implementation is contained in the Microsoft.Web.Publishing.Task.dll assembly.</p>
<p>That wraps it up for applying Web.config transformations via TeamCity using a MSBuild script. You can find the sample project for this article on the <a href="http://cgeers.com/download/" target="_blank">download page</a> of this blog. If you have any questions, suggestions&#8230;etc. please feel free to leave a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/asp-net-mvc/'>ASP.NET MVC</a>, <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/continuous-integration/'>Continuous Integration</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>, <a href='http://cgeers.com/category/programming/teamcity/'>TeamCity</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/2988/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/2988/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/2988/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/2988/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/2988/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/2988/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/2988/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/2988/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/2988/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/2988/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/2988/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/2988/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/2988/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/2988/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=2988&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2011/08/21/web-config-transformation-using-teamcity/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/05/teamcity.png" medium="image">
			<media:title type="html">JetBrains TeamCity</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/08/teamcity.png" medium="image">
			<media:title type="html">MVC 3 Web Application</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/08/teamcity2.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/08/teamcity3.png" medium="image">
			<media:title type="html">teamcity3</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/08/teamcity4.png" medium="image">
			<media:title type="html">TeamCity - Build Step</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/08/teamcity5.png" medium="image">
			<media:title type="html">Deploy Target Output</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2011/08/teamcity6.png" medium="image">
			<media:title type="html">Deploy Target Output</media:title>
		</media:content>
	</item>
	</channel>
</rss>
