<?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>Fri, 24 Feb 2012 04:48:27 +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 3: Create, Delete and Move Folders</title>
		<link>http://cgeers.com/2012/02/19/dropbox-rest-api-part-3-create-delete-and-move-folders/</link>
		<comments>http://cgeers.com/2012/02/19/dropbox-rest-api-part-3-create-delete-and-move-folders/#comments</comments>
		<pubDate>Sun, 19 Feb 2012 13:33:26 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Dropbox]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Dropbox API]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3893</guid>
		<description><![CDATA[Introduction In the previous part (part 2: API Requests) I mentioned that the third part would show you how to perform various folder operations such as creating, deleting and moving folders. Well it has been a month, so let&#8217;s get to it. Go to the download page and download the source code of part 2 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3893&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 part (<a href="http://cgeers.com/2012/01/08/dropbox-rest-api-part-2-api-requests/" target="_blank">part 2: API Requests</a>) I mentioned that the third part would show you how to perform various folder operations such as creating, deleting and moving folders.</p>
<p>Well it has been a month, so let&#8217;s get to it. Go to the download page and download the source code of part 2 (Article #63). Unzip and open the solution in Visual Studio. Make sure you modify the API key and secret located in the console application (Program.cs code file). Replace the values with your own application&#8217;s key and secret.</p>
<p>Ready? Set? OK, let&#8217;s start with creating folders&#8230;</p>
<p><span id="more-3893"></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="#create">Create Folder</a></li>
<li><a href="#encoding">URL Encoding</a></li>
<li><a href="#move">Move Folder</a></li>
<li><a href="#delete">Delete Folder</a></li>
</ul>
<p><a title="create" name="create"></a><strong>Create Folder</strong></p>
<p>The Dropbox REST API states that to <a href="http://www.dropbox.com/developers/reference/api#fileops-create-folder" target="_blank">create a folder</a> you must supply at least two parameters, namely:</p>
<ol>
<li><strong>root</strong>: The root relative to which the path is specified. Valid values are sandbox and dropbox.</li>
<li><strong>path</strong>: The path to the new folder to create relative to the root</li>
</ol>
<p>After creating the folder Dropbox returns some metadata about it. As usual this data is JSON-formatted. Let&#8217;s create a simple class decorated with attributes from the <a href="http://james.newtonking.com/projects/json-net.aspx" target="_blank">Json.NET library</a> so that we can easily 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> FileSystemInfo
{
    [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">"bytes"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">long</span> Bytes { <span class="kwrd">get</span>; <span class="kwrd">internal</span> <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"modified"</span>)]
    <span class="kwrd">public</span> DateTime Modified { <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">"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>; }

    <span class="rem">//...</span>
}</pre>
</div>
<p>The FileSystemInfo type is very similar to the File type shown in part 2 of this series. I&#8217;ve abbreviated the code here for readability. <a href="http://cgeers.com/download/">Download the source</a> and check it out if you want to see the whole class. This type will also be used as the return type of the Move(&#8230;) and Delete(&#8230;) methods that we&#8217;ll implement later.</p>
<p>Let&#8217;s expand the DropboxApi type so that we can create a folder in the following manner:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> folder = api.CreateFolder(<span class="str">"dropbox"</span>, <span class="str">"/test"</span>);</pre>
</div>
<p>First you need to specify the root. Valid values are sandbox or dropbox (production). Then you need to specify the folder relative to the root. Subdirectories are allowed.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> folder = api.CreateFolder(<span class="str">"dropbox"</span>, <span class="str">"/test/subdir"</span>);</pre>
</div>
<p>The implementation of the CreateFolder(&#8230;) method is similar to the API requests we handled in part 2.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> FileSystemInfo CreateFolder(<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">"fileops/create_folder?root={0}&amp;path={1}"</span>,
        root, UpperCaseUrlEncode(path)));
    <span class="kwrd">var</span> json = GetResponse(uri);
    <span class="kwrd">return</span> ParseJson&lt;FileSystemInfo&gt;(json);
}</pre>
</div>
<p>First we compose the URL to call, e.g.:</p>
<p><a href="https://api.dropbox.com/1/fileops/create_folder?root=dropbox&amp;path=%2Ftest" target="_blank">https://api.dropbox.com/1/fileops/create_folder?root=dropbox&amp;path=%2Ftest</a></p>
<p>Then we retrieve the response (JSON) by calling the GetResponse(&#8230;) method (see part 2), which signs the request using OAuth, and deserialize it into a Folder object using the Json.NET library.</p>
<p>You can examine the folder metadata afterwards:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> folder = api.CreateFolder(<span class="str">"dropbox"</span>, <span class="str">"/test"</span>);
Console.WriteLine(<span class="str">"Folder created."</span>);
Console.WriteLine(String.Format(<span class="str">"Root: {0}"</span>, folder.Root));
Console.WriteLine(String.Format(<span class="str">"Path: {0}"</span>, folder.Path));
Console.WriteLine(String.Format(<span class="str">"Modified: {0}"</span>, folder.Modified));     </pre>
</div>
<p>Which outputs:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/02/dropbox.png"><img src="http://cgeers.files.wordpress.com/2012/02/dropbox.png?w=480&#038;h=140" alt="Create a Folder" title="Create a Folder" width="480" height="140" class="aligncenter size-full wp-image-3912" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="encoding" name="encoding"></a><strong>URL Encoding</strong></p>
<p>Did you notice that I URL encoded the path parameter in the CreateFolder(&#8230;) method? This is necessary in order to send the request. However there is a small issue that we must address.</p>
<p>Let&#8217;s say we use the <a href="http://msdn.microsoft.com/en-us/library/4fkewx0t.aspx" target="_blank">HttpUtility.UrlEncode</a>(&#8230;) method to URL encode the path.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> path = HttpUtility.UrlEncode(path);</pre>
</div>
<p>This will transform the path /test info %2ftest. The slash (/) is translated to %2f. However if you use that value with the Dropbox API you&#8217;ll get an error informing you that the signature is invalid. </p>
<p>Apparently the Dropbox API doesn&#8217;t like lowercased escaped paths. Instead of %2f it expects %2F (notifice the upper-casing!). Luckily StackOverflow provided an answer for this problem:</p>
<p><a href="http://stackoverflow.com/questions/918019/net-urlencode-lowercase-problem" target="_blank">http://stackoverflow.com/questions/918019/net-urlencode-lowercase-problem</a></p>
<p>So that&#8217;s why I&#8217;ve included the (private) UpperCaseUrlEncode(&#8230;) method to the DropboxApi type. This method encodes the path and makes sure the escaped parts are correctly cased.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">string</span> UpperCaseUrlEncode(<span class="kwrd">string</span> s)
{
    <span class="kwrd">char</span>[] temp = HttpUtility.UrlEncode(s).ToCharArray();
    <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; temp.Length - 2; i++)
    {
        <span class="kwrd">if</span> (temp[i] == <span class="str">'%'</span>)
        {
            temp[i + 1] = <span class="kwrd">char</span>.ToUpper(temp[i + 1]);
            temp[i + 2] = <span class="kwrd">char</span>.ToUpper(temp[i + 2]);
        }
    }
    <span class="kwrd">return</span> <span class="kwrd">new</span> <span class="kwrd">string</span>(temp);
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="move" name="move"></a><strong>Move Folder</strong></p>
<p>You&#8217;ve already done most of the work by now. We can reuse most of the code to move a folder (or file).</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
folder = api.Move(<span class="str">"dropbox"</span>, <span class="str">"/test"</span>, <span class="str">"/temp"</span>);</pre>
</div>
<p>Apart from the URL the implementation is the same as the CreateFolder(&#8230;) method.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> FileSystemInfo Move(<span class="kwrd">string</span> root, <span class="kwrd">string</span> fromPath, <span class="kwrd">string</span> toPath)
{
    <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">"fileops/move?root={0}&amp;from_path={1}&amp;to_path={2}"</span>,
        root, UpperCaseUrlEncode(fromPath), UpperCaseUrlEncode(toPath)));
    <span class="kwrd">var</span> json = GetResponse(uri);
    <span class="kwrd">return</span> ParseJson&lt;FileSystemInfo&gt;(json);
}</pre>
</div>
<p>The Move(&#8230;) method 3 parameters, namely:</p>
<ol>
<li><strong>root</strong>: The root. Valid values are sandbox or dropbox.</li>
<li><strong>fromPath</strong>: The file or folder to be copied from relative to the root.</li>
<li><strong>toPath</strong>: The destination path, including the new name for the file or folder, relative to root.</li>
</ol>
<p><a href="#top">Top of page</a></p>
<p><a title="delete" name="delete"></a><strong>Delete Folder</strong></p>
<p>Let&#8217;s clean up after ourselves and delete the folder(s) we created. First we created a folder named &#8220;test&#8221;, then moved it to &#8220;temp&#8221;. So let&#8217;s delete that one.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
folder = api.Delete(<span class="str">"dropbox"</span>, <span class="str">"/temp"</span>);</pre>
</div>
<p>Again the implementation of the Delete(&#8230;) method is very similar to the CreateFolder(&#8230;) and Move(&#8230;) methods.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> FileSystemInfo Delete(<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">"fileops/delete?root={0}&amp;path={1}"</span>,
        root, UpperCaseUrlEncode(path)));
    <span class="kwrd">var</span> json = GetResponse(uri);
    <span class="kwrd">return</span> ParseJson&lt;FileSystemInfo&gt;(json);
}      </pre>
</div>
<p>And that is all there is to it! Apart from an issue with the casing of the URL encoding creating, moving and deleting folders is pretty easy with the Dropbox REST API. Note that you can also use the Move(&#8230;) and Delete(&#8230;) methods with files, not just folders.</p>
<p>For the sake of completeness, here&#8217;s the entire flow of the client application.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">// Create a folder</span>
<span class="kwrd">var</span> folder = api.CreateFolder(<span class="str">"dropbox"</span>, <span class="str">"/test"</span>);
Console.WriteLine(<span class="str">"Folder created."</span>);
Console.WriteLine(String.Format(<span class="str">"Root: {0}"</span>, folder.Root));
Console.WriteLine(String.Format(<span class="str">"Path: {0}"</span>, folder.Path));
Console.WriteLine(String.Format(<span class="str">"Modified: {0}"</span>, folder.Modified));                                    

<span class="rem">// Move a folder</span>
folder = api.Move(<span class="str">"dropbox"</span>, <span class="str">"/test"</span>, <span class="str">"/temp"</span>);

<span class="rem">// Delete a folder</span>
folder = api.Delete(<span class="str">"dropbox"</span>, <span class="str">"/temp"</span>);</pre>
</div>
<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 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/3893/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3893/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3893/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3893/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3893/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3893/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3893/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3893/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3893/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3893/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3893/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3893/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3893/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3893/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3893&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/02/19/dropbox-rest-api-part-3-create-delete-and-move-folders/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/12/logo1.png" medium="image">
			<media:title type="html">DropBox Logo</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/02/dropbox.png" medium="image">
			<media:title type="html">Create a Folder</media:title>
		</media:content>
	</item>
		<item>
		<title>Enabling SSL for a WCF Service</title>
		<link>http://cgeers.com/2012/01/30/enabling-ssl-for-a-wcf-service/</link>
		<comments>http://cgeers.com/2012/01/30/enabling-ssl-for-a-wcf-service/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 14:21:03 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[IIS]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=3817</guid>
		<description><![CDATA[Introduction Last week a reader mailed me with some questions about my &#8220;WCF over HTTPS&#8221; blog post, which I wrote almost 3 years ago. I created some sample code to help him enable SSL for a WCF service. Last year this was my most popular article, so I thought it would make sense to create [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3817&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>Last week a reader mailed me with some questions about my &#8220;<a href="http://cgeers.com/2009/08/07/wcf-over-https/" target="_blank">WCF over HTTPS</a>&#8221; blog post, which I wrote almost 3 years ago.</p>
<p>I created some sample code to help him enable SSL for a WCF service. Last year this was my most popular article, so I thought it would make sense to create a new up-to-date version that shows you step-by-step how to enable SSL for a WCF service with as little fuss as possible.</p>
<p>Let&#8217;s get started&#8230;</p>
<p><span id="more-3817"></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="#theservice">Step 1 &#8211; The Service</a></li>
<li><a href="#configuration">Step 2 &#8211; Configuration</a></li>
<li><a href="#hosting">Step 3 &#8211; Hosting The Service</a></li>
<li><a href="#certificate">Step 4 &#8211; SSL Certificate</a></li>
<li><a href="#enablessl">Step 5 &#8211; Enable SSL</a></li>
<li><a href="#consume">Step 6 &#8211; Consume The Service</a></li>
</ul>
<p><a title="theservice" name="theservice"></a><strong>Step 1 &#8211; The Service</strong></p>
<p>First we are going to create a simple and easy-to-use WCF service. Start up Visual Studio 2010 and create a new blank solution called &#8220;SslEnabledWcfService&#8221;. Next add a new class library project to it called &#8220;CustomerService&#8221;. </p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf1.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf1.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3825" /></a></p>
<p>Add a reference to the System.ServiceModel and System.Runtime.Serialization assemblies to the CustomerService project.</p>
<p>Add a new interface called ICustomerService to the project<br />
 that defines the service contract.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[ServiceContract]
<span class="kwrd">public</span> <span class="kwrd">interface</span> ICustomerService
{
    [OperationContract]
    IEnumerable&lt;Customer&gt; GetCustomers();
}</pre>
</div>
<p>The service returns a collection of customers. Each customer is represented by an instance of the Customer class. </p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[DataContract]
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    [DataMember]
    <span class="kwrd">public</span> Guid Id { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    [DataMember]
    <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    [DataMember]
    <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }
}</pre>
</div>
<p>Go ahead and add a file called Customer.cs. Copy and paste the code listed above.</p>
<p>The actual service implementation is very simple. It returns a list of customers which I create on the fly. No use in dealing with a database, or another persistant data store for this post. Let&#8217;s keep things as simple as possible.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[ServiceBehavior]
<span class="kwrd">public</span> <span class="kwrd">class</span> CustomerService : ICustomerService
{
    <span class="kwrd">private</span> IEnumerable&lt;Customer&gt; LoadCustomers()
    {
        <span class="rem">//...</span>
    }

    <span class="kwrd">public</span> IEnumerable&lt;Customer&gt; GetCustomers()
    {
        <span class="kwrd">var</span> customers = <span class="kwrd">new</span> List&lt;Customer&gt;();
        customers.AddRange(LoadCustomers());
        <span class="kwrd">return</span> customers;
    }
}</pre>
</div>
<p>Check out the source code accompanying this post for the full code of the CustomerService class.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="configuration" name="configuration"></a><strong>Step 2 &#8211; Configuration</strong></p>
<p>OK, now it&#8217;s time to add some configuration for our service. The host process (IIS) needs this to be able to figure out how to host the service. First add a new application configuration file called Web.config to the CustomerService project.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf2.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf2.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3835" /></a></p>
<p>First you need to list the service in the <a href="http://msdn.microsoft.com/en-us/library/ms731354.aspx" target="_blank">&lt;system.serviceModel&gt;</a> node.</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">="CustomerService.CustomerService"</span>
              <span class="attr">behaviorConfiguration</span><span class="kwrd">="MyServiceBehavior"</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">="basicHttpBinding"</span>
                <span class="attr">bindingConfiguration</span><span class="kwrd">="TransportSecurity"</span>
                <span class="attr">contract</span><span class="kwrd">="CustomerService.ICustomerService"</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">="mexHttpsBinding"</span>
                <span class="attr">contract</span><span class="kwrd">="IMetadataExchange"</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="rem">&lt;!--...--&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">system.serviceModel</span><span class="kwrd">&gt;</span></pre>
</div>
<p>As you can see the service is linked to a custom service behavior called &#8220;MyServiceBehavior&#8221;. You need to define this behavior in the <a href="http://msdn.microsoft.com/en-us/library/ms731298.aspx" target="_blank">&lt;behaviors&gt;</a> node of the &lt;system.serviceModel&gt; node.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<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">="MyServiceBehavior"</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">serviceMetadata</span> <span class="attr">httpsGetEnabled</span><span class="kwrd">="true"</span> <span class="attr">httpsGetUrl</span><span class="kwrd">=""</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></pre>
</div>
<p>Note that the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicemetadatabehavior.httpsgetenabled.aspx" target="_blank">httpsGetEnabled</a> property of the behavior is set to true. This allows us to retrieve metadata for the service using an HTTPS/GET request. Handy for creating our client proxies later on.</p>
<p>The first endpoint (non-mex) of the service is also tied to a custom binding (basicHttpBinding) called TransportSecurity.</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">basicHttpBinding</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">binding</span> <span class="attr">name</span><span class="kwrd">="TransportSecurity"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">security</span> <span class="attr">mode</span><span class="kwrd">="Transport"</span><span class="kwrd">&gt;</span>
          <span class="kwrd">&lt;</span><span class="html">transport</span> <span class="attr">clientCredentialType</span><span class="kwrd">="None"</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">security</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">basicHttpBinding</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">bindings</span><span class="kwrd">&gt;</span>          </pre>
</div>
<p>It is on the binding level that you must specify which security model the service uses. Here we set the mode to Transport (SSL) and turn off any type of <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.httptransportsecurity.clientcredentialtype.aspx" target="_blank">client authentication</a>.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="hosting" name="hosting"></a><strong>Step 3 &#8211; Hosting The Service</strong></p>
<p>The service has been created and configured. Time to host it. I&#8217;m using IIS 7.5 (7.5.7600.16385) on Windows 7 for this purpose. Create a new text file called &#8220;Service.svc&#8221;. Note the .svc extension! </p>
<p>Add it to the CustomerService project. </p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf3.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf3.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-3846" /></a></p>
<p>It only contains one line, namely:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
&lt;%@ ServiceHost Language=<span class="str">"C#"</span>
                Service=<span class="str">"CustomerService.CustomerService"</span>
                CodeBehind=<span class="str">"CustomerService.cs"</span> %&gt;</pre>
</div>
<p>Here you identify the service, the language used and the location of the code behind file. </p>
<p>Open up Windows Explorer and navigate to the default installation folder for IIS (C:\inetpub). I started with a clean installation to make things easy. Since I don&#8217;t host any other sites locally I deleted everything I found within the wwwroot subfolder. You might want to create a subfolder within the wwwroot folder to host your service. Once you have done so create a new directory called bin within the wwwroot folder or your custom subfolder.</p>
<p>To host the service you must copy the following files to the directory in which you host your service:</p>
<ul>
<li>Service.svc</li>
<li>Web.config</li>
<li>CustomerService.dll (\bin)</li>
</ul>
<p>You must copy the compiled CustomerService.dll assembly (and any other dependent assemblies) inside the bin folder! Just set your solution configuration to Release, rebuild your solution and copy the necessary files as described.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf4.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf4.png?w=480&#038;h=87" alt="Inetpub wwwroot" title="Inetpub wwwroot" width="480" height="87" class="aligncenter size-full wp-image-3852" /></a></p>
<p>Almost there, we just need to configure IIS. Start up the Internet Information Services (IIS) Manager and navigate to the Default Web Site node in the left pane.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf5.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf5.png?w=480" alt="IIS Manager" title="IIS Manager"   class="aligncenter size-full wp-image-3854" /></a></p>
<p>Double click on the Default Document displayed in the middle pane under the IIS group.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf6.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf6.png?w=480" alt="Default Document" title="Default Document"   class="aligncenter size-full wp-image-3856" /></a></p>
<p>Remove all the documents listed there and afterwards add a new document called Service.svc. When we navigate to http://localhost we want IIS to serve up the Service.svc document by default.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf7.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf7.png?w=480&#038;h=128" alt="Default Document" title="Default Document" width="480" height="128" class="aligncenter size-full wp-image-3857" /></a></p>
<p>Open your favorite browser (*cough* Chrome * cough*) and navigate to <a href="http://localhost" target="_blank">http://localhost</a>. You&#8217;ll be greeted by the following error page:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf8.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf8.png?w=480&#038;h=361" alt="Secured Page" title="Secured Page" width="480" height="361" class="aligncenter size-full wp-image-3861" /></a></p>
<p>The page is secured and cannot be accessed via http. Exactly what we want! You can try and access it via <a href="https://localhost" target="_blank">https://localhost</a>, but this will result in a page not found error as we have not yet configured SSL.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="certificate" name="certificate"></a><strong>Step 4 &#8211; SSL Certificate</strong></p>
<p>Before you can configure your service to use SSL you need a valid SSL certificate. Luckily you can create one yourself for development / testing purposes instead of purchasing one. Using the <a href="http://msdn.microsoft.com/en-us/library/bfsktky3(v=vs.80).aspx" target="_blank">makecert.exe</a> command-line utility you can create your own certificates. </p>
<p>Let&#8217;s quickly create a certificate. Start up an elevated Visual Studio Command Prompt and enter the following command:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
makecert -r -pe -n “CN=YourComputerName” -b 01/01/2012 -e 01/01/2020
-eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp
“Microsoft RSA SChannel Cryptographic Provider” -sy 12</pre>
</div>
<p>Make sure to replace the term &#8220;YourComputerName&#8221; with your actual computer&#8217;s name. After executing the command you should get a simple &#8220;succeeded&#8221; message.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf9.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf9.png?w=480&#038;h=148" alt="Makecert.exe" title="Makecert.exe" width="480" height="148" class="aligncenter size-full wp-image-3867" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="enablessl" name="enablessl"></a><strong>Step 5 &#8211; Enable SSL</strong></p>
<p>Alright, we have our SSL certificate. Let&#8217;s bind it to our service. Go back to IIS Manager and select the Default Web Site node. In the right pane click on the &#8220;Bindings&#8230;&#8221; link.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf10.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf10.png?w=480" alt="Bindings" title="Bindings"   class="aligncenter size-full wp-image-3870" /></a></p>
<p>In the Site Bindings popup click on the Add button to add a new binding.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf11.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf11.png?w=480&#038;h=224" alt="Site Bindings" title="Site Bindings" width="480" height="224" class="aligncenter size-full wp-image-3872" /></a></p>
<p>and enter the following data to enable SSL for your site:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf12.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf12.png?w=480&#038;h=261" alt="Site Binding" title="Site Binding" width="480" height="261" class="aligncenter size-full wp-image-3873" /></a></p>
<p>Be sure to select the SSL certificate you created earlier! Just click OK to add the binding and close the Site Bindings popup afterwards.</p>
<p>Restart your web site and navigate to <a href="https://localhost" target="_blank">https://localhost</a>. This time it&#8217;ll work, but you&#8217;ll probably get a warning message because of your untrusted SSL certificate. Just ignore it.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/wcf13.png"><img src="http://cgeers.files.wordpress.com/2012/01/wcf13.png?w=480&#038;h=387" alt="SSL Enabled Service" title="SSL Enabled Service" width="480" height="387" class="aligncenter size-full wp-image-3875" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="consume" name="consume"></a><strong>Step 6 &#8211; Consume The Service</strong></p>
<p>Now that we have our service running in IIS and secured with SSL let&#8217;s test it. Time to consume the service. Add a new console application to the solution called ClientApp. Add a service reference to our newly created WCF service.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/service-reference.png"><img src="http://cgeers.files.wordpress.com/2012/01/service-reference.png?w=480&#038;h=387" alt="Add Service Reference" title="Add Service Reference" width="480" height="387" class="aligncenter size-full wp-image-3877" /></a></p>
<p>When adding the service reference Visual Studio will report a problem with the SSL certificate.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/certificate-problem.png"><img src="http://cgeers.files.wordpress.com/2012/01/certificate-problem.png?w=480&#038;h=375" alt="Certificate Problem" title="Certificate Problem" width="480" height="375" class="aligncenter size-full wp-image-3878" /></a></p>
<p>Just click Yes to proceed. The message is shown because the certificate has not been issued by a company you have chosen to trust.</p>
<p>After you&#8217;ve created the service reference you can consume the service. Let&#8217;s display a list of the customers.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">using</span> (<span class="kwrd">var</span> proxy = <span class="kwrd">new</span> CustomerServiceClient())
{
    <span class="kwrd">var</span> customers = proxy.GetCustomers();
    <span class="kwrd">foreach</span>(<span class="kwrd">var</span> customer <span class="kwrd">in</span> customers)
    {
        Console.WriteLine(String.Format(<span class="str">"{0} {1}"</span>, customer.FirstName, customer.LastName));
    }
}</pre>
</div>
<p>When you try to execute this code you&#8217;ll get the following exception:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/securitynegotiatianexception1.png"><img src="http://cgeers.files.wordpress.com/2012/01/securitynegotiatianexception1.png?w=480&#038;h=219" alt="SecurityNegotiatianException" title="SecurityNegotiatianException" width="480" height="219" class="aligncenter size-full wp-image-3883" /></a></p>
<p>The client application does not trust the service. You can fix this by inspecting the certificate which the service hands over to the client. You need to hook up a handler for the <a href="http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx" target="_blank">ServicePointManager&#8217;s ServerCertifcateValidationCallback</a>.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
ServicePointManager.ServerCertificateValidationCallback += customXertificateValidation;</pre>
</div>
<p>When this callback is triggered you can inspect the server certificate.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> customXertificateValidation(<span class="kwrd">object</span> sender, X509Certificate cert,
    X509Chain chain, SslPolicyErrors error)
{
    <span class="kwrd">var</span> certificate = (X509Certificate2) cert;

    <span class="rem">// Inspect the server certficiate here to validate </span>
    <span class="rem">// that you are dealing with the correct server.</span>
    <span class="rem">// If so return true, if not return false.</span>
    <span class="kwrd">return</span> <span class="kwrd">true</span>;
}</pre>
</div>
<p>We&#8217;re finally there. If you run the client application now it will correctly list the customers returned by the SSL-enabled WCF service.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/01/output1.png"><img src="http://cgeers.files.wordpress.com/2012/01/output1.png?w=480&#038;h=106" alt="The Customers" title="The Customers" width="480" height="106" class="aligncenter size-full wp-image-3887" /></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/iis/'>IIS</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/3817/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/3817/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cgeers.wordpress.com/3817/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cgeers.wordpress.com/3817/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cgeers.wordpress.com/3817/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cgeers.wordpress.com/3817/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cgeers.wordpress.com/3817/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cgeers.wordpress.com/3817/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cgeers.wordpress.com/3817/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cgeers.wordpress.com/3817/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cgeers.wordpress.com/3817/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cgeers.wordpress.com/3817/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cgeers.wordpress.com/3817/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cgeers.wordpress.com/3817/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&amp;blog=2504479&amp;post=3817&amp;subd=cgeers&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/01/30/enabling-ssl-for-a-wcf-service/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/2008/04/dotnetwcf.gif" medium="image" />

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf1.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf2.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf3.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf4.png" medium="image">
			<media:title type="html">Inetpub wwwroot</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf5.png" medium="image">
			<media:title type="html">IIS Manager</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf6.png" medium="image">
			<media:title type="html">Default Document</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf7.png" medium="image">
			<media:title type="html">Default Document</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf8.png" medium="image">
			<media:title type="html">Secured Page</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf9.png" medium="image">
			<media:title type="html">Makecert.exe</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf10.png" medium="image">
			<media:title type="html">Bindings</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf11.png" medium="image">
			<media:title type="html">Site Bindings</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf12.png" medium="image">
			<media:title type="html">Site Binding</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/wcf13.png" medium="image">
			<media:title type="html">SSL Enabled Service</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/service-reference.png" medium="image">
			<media:title type="html">Add Service Reference</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/certificate-problem.png" medium="image">
			<media:title type="html">Certificate Problem</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/securitynegotiatianexception1.png" medium="image">
			<media:title type="html">SecurityNegotiatianException</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/01/output1.png" medium="image">
			<media:title type="html">The Customers</media:title>
		</media:content>
	</item>
		<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[C#]]></category>
		<category><![CDATA[Dropbox]]></category>
		<category><![CDATA[Programming]]></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>10</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>14</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>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/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>
	</channel>
</rss>
