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

<channel>
	<title>ON Blog</title>
	<atom:link href="http://onishimura.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://onishimura.com</link>
	<description></description>
	<lastBuildDate>Sat, 21 May 2011 17:23:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Facebook Messaging</title>
		<link>http://onishimura.com/2010/11/16/facebook-messaging/</link>
		<comments>http://onishimura.com/2010/11/16/facebook-messaging/#comments</comments>
		<pubDate>Tue, 16 Nov 2010 03:00:30 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[Facebook]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=257</guid>
		<description><![CDATA[Lots of commentary on the web today regarding Facebook&#8217;s new Messaging product&#8230;. Announcement on facebook blog Facebook Messages Tour Good write-up at Techcrunch Facebook stats from Techcrunch Lifehacker on why [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F11%2F16%2Ffacebook-messaging%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F11%2F16%2Ffacebook-messaging%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Lots of commentary on the web today regarding Facebook&#8217;s new Messaging product&#8230;.</p>
<ul>
<li><a href='http://blog.facebook.com/blog.php?post=452288242130'>Announcement on facebook blog</a></li>
<li><a href='http://www.facebook.com/about/messages/'>Facebook Messages Tour</a></li>
<li><a href="http://techcrunch.com/2010/11/15/facebook-messaging/">Good write-up at Techcrunch</a></li>
<li><a href="http://techcrunch.com/2010/11/15/facebook-350m-people-using-messaging-more-than-4b-messages-sent-daily/">Facebook stats from Techcrunch</a></li>
<li><a href="http://lifehacker.com/5690722/why-you-shouldnt-switch-your-email-to-facebook">Lifehacker on why you should avoid it</a></li>
<li><a href="http://www.salon.com/technology/dan_gillmor/2010/11/15/facebook_uber_messaging">Salon warning from Dan Gillmore</a></li>
<li><a href="http://www.businessinsider.com/facebook-google-apple-2010-11">I just like the picture</a></li>
</ul>
<p><span id="more-257"></span></p>
<h3>Generally speaking&#8230;</h3>
<p>Some of the more interesting stats to come out of all of this : 4 billion messages sent daily, used by 350 million facebook users. Unsurprisingly, the new Messaging platform will be available on facebook.com as well as their mobile apps, so we can expect an updated iphone app in the near future.</p>
<p>Generally speaking the goal of this new product is to consolidate all of your text messages, by merging Facebook messages, email, SMS, and IM. The core concepts at play in Facebook Messaging are the following:</p>
<ol>
<li>A Social inbox (a unified store)</li>
<li>Seamless messaging (send/reply to multiple types of messages)</li>
<li>Conversation history (all conversations are kept)</li>
</ol>
<h3>For developers&#8230;</h3>
<ul>
<li><a href="http://developers.facebook.com/blog/post/428">Messaging API Announcement</a></li>
<li><a href="http://www.facebook.com/note.php?note_id=454991608919">Discussion of Messaging Tech</a></li>
<li><a href="http://hbase.apache.org/">Rebuilt and now uses hBase (Hadoop database)</a></li>
</ul>
<p>
So there will be an early beta for a read API for the new messaging system, open to registered devs.  Currently there&#8217;s some api documentation available<br />
http://developers.facebook.com/docs/reference/api/thread. Note that this is a read-only API &#8211;  devs cannot send messages to @facebook.com addresses. Apparently you need an extended permission set, read_mailbox, which is set just like any other extended permission:
</p>
<p><img src='http://onishimura.s3.amazonaws.com/fb-mailbox-permission.png' alt='Read mailbox extended permission' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px' /></p>
<p>
I&#8217;ve tried calling it with a valid acces_token however and got this back as a result
</p>
<pre class="brush: plain; title: ; notranslate">
{
   &quot;error&quot;: {
      &quot;type&quot;: &quot;MessagingException&quot;,
      &quot;message&quot;: &quot;Service Unavailable: Unfortunately, we cannot currently access your messages.  Please try again later.&quot;
   }
}
</pre>
<p>
Gotta love betas</p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/11/16/facebook-messaging/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Facebook, C# and ASP.NET MVC &#8211; Updated code samples for places, wall and offline access</title>
		<link>http://onishimura.com/2010/11/15/facebook-c-and-asp-net-mvc-updated-code-samples-for-places-wall-offline-access/</link>
		<comments>http://onishimura.com/2010/11/15/facebook-c-and-asp-net-mvc-updated-code-samples-for-places-wall-offline-access/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 22:09:51 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Facebook]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=230</guid>
		<description><![CDATA[The big news a couple of weeks ago was the opening up of the Facebook Places API and launching a Deals Service as well. The Places API is pretty straightforward [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F11%2F15%2Ffacebook-c-and-asp-net-mvc-updated-code-samples-for-places-wall-offline-access%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F11%2F15%2Ffacebook-c-and-asp-net-mvc-updated-code-samples-for-places-wall-offline-access%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>
The big news a couple of weeks ago was the <a href='http://techcrunch.com/2010/11/03/facebook-gives-developers-access-to-full-set-of-places-apis/'>opening up</a> of the <a href='http://blog.facebook.com/blog.php?post=418175202130'>Facebook Places</a> API and launching a <a href='http://www.facebook.com/blog.php?post=446183422130'>Deals</a> Service as well. The Places API is pretty straightforward to work with so I&#8217;ve updated the Sample MVC App to show an example of calling it, specifically getting a user&#8217;s checkins and search for places given a search term, latitude and longitude, and distance. I&#8217;ve also had a few requests to show a few other calls, so I&#8217;ve included a sample for displaying a user&#8217;s wall (feed) and how to use offline_access to retrieve a user&#8217;s wall even when they aren&#8217;t logged in. Additionally, I&#8217;ve refactored some of the code a bit to be a little cleaner, but I&#8217;ve only written samples using the official C# SDk (I assume thats what everyone&#8217;s using at this point).
</p>
<p><span id="more-230"></span></p>
<p><h3>Setting the proper extended permissions</h3>
<p>We&#8217;re going to be using two new <a href='http://developers.facebook.com/docs/authentication/permissions'>extended permissions</a> here, checkins and offline_access, so the first change we need to make is in Home/Index.aspx. </p>
<pre class="brush: xml; title: ; notranslate">
	&lt;fb:login-button autologoutlink='true' onlogin='window.location.reload()'
	perms='read_stream, publish_stream, read_friendlists, user_activities,
	user_checkins, offline_access'&gt;&lt;/fb:login-button&gt;
</pre>
<p>The first time you log in after making these changes you should get prompted with a confirmation dialog from facebook.<br />
<img src='http://onishimura.s3.amazonaws.com/fb-extended.png' alt='Extended permissions: Offline Access and Checkins' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px' />
</p>
<p><h3>Places and checkins</h3>
<p>The code to get a user&#8217;s checkins unsurprisingly makes a call to the <a href='http://developers.facebook.com/docs/reference/api/checkin'>Facebook Checkin service</a></p>
<pre class="brush: csharp; title: ; notranslate">
	public ActionResult GetCheckins()
	{
		JSONObject checkins = helper.Get(&quot;/me/checkins&quot;);
		if (checkins != null)
		{
			var data = checkins.Dictionary[&quot;data&quot;];
			List&lt;JSONObject&gt; checkinData = data.Array.ToList&lt;JSONObject&gt;();
			ViewData[&quot;Checkins&quot;] = checkinData;
		}

		ViewData[&quot;Name&quot;] = Session[Constants.FacebookNameKey];
		ViewData[&quot;isConnected&quot;] = helper.IsConnected;

		return View(&quot;Index&quot;);
	}
</pre>
<p>The structure of the returned data is as follows:</p>
<pre class="brush: plain; title: ; notranslate">
{
   &quot;data&quot;: [
      {
         &quot;id&quot;: &quot;CheckinID&quot;,
         &quot;from&quot;: {
            &quot;name&quot;: &quot;UserName&quot;,
            &quot;id&quot;: &quot;UserId&quot;
         },
         &quot;place&quot;: {
            &quot;id&quot;: &quot;PlaceId&quot;,
            &quot;name&quot;: &quot;Giants World Series Victory Parade Route&quot;,
            &quot;location&quot;: {
               &quot;latitude&quot;: 37.78627395,
               &quot;longitude&quot;: -122.40441083333
            }
         },
         &quot;application&quot;: null,
         &quot;created_time&quot;: &quot;2010-11-03T19:45:31+0000&quot;
      }
   ]
}
</pre>
<p><img src='http://onishimura.s3.amazonaws.com/fb-checkin.png' alt='Facebook Checkin sample' style='margin-top:20px;margin-bottom:20px' /></p>
<p>Note that the data set returned from a call to the checkins api will be paged. I&#8217;ve only ever checked in once, hence the single item in mu list.</p>
<p>The search call is somewhat different since you need to have 4 parameters set, the query term, the latitude and longitude of the center of the lcoation, and the distance from the center to use (the 5th parameter, &#8216;type&#8217; is just set to &#8216;place&#8217; in the code below). I&#8217;ve provided some sample data (which is just the sample data used in the Facebook example), which can be loaded by pressing the &#8216;Load Test Data&#8217; button. If you want to test a different address and need to find a valid lat/long setting, you can use <a href='http://geocoder.us/'>http://geocoder.us/</a> to convert an address.</p>
<pre class="brush: csharp; title: ; notranslate">
	public ActionResult SearchPlaces(FormCollection form)
	{
		Dictionary&lt;string,string&gt; parameters = new Dictionary&lt;string,string&gt;();
		parameters.Add(&quot;q&quot;, form[&quot;q&quot;]);
		parameters.Add(&quot;center&quot;, String.Format(&quot;{0},{1}&quot;,form[&quot;lat&quot;], form[&quot;long&quot;]));
		parameters.Add(&quot;type&quot;, &quot;place&quot;);
		parameters.Add(&quot;distance&quot;, form[&quot;distance&quot;]);

		JSONObject searchResults = helper.Get(&quot;/search&quot;, parameters);
		if (searchResults != null)
		{
			var data = searchResults.Dictionary[&quot;data&quot;];
			List&lt;JSONObject&gt; places = data.Array.ToList&lt;JSONObject&gt;();
			ViewData[&quot;Places&quot;] = places;
		}

		ViewData[&quot;Name&quot;] = Session[Constants.FacebookNameKey];
		ViewData[&quot;isConnected&quot;] = helper.IsConnected;

		return View(&quot;Index&quot;);
	}
</pre>
<p>Nothing fancy about the returned data either, it&#8217;s pretty similar to the data for the checkin. One thing to note though is that the location item may not have an address associated with it, so you need to account for that when working with the data (the sample just checks for the existence of the &#8216;street&#8217; key in the location array). </p>
<pre class="brush: plain; title: ; notranslate">
{
   &quot;data&quot;: [
      {
         &quot;name&quot;: &quot;Philz Coffee&quot;,
         &quot;category&quot;: &quot;Local business&quot;,
         &quot;location&quot;: {
            &quot;street&quot;: &quot;4023 18th St&quot;,
            &quot;city&quot;: &quot;San Francisco&quot;,
            &quot;state&quot;: &quot;CA&quot;,
            &quot;zip&quot;: &quot;94114-2501&quot;,
            &quot;latitude&quot;: 37.760863,
            &quot;longitude&quot;: -122.433326
         },
         &quot;id&quot;: &quot;151116474914629&quot;
      },
      {
         &quot;name&quot;: &quot;Ritual Coffee Roasters&quot;,
         &quot;category&quot;: &quot;Local business&quot;,
         &quot;location&quot;: {
            &quot;latitude&quot;: 37.75659,
            &quot;longitude&quot;: -122.4211
         },
         &quot;id&quot;: &quot;119185971453428&quot;
      },
	  ...
	 ]
}
</pre>
<p><img src='http://onishimura.s3.amazonaws.com/fb-places.png' alt='Facebook Places search sample' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px' /></p>
<p><h3>Retrieving a user&#8217;s wall</h3>
<p>The previous iteration of the sample including an example on how to post to a user&#8217;s wall, so getting a user&#8217;s wall is a natural corollary. Getting a user&#8217;s feed is accomplished by making a call to &#8216;me/feed&#8217;</p>
<pre class="brush: csharp; title: ; notranslate">
	public ActionResult GetWall()
	{
		JSONObject wallData = helper.Get(&quot;/me/feed&quot;);
		if (wallData != null)
		{
			var data = wallData.Dictionary[&quot;data&quot;];
			List&lt;JSONObject&gt; wallPosts = data.Array.ToList&lt;JSONObject&gt;();
			ViewData[&quot;Wall&quot;] = wallPosts;
		}

		ViewData[&quot;Name&quot;] = Session[Constants.FacebookNameKey];
		ViewData[&quot;isConnected&quot;] = helper.IsConnected;

		return View(&quot;Index&quot;);
	}
</pre>
<p>The returned data can differ depending on the type of the wall post, so when working with the data you just need to check for the presence of the appropriate dictionary keys before trying to use it. For example:</p>
<pre class="brush: xml; title: ; notranslate">
	&lt;%
		foreach (Facebook.JSONObject wallItem in wallPosts)
		{
			string wallItemType = wallItem.Dictionary[&quot;type&quot;].String;
			if (wallItemType == &quot;photo&quot; || wallItemType == &quot;video&quot;)
			{
	%&gt;
		&lt;li&gt;&lt;% if (wallItem.Dictionary.ContainsKey(&quot;name&quot;)) {  %&gt;&lt;%= wallItem.Dictionary[&quot;name&quot;].String%&gt; &lt;% } %&gt; (&lt;%= wallItemType %&gt;) 			&lt;br /&gt; &lt;a href='&lt;%= wallItem.Dictionary[&quot;link&quot;].String %&gt;'&gt;&lt;%= wallItem.Dictionary[&quot;link&quot;].String %&gt;&lt;/a&gt;&lt;/li&gt;
	 &lt;% }
		else if (wallItemType == &quot;status&quot;) {  %&gt;
			&lt;li&gt;&lt;%= wallItem.Dictionary[&quot;from&quot;].Dictionary[&quot;name&quot;].String%&gt; &lt;br /&gt; &lt;%= wallItem.Dictionary[&quot;message&quot;].String%&gt;&lt;/li&gt;
	 &lt;% } %&gt;
</pre>
<p>Note that a picture or video may or may not have a name so you&#8217;ll need to check for that as well.</p>
<p><img src='http://onishimura.s3.amazonaws.com/fb-wall-sample.png' alt='Facebook Wall sample' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px' /></p>
<p><h3>Offline Access</h3>
<p>The offline_access extended permission is pretty cool, it basically extends the life of the access_token you receive after logging in via OAuth. The example I wrote just stores this in a cookie (named FacebookAccessToken) the first time you log in with your account. Normally you&#8217;d want to store this in a database or some other more permanent store.</p>
<pre class="brush: csharp; title: ; notranslate">
	public ActionResult GetOfflineWall()
	{
		if (HttpContext.Request.Cookies[Constants.TokenCookieName] == null ||
			String.IsNullOrEmpty(HttpContext.Request.Cookies[Constants.TokenCookieName].Value))
		{
			return View(&quot;Index&quot;);
		}

		JSONObject wallData = helper.GetWhileOffline(&quot;/me/feed&quot;);
		if (wallData != null)
		{
			var data = wallData.Dictionary[&quot;data&quot;];
			List&lt;JSONObject&gt; wallPosts = data.Array.ToList&lt;JSONObject&gt;();
			ViewData[&quot;OfflineWall&quot;] = wallPosts;
		}

		return View(&quot;Index&quot;);
	}
</pre>
<p>The GetWhileOffline method beind used there just takes the access_token out of the FacebookAccessToken cookie and uses that when instantiating the FacebookAPI object&#8230;(in FacebookHelper.cs)</p>
<pre class="brush: csharp; title: ; notranslate">
	public JSONObject GetWhileOffline(string apiCall)
	{
		JSONObject jsonObject = null;

		if (HttpContext.Current.Request.Cookies[Constants.TokenCookieName] != null ||
			!String.IsNullOrEmpty(HttpContext.Current.Request.Cookies[Constants.TokenCookieName].Value))
		{ 

			string token = HttpContext.Current.Request.Cookies[Constants.TokenCookieName].Value;
			token = HttpUtility.UrlDecode(token);

			Facebook.FacebookAPI api = new Facebook.FacebookAPI(token);
			jsonObject = api.Get(apiCall);
		}

		return jsonObject;
	}
</pre>
<p><img src='http://onishimura.s3.amazonaws.com/fb-offline-wall.png' alt='Facebook Offline Wall Sample' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px' /></p>
<p>Thats really all there is to it, as long as you have the extended permission &#8216;offline_access&#8217; and an access_token that was created when a user logs in after granting this permission, you should be able to make offline calls.</p>
<p><a href='http://onishimura.s3.amazonaws.com/code/FacebookSampleMVC2Appv3.zip'>Download the latest version here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/11/15/facebook-c-and-asp-net-mvc-updated-code-samples-for-places-wall-offline-access/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Facebook, C# and ASP.NET MVC &#8211; Code samples for friends list, activities list and wall posts</title>
		<link>http://onishimura.com/2010/08/11/facebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts/</link>
		<comments>http://onishimura.com/2010/08/11/facebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 09:50:17 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[sf]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=202</guid>
		<description><![CDATA[A few weeks back I wrote about the official C# SDK from Facebook and provided some sample code demonstrating how to use it to get some basic information about the [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F08%2F11%2Ffacebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F08%2F11%2Ffacebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>A few weeks back I wrote about the <a href='http://onishimura.com/2010/07/17/official-facebook-c-sdk-released/'>official C# SDK from Facebook</a> and provided some sample code demonstrating how to use it to get some basic information about the logged in user. Admittedly the initial sample asp.net mvc code was fairly simple in order for it to be straight forward and easy to understand. I&#8217;ve decided to expand a bit on the sample in order to demonstrate how to use the Open graph API to perform a few more interesting calls, notably:</p>
<ul>
<li>Post to a user&#8217;s wall</li>
<li>Retrieve a list of the user&#8217;s friends</li>
<li>Retrieve a list of the user&#8217;s activities</li>
</ul>
<p>The <a href='http://onishimura.com/2010/07/17/official-facebook-c-sdk-released/'>original sample code</a> demonstrated how to authenticate a user and make calls using both the official C# sdk and a home grown solution. I&#8217;ve kept that approach but have organized and refactored the samples a bit better to make it hopefully more clear. The new version of the sample code allows you to login/out to facebook only on the home page. Once logged in you can go to the &#8216;Official&#8217; and &#8216;Custom&#8217; tabs to view your friends, activities or to post a message to your wall. While the functionality is the same between the two tabs, the code behind them is different. I assume most people would use the official SDK but I provided an alternative just as a point of interest. OK, I was bored really, and just wanted to see how it could be done differently.</p>
<p><span id="more-202"></span><br />
In any case, the first step before running the code is to make sure you clear any previous permissions granted to this app (or whatever app you will be using with the sample code). The login button on the home page now requests extended permissions so you&#8217;ll probably need to remove it from your list of allowed applications if you&#8217;re running the latest code with a facebook app that was using the original sample code. The actual list of permissions being request are perms=&#8217;read_stream,publish_stream,read_friendlists,user_activities&#8217;, and the full list of permissions available can be found here <a href='http://developers.facebook.com/docs/authentication/permissions'>http://developers.facebook.com/docs/authentication/permissions</a>.</p>
<h4>Official C# SDK </h4>
<p>The code to use the Facebook API can be found in the OfficialFacebookController. By default index view will simply show the name of the logged in user, which uses the same code present in the HomeController (and the original post<)</p>
<pre class="brush: csharp;">
string token = HttpUtility.UrlDecode(fbConnect.AccessToken);
FacebookAPI api = new FacebookAPI(token);
JSONObject me = api.Get(&#8220;/&#8221; + fbConnect.UserID);
ViewData["Name"] = me.Dictionary["name"].String;
</pre>
<p><img src='http://onishimura.s3.amazonaws.com/fb-official-index.png' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px' /></p>
<p>There are three other actions a logged in user can take here, view their friends list, view their activity list, and post a message to their wall. </p>
<ol style='list-style-type:decimal;margin-left:0;line-height:150%'>
<li>
Clicking the Get Friends button will call the GetFriends action in the controller. The call is simply api.Get("me/friends"), which returns a dictionary with a data key and an array of JSONObjects, representing all of the friends for the user. You could also call it with something like, api.Get("/" + fbConnect.UserID + "/friends"): "me" just uses the currently logged in user. </p>
<pre class="brush: csharp;">
Facebook.FacebookAPI api = new Facebook.FacebookAPI(token);
JSONObject me = api.Get("/" + fbConnect.UserID);
JSONObject friendsData = api.Get("/me/friends");
var data = friendsData.Dictionary["data"];
List&lt;JSONObject&gt; friendsList = data.Array.ToList<JSONObject>();

ViewData["Name"] = me.Dictionary["name"].String;
ViewData["Friends"] = friendsList;
</pre>
<p>The data itself is just the name and facebook id of the user's friends, so the view just loops through the friendsList collection and displays in this format Name - Id</p>
<pre class="brush: xml;">
&lt;%= friend.Dictionary["name"].String %&gt; - &lt;%= friend.Dictionary["id"].String %&gt;
</pre>
<p><img src='http://onishimura.s3.amazonaws.com/fb-official-friends.png' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px'  /></p>
</li>
<li>
Similarly, clicking the Get Activities button will call the GetActivities controller. The code is pretty much the same as the above friends code, but calls api.Get("/me/activities");. The data is also slightly different, since the activity data contains more information (such as category, and create_date). So, the view follows pretty much the same format but displays more fields:</p>
<pre class="brush: xml;wrap-lines:false">
&lt;%= activity.Dictionary["name"].String%&gt; - &lt;%= activity.Dictionary["id"].String%&gt;- &lt;%= activity.Dictionary["category"].String%&gt;- &lt;%= activity.Dictionary["created_time"].String%&gt;
</pre>
<p><img src='http://onishimura.s3.amazonaws.com/fb-official-activities.png' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px'  /></p>
</li>
<li>
Finally, the message section allows the user to enter a message and post it to a user's wall. Entering text and clicking the Post Message button will call the PostMessage action. Instead of calling the Get method of the FacebookAPI class, we call Post:</p>
<pre class="brush: csharp;">
Dictionary<string, string> postArgs = new Dictionary<string, string>();
postArgs["message"] = message;
JSONObject post = api.Post("/" + fbConnect.UserID + "/feed", postArgs);
</pre>
<p><img src='http://onishimura.s3.amazonaws.com/fb-official-messages.png' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px'  /></p>
<p>The post call also returns a JSONObject which contains the id of the new post. Just for verification, we show this in the view.</p>
<p><img src='http://onishimura.s3.amazonaws.com/fb-official-message-sent.png' width='500px' height='259px' style='margin-top:20px;margin-bottom:20px'  /></p>
</li>
</ol>
<h4>Custom C# classes</h4>
<p>The display of the custom code looks pretty much the same as the official sdk, so I won't post any images of the views. The primary classes involved are FacebookConnect.cs, FacebookObjects.cs and OpenGraph.cs. Note that compared to the <a href='http://onishimura.com/2010/07/17/official-facebook-c-sdk-released/'>original sample code</a> I've removed the "DEMO" prefix and added a few more methods to OpenGraph, renamed the DEMOFacebookUser to FacebookObjects, and added objects to FacebookObjects.cs. These serve as the definition for our extra calls</p>
<p>You might also notice in FacebookObjects that the DataContract and DataMember attributes have been removed from FacebookUser. One of the more significant changes is the way in which the Call method in the OpenGraph class works. Initially it was using the DataContractJsonSerializer class, which required you to mark your class and it's properties with DataContract and DataMember attributes. However, this serializer seems to <a href='http://stackoverflow.com/questions/596271/deserialization-problem-with-datacontractjsonserializer'>have</a> <a href='http://blog.dotsmart.net/2008/01/07/wcf-json-serialization-is-flawed/'>some</a> <a href='http://blog.dotsmart.net/2008/01/07/wcf-json-serialization-is-flawed/'>issues</a> parsing certain JSON strings. So instead I've changed the code to use the JavascriptSerializer which seems to work just fine. In fact it's more flexible and seems to take less configuration than DataContractJsonSerializer, which is why it was probably undeprecated (dedeprecated?). In addition to the use of JavascriptSerializer, the Call method also takes an additional parameter to specify the type of http request made. This allows us to use the same code to make a POST request, which is necessary when writing to a user's wall. The new Call method looks like this:</p>
<pre class="brush: csharp;">
private T Call&lt;T&gt;(string url, string methodType) where T : class
{
	T result;
	HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
	request.Method = methodType;

	using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
	using (StreamReader reader = new StreamReader(response.GetResponseStream()))
	{
		JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
		string jsonData = reader.ReadToEnd();
		result = (T)jsSerializer.Deserialize&lt;T&gt;(jsonData);
	}

	return result;
}
</pre>
<p>The various Get/Post methods in the OpenGraph class are pretty similar to the original GetCurrentUser method and rely on the objects defined in the FacebookObjects.cs file. For example, the GetCurrentUserFriends looks like the following:</p>
<pre class="brush: csharp;">
public List&lt;FacebookFriend&gt; GetCurrentUserFriends(string accessToken)
{
	string parameters = "me/friends?access_token=" + accessToken;
	string url = baseUrl + parameters;

	FacebookFriendData call = Call&lt;FacebookFriendData&gt;(url, GET);

	return call.Data;
}
</pre>
<p>The action just needs to call this method with a valid access_token. For example, the GetFriends action in CustomFacebookController, calls the following:</p>
<pre class="brush: csharp;">
List&lt;FacebookFriend&gt; friends =  openGraph.GetCurrentUserFriends(fbConnect.AccessToken);
</pre>
<p>Once this has been placed into the ViewData dictionary, we can just pull it out and iterate through it like so:</p>
<pre class="brush: xml; wrap-lines:false">
&lt;%
	List&lt;FacebookSampleMVC2App.FacebookFriend&gt; friendsList = ViewData["Friends"] as List&lt;FacebookSampleMVC2App.FacebookFriend&gt;;
	foreach(FacebookSampleMVC2App.FacebookFriend friend in friendsList) {
%&gt;
	&lt;%= friend.Name %&gt; - &lt;%= friend.Id %&gt;&lt;br /&gt;
&lt;%  } %&gt;
</pre>
<p>The logic/view for retrieving the user's activities and posting to the user's wall are fairly similar.</p>
<h4>Wrap up</h4>
<p>So there you have it, some sample code to do a bit more than just display the user's name and facebook id. The custom classes and the official sdk are pretty similar in the sense that they both just call REST methods like 'me/friends', 'me/activities' and 'me/feed' from https://graph.facebook.com/. The official SDK is more flexible however, since it doesn't need to have classes defined for each of the types, instead relying on JSONObject to wrap the dictionaries/arrays/scalars returned from the api calls. </p>
<p><a href='http://onishimura.s3.amazonaws.com/code/FacebookSampleMVC2Appv2.zip'>Download the code here</a></p>
<p><h3>Update - 11/15/2010</h3>
<p>I recently updated the sample project with more samples, which can be viewed here: <a href='http://onishimura.com/2010/11/15/facebook-c-and-asp-net-mvc-updated-code-samples-for-places-wall-offline-access/'>http://onishimura.com/2010/11/15/facebook-c-and-asp-net-mvc-updated-code-samples-for-places-wall-offline-access/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/08/11/facebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Windows Phone 7 Tutorial &#8211; Creating a simple notes app with Silverlight Part 3</title>
		<link>http://onishimura.com/2010/07/29/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-3/</link>
		<comments>http://onishimura.com/2010/07/29/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-3/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 09:27:44 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=191</guid>
		<description><![CDATA[This is part 3 in a 3 part tutorial for creating a notes application using Silverlight and Windows Phone 7. The previous articles can be read here Windows Phone 7 [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F29%2Fwindows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-3%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F29%2Fwindows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-3%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p style='font-style: italic;'>
This is part 3 in a 3 part tutorial for creating a notes application using Silverlight and Windows Phone 7. The previous articles can be read here<br />
<a href='http://onishimura.com/2010/07/25/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-1/'>Windows Phone 7 Tutorial – Creating a simple notes app with Silverlight Part 1</a><br />
<a href='http://onishimura.com/2010/07/27/windows-phone-7-tutorial%E2%80%93creating-a-simple-notes-app-with-silverlight-part-2/'>Windows Phone 7 Tutorial – Creating a simple notes app with Silverlight Part 2</a></p>
<p><a href='http://onishimura.s3.amazonaws.com/code/MyNotes.zip'>Download the code here</a></p>
<p>Currently our application can display a list of notes, and create and save a new note. The last piece of the puzzle is to allow the user to delete an existing note. To accomplish this all we really need to do is add an application bar button to the details page, remove it from the working items list, and save it to isolated storage.</p>
<ol style='list-item-type:decimal'>
<li>
Add the appbar.save.rest.png image in C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons to the Images folder in the project, and set it&#8217;s &#8216;Build Action&#8217; to Content&#8217;, and it&#8217;s &#8216;Copy to Output Directory&#8217; proerpty to &#8216;Copy if newer&#8217;.
</li>
<p><span id="more-191"></span></p>
<li>
Change DetailsPage.xaml to include an application bar, with the following code:</p>
<pre class="brush: xml; wrap-lines:false">
&lt;phone:PhoneApplicationPage.ApplicationBar&gt;
	&lt;shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"&gt;
		&lt;shell:ApplicationBarIconButton x:Name="appbar_button2" IconUri="/Images/appbar.back.rest.png" Text="Back" Click="appbar_button2_Click"&gt;&lt;/shell:ApplicationBarIconButton&gt;
		&lt;shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/Images/appbar.delete.rest.png" Text="Delete Note" Click="appbar_button1_Click"&gt;&lt;/shell:ApplicationBarIconButton&gt;
	&lt;/shell:ApplicationBar&gt;
&lt;/phone:PhoneApplicationPage.ApplicationBar&gt;
</pre>
<p>The two ApplicationBarIconButton added here will allow the user to return to the main list of notes, or delete the current note being viewed.</p>
<p><img src='http://onishimura.s3.amazonaws.com/wp7detail.png' alt='Windows Phone 7 Home' /></p>
</li>
<li>
Modify the DetailsPage class (DetaislPage.xaml.cs) to do the following</p>
<ul>
<li>Create a private instance variable to represent the current index of current note</li>
<li>Change the &#8216;OnNavigatedTo&#8217; method to set this index when the page gets focus</li>
<li>Add event handlers for the delete and back buttons</li>
</ul>
<p>The DetailsPage class uses an index scoped to the OnNavigatedTo method, and sets the pages DataContext using it. All we really need to do is change it to an instance member and set it in OnNavigated To like so:</p>
<pre class="brush: csharp">
private int index;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
	base.OnNavigatedTo(e);

	string selectedIndex = "";
	if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
	{
		index = int.Parse(selectedIndex);
		DataContext = App.ViewModel.Items[index];
	}
}
</pre>
<p>The event handlers are fairly straightforward. For the delete button, it should remove the note from the working list, save the current list to isolated storage, and finally navigate to the MainPage. The back button should simply navigate the user back to the MainPage.</p>
<pre class="brush: csharp;wrap-lines: false">
private void appbar_button1_Click(object sender, EventArgs e)
{
	if (index &lt; App.ViewModel.Items.Count)
	{
		App.ViewModel.Items.RemoveAt(index);
		StorageHelper.Save&lt;ObservableCollection&lt;Note&gt;&gt;(App.NotesFileName, App.ViewModel.Items);
	}
	NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}

private void appbar_button2_Click(object sender, EventArgs e)
{
	NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
</pre>
<p>After all of these changes your class should look like this</p>
<pre class="brush: csharp; wrap-lines: false">
using System;
using System.Collections.ObjectModel;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;

namespace MyNotes
{
    public partial class DetailsPage : PhoneApplicationPage
    {
        // Constructor
        public DetailsPage()
        {
            InitializeComponent();
        }

        private int index;

        // When page is navigated to, set data context to selected item in list
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string selectedIndex = "";
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
            {
                index = int.Parse(selectedIndex);
                DataContext = App.ViewModel.Items[index];
            }
        }

        private void appbar_button1_Click(object sender, EventArgs e)
        {
            if (index &lt; App.ViewModel.Items.Count)
            {
                App.ViewModel.Items.RemoveAt(index);
                StorageHelper.Save&lt;ObservableCollection&lt;Note&gt;&gt;(App.NotesFileName, App.ViewModel.Items);
            }
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void appbar_button2_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }
    }
}
</pre>
</li>
</ol>
<p>And thats it. We can now add a new note, view a list of current notes and delete an existing note. This note app for Windows Phone 7 is fairly simple in functionality, so naturally there&#8217;s many more features you can add. For example, we could allow the editing of notes, or the addition of different types of notes, such as sketches. I&#8217;ve added the completed project below.</p>
<p><img src='http://onishimura.s3.amazonaws.com/wp7home.png' alt='Windows Phone 7 Home' /></p>
<p><a href='http://onishimura.s3.amazonaws.com/code/MyNotes.zip'>Download the code here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/07/29/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-3/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Windows Phone 7 Tutorial – Creating a simple notes app with Silverlight Part 2</title>
		<link>http://onishimura.com/2010/07/27/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-2/</link>
		<comments>http://onishimura.com/2010/07/27/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-2/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 09:19:50 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=157</guid>
		<description><![CDATA[This is part 2 in a 3 part tutorial for creating a notes application using Silverlight and Windows Phone 7. The other articles can be read here Windows Phone 7 [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F27%2Fwindows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-2%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F27%2Fwindows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-2%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p style='font-style: italic;'>
	This is part 2 in a 3 part tutorial for creating a notes application using Silverlight and Windows Phone 7. The other articles can be read here<br />
	<a href='http://onishimura.com/2010/07/25/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-1/'>Windows Phone 7 Tutorial – Creating a simple notes app with Silverlight Part 1</a><br />
<a href='http://onishimura.com/2010/07/29/windows-phone-7-tutorialcreating-a-simple-notes-app-with-silverlight-part-3/'>Windows Phone 7 Tutorial – Creating a simple notes app with Silverlight Part 3</a>
	</p>
<p>	In part one of the tutorial we created the project, added a new Note class to serve as our model, and added a StorageHelper class to help us manage IsolatedStorage. The next step is to add support for adding a note to the app. We&#8217;ll keep it simple and just use a button on the main page&#8217;s application bar to add a note. When a user clicks the add note button on the main page, a new Windows Phone 7 page will load, which will enable the user to enter a note title and note text. They&#8217;ll also be able to save the note, or cancel the save, which will return them to the main page.</p>
<p><span id="more-157"></span></p>
<ol style='list-style-type:decimal;margin-left:0;line-height:150%'>
<li>
	Add default icons to the project in order to support adding a note, saving a note and canceling the action. When you install the Windows Phone 7 SDK it also installs a number of default icons in C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons. For our purposes we&#8217;re going to use the icons in the dark folder, specifically add the following to the Images folder:</p>
<ul>
<li>appbar.add.rest.png</li>
<li>appbar.save.rest.png</li>
<li>appbar.cancel.rest.png</li>
</ul>
<p>		After adding these icons, modify their properties so that their Resource type is Content and Copy to output directory is &#8216;Copy if newer&#8217;. This allows us to configure the IconUri property on the ApplicationBarIconButton to a path like the following: IconUri=&#8221;/Images/appbar.add.rest.png&#8221;.
	</li>
<li>
	Modify MainPage.xaml and MainPage.xaml.cs to do the following:</p>
<ul>
<li>Display the notes properly</li>
<li>Add a new application bar button</li>
<li>An event handler for the button&#8217;s click</li>
<li>Refresh the list of displayed notes whenever the page is navigated to. This will allow the user to see the new notes that they&#8217;ve added.</li>
</ul>
<p>	In MainPage.xaml change the StackPanel in MainListBox to the following:</p>
<pre class="brush: xml;">
&lt;StackPanel&gt;
   &lt;TextBlock x:Name="ItemText" Text="{Binding Title}" Margin="-2,-13,0,0" Style="{StaticResource PhoneTextExtraLargeStyle}"/&gt;
   &lt;TextBlock x:Name="DetailsText" Text="{Binding CreateDate}" Margin="0,-6,0,3" Style="{StaticResource PhoneTextSubtleStyle}"/&gt;
&lt;/StackPanel&gt;
</pre>
<p>	This allows the notes to be displayed on the main page, displaying the note&#8217;s title and createdate. Now add the following application bar before the closing phone:PhoneApplicationPage tag</p>
<pre class="brush: xml;">
&lt;phone:PhoneApplicationPage.ApplicationBar&gt;
   &lt;shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"&gt;
        &lt;shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/Images/appbar.add.rest.png" Text="Add" Click="appbar_button1_Click"&gt;&lt;/shell:ApplicationBarIconButton&gt;
   &lt;/shell:ApplicationBar&gt;
&lt;/phone:PhoneApplicationPage.ApplicationBar&gt;
</pre>
<p>	This will add our appbar button and use the add icon we added earlier as it&#8217;s image. Next we change MainPage.xaml.cs to handle the app bar button&#8217;s click event. First add an event handler: </p>
<pre class="brush: csharp;">
        private void appbar_button1_Click(object sender, EventArgs e)
        {
            // Navigate to the new page
            NavigationService.Navigate(new Uri("/AddPage.xaml", UriKind.Relative));

            // Reset selected index to -1 (no selection)
            MainListBox.SelectedIndex = -1;
        }
	</pre>
<p>	This simply uses the base navigation framework in the windows phone 7 version of silverlight to navigate the user to the AddPage page, which we&#8217;ll add in a bit. Now modify the OnNavigatedTo method to refresh the data list whenever the page gets focus</p>
<pre class="brush: csharp;">
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (DataContext == null)
                DataContext = App.ViewModel;

            App.ViewModel.Refresh();
            MainListBox.ItemsSource = App.ViewModel.Items;
        }
	</pre>
</li>
<li>
Modify MainViewModel.cs to add a Refresh method that will set the ViewModel&#8217;s current Items property to the latest data in isolated storage. All we really need to do is call the Load method in our StorageHelper class</p>
<pre class="brush: csharp;wrap-lines:false;">
public void Refresh()
{
    Items = StorageHelper.Load&lt;ObservableCollection&lt;Note&gt;&gt;(App.NotesFileName);
}
</pre>
<p>Also, remove the code in the MainViewModel.cs constructor that initializes the ObservableCollection of ItemViewModels. The Refresh method will be called by the MainPage&#8217;s OnNavigateTo method (which is also called when the page is first displayed)
</li>
<li>
	Finally, add a new Silverlight xaml page, AddPage.xaml and configure it with Silverlight controls (textblocks and textboxes) for title and note. Additionally, add the application bar items to the AddPage.xaml file for saving and canceling, and modify AddPage.xaml.cs to handle the click events</p>
<p>	<img src='http://onishimura.s3.amazonaws.com/wp7add.png' alt='Add Page image' /></p>
<p>	The xaml for AddPage.xaml should look like the following. Note that we&#8217;re using the save and cancel icons we added earlier, for the application bar</p>
<pre class='brush: xml;wrap-lines:false;'>
&lt;phone:PhoneApplicationPage
    x:Class="MyNotes.AddPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True"&gt;

    &lt;!--LayoutRoot contains the root grid where all other page content is placed--&gt;
    &lt;Grid x:Name="LayoutRoot" Background="Transparent"&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height="Auto"/&gt;
            &lt;RowDefinition Height="*"/&gt;
        &lt;/Grid.RowDefinitions&gt;

        &lt;!--TitlePanel contains the name of the application and page title--&gt;
        &lt;StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12"&gt;
            &lt;TextBlock x:Name="ApplicationTitle" Text="My Notes" Style="{StaticResource PhoneTextNormalStyle}"/&gt;
            &lt;TextBlock x:Name="PageTitle" Text="Add Note" Margin="-3,-8,0,0" Style="{StaticResource PhoneTextTitle1Style}"/&gt;
        &lt;/StackPanel&gt;

        &lt;!--ContentPanel - place additional content here--&gt;
        &lt;Grid x:Name="ContentGrid" Grid.Row="1"&gt;
            &lt;TextBox Height="72" HorizontalAlignment="Left" Margin="14,68,0,0" Name="textTitle" Text="" VerticalAlignment="Top" Width="460" /&gt;
            &lt;TextBox Height="295" HorizontalAlignment="Left" Margin="14,192,0,0" Name="textNote" Text="" VerticalAlignment="Top" Width="460" /&gt;
            &lt;TextBlock Height="30" HorizontalAlignment="Left" Margin="24,32,0,0" Text="Title" VerticalAlignment="Top" /&gt;
            &lt;TextBlock Height="30" HorizontalAlignment="Left" Margin="24,156,0,0" Text="Note" VerticalAlignment="Top" /&gt;
        &lt;/Grid&gt;
    &lt;/Grid&gt;

    &lt;phone:PhoneApplicationPage.ApplicationBar&gt;
        &lt;shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"&gt;
            &lt;shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/Images/appbar.save.rest.png" Text="Save Note" Click="button1_Click"&gt;&lt;/shell:ApplicationBarIconButton&gt;
            &lt;shell:ApplicationBarIconButton x:Name="appbar_button2" IconUri="/Images/appbar.cancel.rest.png" Text="Cancel" Click="button2_Click"&gt;&lt;/shell:ApplicationBarIconButton&gt;
        &lt;/shell:ApplicationBar&gt;
    &lt;/phone:PhoneApplicationPage.ApplicationBar&gt;    

&lt;/phone:PhoneApplicationPage&gt;
</pre>
<p>The code behind for this page really only needs two events added to it, to save the note and navigate back to the main page, and to navigate back to the main page when the user clicks &#8216;cancel&#8217;</p>
<pre class='brush:csharp;'>
private void button1_Click(object sender, EventArgs e)
{
	Note newNote = new Note { Title = textTitle.Text, NoteText = textNote.Text, CreateDate = DateTime.Now };
	newNote.Save();

	NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}

private void button2_Click(object sender, EventArgs e)
{
	NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
</pre>
</li>
</ol>
<p>And thats it! We should now be able to add a note to our notes.dat file, and view the new note in a list of notes on our main page. As you can see adding controls and event handlers in silverlight and windows phone 7 is quick and easy. Next up, deleting a note&#8230;..</p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/07/27/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Windows Phone 7 Tutorial &#8211; Creating a simple notes app with Silverlight Part 1</title>
		<link>http://onishimura.com/2010/07/25/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-1/</link>
		<comments>http://onishimura.com/2010/07/25/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-1/#comments</comments>
		<pubDate>Sun, 25 Jul 2010 08:24:28 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=142</guid>
		<description><![CDATA[This is part 1 in a 3 part tutorial for creating a notes application using Silverlight and Windows Phone 7. The other articles can be read here Windows Phone 7 [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F25%2Fwindows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-1%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F25%2Fwindows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-1%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p style='font-style: italic;'>
This is part 1 in a 3 part tutorial for creating a notes application using Silverlight and Windows Phone 7. The other articles can be read here<br />
<a href='http://onishimura.com/2010/07/27/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-2/'>Windows Phone 7 Tutorial – Creating a simple notes app with Silverlight Part 2</a><br />
<a href='http://onishimura.com/2010/07/29/windows-phone-7-tutorialcreating-a-simple-notes-app-with-silverlight-part-3/'>Windows Phone 7 Tutorial – Creating a simple notes app with Silverlight Part 3</a>
</p>
<p>Admittedly a <a href='http://onishimura.com/2010/07/20/windows-phone-7-and-silverlight-getting-started-with-a-bouncing-ball/'>bouncing ball</a> on Windows Phone 7 isn&#8217;t all that useful, so I decided to create a sample application that could do a little more than draw a ball or say &#8216;hello world&#8217;. Ideally I wanted to work with some of the core concepts on the phone, such as lists, navigation and the application bar. Additionally I wanted a Windows Phone 7 app that persisted it&#8217;s data, which meant working with <a href='http://msdn.microsoft.com/en-us/library/ff626522(v=VS.92).aspx'>Isolated Storage</a>. Obviously this calls for a note-taking app&#8230;after all who doesn&#8217;t love taking notes? Notes are only second to bouncing balls in my book.</p>
<p>To keep the scope of the app small and focused, I wanted the note app to do only the following</p>
<ul>
<li>View a list of notes</li>
<li>Add a note</li>
<li>Delete a note</li>
</ul>
<p><span id="more-142"></span><br />
Pretty simple, right? The actual implementation turned out to be fairly quick as well. The full step by step is a little long for a single blog post so I&#8217;m breaking it up into three posts. The first post covers creating the project, adding a support class to help manage the isolated storage, and defining the model. The second post will cover adding a note, and the third post will cover deleting a note.</p>
<ol style='list-style-type:decimal;margin-left: 0;'>
<li>
		To start with, create a Windows Phone List Application, named MyNotes. This will create a basic silverlight template for managing list-based apps. The structure of the project follows the MVVM pattern, so the views are populated by ViewModel classes, defined in the ViewModel folder. </p>
<p><img src='http://onishimura.s3.amazonaws.com/wp7create.png' style='height:320px;width:480px' /></p>
<p>Here&#8217;s a quick run down of the files in the base list project:</p>
<ul>
<li><strong>MainPage.xaml</strong> : The initial screen of the site, which displays data in a ListBox named MainListBox by default. Selecting an item fires the MainListBox_SelectionChanged which navigates the user to the details page</li>
<li><strong>DetailsPage.xaml</strong> : Individual item details for each item in the list. Clicking on an item on the main page brings you here</li>
<li><strong>MainViewModelSampleData.xaml</strong> : Just as the name states, sample data that&#8217;s displayed during design time. Basically allows the design surface to render with the xaml designer.</li>
<li><strong>MainViewModel.cs</strong> : ViewModel for the MainPage, by default the project populates itself with dummy &#8220;runtime&#8221; data when the project is run. The application has a property, ViewModel, which is an instance of this class and used in both the main page and details page to show the items. </li>
<li><strong>ItemViewModel.cs</strong> : ViewModel for each individual item in the list. This default class has really only three properties, LineOne, LineTwo, LineThree, but also demonstrates an implementation for INotifyPropertyChanged</li>
</ul>
<p><img src='http://onishimura.s3.amazonaws.com/wp7initial.png' style='height:320px;width:480px' /></p>
</li>
<li>
	Create a helper class to save notes data. Local data storage using silverlight in Windows Phone 7 is currently limited to using <a href='http://msdn.microsoft.com/en-us/library/ff426930(v=VS.95).aspx#IsolatedStorage'>isolated storage</a>. There&#8217;s no limit on the amount of data that can be stored though, other than the physical limit of the device of course. I&#8217;ve used something similar to the following in the past (This uses System.Runtime.Serialization so you&#8217;ll have to add that as a reference):</p>
<pre class="brush: csharp;">
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;

namespace MyNotes
{
    public class StorageHelper
    {
        public static T Load&lt;T&gt;(string name) where T : class, new()
        {
            T loadedObject = null;
            using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream storageFileStream = new IsolatedStorageFileStream(name, System.IO.FileMode.OpenOrCreate, storageFile))
            {
                if (storageFileStream.Length > 0)
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    loadedObject = serializer.ReadObject(storageFileStream) as T;
                }
                if (loadedObject == null)
                {
                    loadedObject = new T();
                }
            }

            return loadedObject;
        }

        public static void Save&lt;T&gt;(string name, T objectToSave)
        {
            using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream storageFileStream = new IsolatedStorageFileStream(name, System.IO.FileMode.Create, storageFile))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(storageFileStream, objectToSave);
            }
        }

        public static void Delete(string name)
        {
            using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                storageFile.Remove();
            }
        }
    }
}
</pre>
</li>
<li>
		Instead of using the ItemViewModel class, we&#8217;re going to add our own Model, Note. This requires us to make changes in MainPage.xaml, MainViewModel.cs, DetailsPage.xaml and MainViewModelSampleData.xaml as well, to reflect the new properties. So, create a new folder title Models, and add the Note class below, to it.  Also, change all references from ItemViewModel to Note, as this will be the Model we&#8217;ll be using going forward (I just did a find and replace on the entire project). </p>
<pre class="brush: csharp;wrap-lines:false">
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.Serialization;

namespace MyNotes
{
    [DataContract]
    public class Note : INotifyPropertyChanged
    {
        private string title;
        [DataMember]
        public string Title
        {
            get
            {
                return title;
            }
            set
            {
                if (value != title)
                {
                    title = value;
                    NotifyPropertyChanged("Title");
                }
            }
        }

        private string noteText;
        [DataMember]
        public string NoteText
        {
            get
            {
                return noteText;
            }
            set
            {
                if (value != noteText)
                {
                    noteText = value;
                    NotifyPropertyChanged("NoteText");
                }
            }
        }

        private DateTime createDate;
        [DataMember]
        public DateTime CreateDate
        {
            get
            {
                return createDate;
            }
            set
            {
                if (value != createDate)
                {
                    createDate = value;
                    NotifyPropertyChanged("CreateDate");
                }
            }
        }

        public void Save()
        {
            ObservableCollection&lt;Note&gt; currentNotes = StorageHelper.Load&lt;ObservableCollection&lt;Note&gt;&gt;(App.NotesFileName);
            currentNotes.Add(this);
            StorageHelper.Save&lt;ObservableCollection&lt;Note&gt;&gt;(App.NotesFileName, currentNotes);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
</pre>
<p>For xaml files, such as MainViewModelSampleData.xaml you&#8217;ll need to change the properties that are bound, for example</p>
<pre class="brush: xml;">
&lt;local:MainViewModel.Items&gt;
	&lt;local:Note Title="design one" NoteText="Maecenas praesent accumsan bibendum" CreateDate="7/22/2010" /&gt;
	&lt;local:Note Title="design two" NoteText="Dictumst eleifend facilisi faucibus" CreateDate="7/22/2010" /&gt;
&lt;/local:MainViewModel.Items&gt;
</pre>
</li>
<li>
Modify your App.xaml.cs file to add the following property. This is just the name of the notes file that will be stored in isolated storage.</p>
<pre class="brush: csharp;">
	public static string NotesFileName
	{
		get { return "notes.dat"; }
	}
</pre>
</li>
</ol>
<p>	So now we have a fairly simple starting point. We have a main page, a details page, a class to help us manage isolated storage, and our base model class, Note. Next up, adding a note&#8230;</p>
<p>Part 2 is now up and can be read here<br />
<a href='http://onishimura.com/2010/07/27/windows-phone-7-tutorial%E2%80%93creating-a-simple-notes-app-with-silverlight-part-2/'>Windows Phone 7 Tutorial – Creating a simple notes app with Silverlight Part 2</a></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/07/25/windows-phone-7-tutorial-creating-a-simple-notes-app-with-silverlight-part-1/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Windows Phone 7 &#8211; List of Tutorials and Resources</title>
		<link>http://onishimura.com/2010/07/22/windows-phone-7-list-of-tutorials-and-resources/</link>
		<comments>http://onishimura.com/2010/07/22/windows-phone-7-list-of-tutorials-and-resources/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 08:11:41 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=133</guid>
		<description><![CDATA[Following up on yesterday&#8217;s post on Windows Phone 7 development, here&#8217;s a few of the tutorials and guides I&#8217;ve been looking at the past few days. There&#8217;s a lot of [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F22%2Fwindows-phone-7-list-of-tutorials-and-resources%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F22%2Fwindows-phone-7-list-of-tutorials-and-resources%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Following up on yesterday&#8217;s <a href='http://onishimura.com/2010/07/20/windows-phone-7-and-silverlight-getting-started-with-a-bouncing-ball/'>post on Windows Phone 7 development</a>, here&#8217;s a few of the tutorials and guides I&#8217;ve been looking at the past few days. There&#8217;s a lot of info to digest so I&#8217;ll be adding to this post as I come across more resoucres.</p>
<h2>Tutorials and Samples</h2>
<ul>
<li>
		Scott Guthrie&#8217;s Tutorial<br />
		<a href='http://weblogs.asp.net/scottgu/archive/2010/03/18/building-a-windows-phone-7-twitter-application-using-silverlight.aspx'>http://weblogs.asp.net/scottgu/archive/2010/03/18/building-a-windows-phone-7-twitter-application-using-silverlight.aspx</a>
	</li>
<li>
		Introduction to Silverlight on Windows Phone 7 &#8211; Creating a list application<br />
		<a href='http://10rem.net/blog/2010/03/15/building-your-first-silverlight-for-windows-phone-application'>http://10rem.net/blog/2010/03/15/building-your-first-silverlight-for-windows-phone-application</a>
	</li>
<li>
		Introduction to XNA<br />
		<a href='http://mobile.tutsplus.com/tutorials/windows/introduction-to-xna-on-windows-phone-7/'>http://mobile.tutsplus.com/tutorials/windows/introduction-to-xna-on-windows-phone-7/</a>
	</li>
<li>
		Channel 9 Developer Training Kit<br />
		<a href='http://channel9.msdn.com/learn/courses/WP7TrainingKit/'>http://channel9.msdn.com/learn/courses/WP7TrainingKit/</a>
	</li>
<li>
		Code Samples for Windows Phone<br />
		<a href='http://msdn.microsoft.com/en-us/library/ff431744(VS.92).aspx'>http://msdn.microsoft.com/en-us/library/ff431744(VS.92).aspx</a>
	</li>
<li>
		Charles Petzold&#8217;s Free ebook<br />
		<a href='http://blogs.msdn.com/b/microsoft_press/archive/2010/03/15/free-ebook-programming-windows-phone-7-series-draft-preview.aspx'>http://blogs.msdn.com/b/microsoft_press/archive/2010/03/15/free-ebook-programming-windows-phone-7-series-draft-preview.aspx</a>
	</li>
</ul>
<p><span id="more-133"></span></p>
<h2>Blogs/Community</h2>
<ul>
<li>
		Windows Phone Developer Blog<br />
		<a href='http://windowsteamblog.com/Windows_Phone/b/wpdev/'>http://windowsteamblog.com/Windows_Phone/b/wpdev/</a>
	</li>
<li>
		Smarty Pants Coding<br />
		<a href='http://www.smartypantscoding.com/'>http://www.smartypantscoding.com/</a>
	</li>
<li>
		Nick Gravelyn&#8217;s Blog &#8211; Focused on the XNA Framework and game development<br />
		<a href='http://blogs.msdn.com/b/nicgrave/'>http://blogs.msdn.com/b/nicgrave/</a>
	</li>
<li>
		Jesse Liberty &#8211; Check out the mini-tutorials<br />
		<a href='http://jesseliberty.com/Tags/phone/'>http://jesseliberty.com/Tags/phone/</a>
	</li>
<li>
		Paul Thurrott<br />
		<a href='http://windowsphonesecrets.com/'>http://windowsphonesecrets.com/</a>
	</li>
<li>
		Windows Phone 7 Forums<br />
		<a href='http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/threads'>http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/threads</a>
	</li>
</ul>
<h2>Documentation and Resources</h2>
<ul>
<li>
		Official Developer Portal<br />
		<a href='http://developer.windowsphone.com/'>http://developer.windowsphone.com/</a>
	</li>
<li>
		Class Library Reference<br />
		<a href='http://msdn.microsoft.com/en-us/library/ff626516(v=VS.92).aspx'>http://msdn.microsoft.com/en-us/library/ff626516(v=VS.92).aspx</a>
	</li>
<li>
		Programming Guide for Windows Phone<br />
		<a href='http://msdn.microsoft.com/en-us/library/ff402551(v=VS.92).aspx'>http://msdn.microsoft.com/en-us/library/ff402551(v=VS.92).aspx</a>
	</li>
<li>
		Developer Tools Resouces &#8211; Getting started and Developer Fundamentals<br />
		<a href='http://msdn.microsoft.com/en-us/library/ff402523(v=VS.92).aspx'>http://msdn.microsoft.com/en-us/library/ff402523(v=VS.92).aspx</a>
	</li>
<li>
		Design Resources<br />
		<a href='http://msdn.microsoft.com/en-us/library/ff637515(VS.92).aspx'>http://msdn.microsoft.com/en-us/library/ff637515(VS.92).aspx</a>
	</li>
<li>
		Windows Phone 7 Jump Start Training Resources<br />
		<a href='http://borntolearn.mslearn.net/wp7/m/classresources/default.aspx'>http://borntolearn.mslearn.net/wp7/m/classresources/default.aspx</a>
	</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/07/22/windows-phone-7-list-of-tutorials-and-resources/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Windows Phone 7 and Silverlight &#8211; Getting started with a Bouncing Ball</title>
		<link>http://onishimura.com/2010/07/20/windows-phone-7-and-silverlight-getting-started-with-a-bouncing-ball/</link>
		<comments>http://onishimura.com/2010/07/20/windows-phone-7-and-silverlight-getting-started-with-a-bouncing-ball/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 23:55:36 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=124</guid>
		<description><![CDATA[The beta of the developer tools for Windows Phone 7 was released last week. I was curious to see how different/easy it was to develop for this platform so I [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F20%2Fwindows-phone-7-and-silverlight-getting-started-with-a-bouncing-ball%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F20%2Fwindows-phone-7-and-silverlight-getting-started-with-a-bouncing-ball%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>The beta of the developer tools for Windows Phone 7 was <a href='http://weblogs.asp.net/scottgu/archive/2010/07/12/windows-phone-7-developer-tools-beta-released.aspx'>released last week</a>. I was curious to see how different/easy it was to develop for this platform so I decided to convert my old SL 3 bouncing ball app, done <a href='http://onishimura.com/2009/03/25/getting-started-with-silverlight-3-hello-bouncing-ball/'>AGES</a> ago, to Silverlight 4 and Windows Phone 7. The process was pretty painless and even allowed me to add a few features:</p>
<p>1. Install the tools from <a href='http://www.microsoft.com/downloads/details.aspx?FamilyID=c8496c2a-54d9-4b11-9491-a1bfaf32f2e3&#038;displaylang=en'>http://www.microsoft.com/downloads/details.aspx?FamilyID=c8496c2a-54d9-4b11-9491-a1bfaf32f2e3&#038;displaylang=en</a> if you haven&#8217;t already</p>
<p>2. Create a new Windows Phone Application (from templaes: Visual C# &#8211; Silverlight for Windows Phone &#8211; Windows Phone Application)</p>
<p><span id="more-124"></span><br />
3. Modify the ContentGrid, change it to a canvas and add an ellipse:</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
&lt;Canvas x:Name="ContentCanvas" Grid.Row="1"&gt;
	&lt;Ellipse Canvas.Left="350" Canvas.Top="150" Width="75" Height="75" Name="ellipseObject" Canvas.ZIndex="1" &gt;
		&lt;Ellipse.Fill&gt;
			&lt;LinearGradientBrush StartPoint='0.1,0.06' EndPoint='0.5,0.6'&gt;
				&lt;GradientStop Color='#FFFFFFFF' Offset='0'/&gt;
				&lt;GradientStop Color='#FF87BF1B' Offset='1'/&gt;
			&lt;/LinearGradientBrush&gt;
		&lt;/Ellipse.Fill&gt;
	&lt;/Ellipse&gt;
&lt;/Canvas&gt;
</pre>
<p>4. Uncomment the sample app bar code and change it to the following, to add a click event and some descriptive text:</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
&lt;phone:PhoneApplicationPage.ApplicationBar&gt;
	&lt;shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"&gt;
		&lt;shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/Images/appbar_button1.png" Text="Start" Click="appbar_button1_Click" &gt;&lt;/shell:ApplicationBarIconButton&gt;
	&lt;/shell:ApplicationBar&gt;
&lt;/phone:PhoneApplicationPage.ApplicationBar&gt;
</pre>
<p>5. In the code behind add the following private instance variables, which are used to determine the initial speed of the ball and the current state of the ball:</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
private int xVelocity = 5;
private int yVelocity = 5;
private bool isBouncing = false;
</pre>
<p>6. Add a helper method to start a new bounce, randoming the directions and speed:</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
private void startNewBounce()
{
	//Make speed, direction random
	Random r = new Random();
	xVelocity = r.Next(3, 10);
	yVelocity = r.Next(3, 10);
	int coin = r.Next(100);
	if (coin > 50)
	{
		xVelocity *= -1;
	}
	coin = r.Next(100);
	if (coin > 50)
	{
		yVelocity *= -1;
	}

	ellipseStoryboard.Begin();
	isBouncing = true;
}
</pre>
<p>7. Add the storyboard_Completed event. This will move the ellipse and also check for collisions against the layoutroots dimensions. If a collision is found it will reverse the direction. Note that the Y axis is a little funnky here, I had to tweak the upper and lower bounds a bit, partially because of the space the title grid takes up.</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
protected void ellipseStoryboard_Completed(object sender, EventArgs e)
{
	double ellipseX = (double)ellipseObject.GetValue(Canvas.LeftProperty);
	double ellipseY = (double)ellipseObject.GetValue(Canvas.TopProperty);

	//NOTE: canvas.width - ellipse.width for max, since the left and top properties
	//are based on upper left corner of the object
	//+/- 250 if title is present
	if (ellipseX >= (LayoutRoot.ActualWidth - ellipseObject.ActualWidth) || ellipseX <= 0)
	{
		xVelocity *= -1;
	}
	if (ellipseY >= ((LayoutRoot.ActualHeight - 300) + ellipseObject.ActualHeight) || ellipseY <= -150)
	{
		yVelocity *= -1;
	}

	ellipseX += xVelocity;
	ellipseY += yVelocity;

	ellipseObject.SetValue(Canvas.LeftProperty, ellipseX);
	ellipseObject.SetValue(Canvas.TopProperty, ellipseY);

	ellipseStoryboard.Begin();
}
</pre>
<p>8. Add an event handler for the app bar button click. All we need to do is start a new bounce (if the ball is already moving this will change the speed/direction of the ball too):</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
private void appbar_button1_Click(object sender, EventArgs e)
{
	startNewBounce();
}
</pre>
<p>9. One last piece of functionality, add a start/stop toggle if the user touches the screen. On the emulator this boils down to basically clicking the mouse on the screen. The events used to detect touch inputs are OnManipulationStarted, OnManipulationDelta and OnManipulationComepleted. </p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
protected override void OnManipulationStarted(ManipulationStartedEventArgs e)
{
	base.OnManipulationStarted(e);
	if (isBouncing)
	{
		ellipseStoryboard.Stop();
		isBouncing = false;
	}
	else
	{
		ellipseStoryboard.Begin();
		isBouncing = true;
	}

}
</pre>
<p>10. Hit f5 and let the emulator load up, it could take a bit but even on my old machine it wasn't too bad. A lot faster than the Android emulator in Eclipse was at least.</p>
<p><img src='http://onishimura.s3.amazonaws.com/phone7ball.png' alt='Windows Phone 7 Bouncing Ball Sample'></a></p>
<p>The fact that the development language and environment is <a href='http://msdn.microsoft.com/en-us/library/ff426931(v=VS.95).aspx'>pretty much the same</a> is compelling. There are <a href='http://msdn.microsoft.com/en-us/library/ff426930(VS.95).aspx'>some differences</a> though. Debugging in the emulator worked failry well too, clicking on the home button would stop the debugging process but leave the emulator running. Performance on the emulator wasn't fantastic but I guess that's to be expected. Just means I need to get a new computer. As I mentioned I did have to make some adjustments in the collision detection code to account for the title, but there's still a small bar at the top of the emulator that makes it look like the ball isn't hitting the exact top. It might look better on an actual device though, tough to say without having a device to test on.</p>
<p><a href='http://onishimura.s3.amazonaws.com/code/BouncingBall.zip'>Download the code here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/07/20/windows-phone-7-and-silverlight-getting-started-with-a-bouncing-ball/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Facebook C# &#8211; Sample ASP.NET application and access tokens</title>
		<link>http://onishimura.com/2010/07/19/8-facebook-c-sample-asp-net-application-and-access-tokens/</link>
		<comments>http://onishimura.com/2010/07/19/8-facebook-c-sample-asp-net-application-and-access-tokens/#comments</comments>
		<pubDate>Mon, 19 Jul 2010 08:05:58 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Facebook]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=116</guid>
		<description><![CDATA[Put together another quick sample app, this time for ASP.NET 4.0, instead of MVC. I&#8217;ve also added an example of how to post to a user&#8217;s wall, using the Facebook [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F19%2F8-facebook-c-sample-asp-net-application-and-access-tokens%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F19%2F8-facebook-c-sample-asp-net-application-and-access-tokens%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Put together another quick sample app, this time for ASP.NET 4.0, instead of MVC.<br />
I&#8217;ve also added an example of how to post to a user&#8217;s wall, using the <a href='http://github.com/facebook/csharp-sdk'>Facebook C# SDK</a></p>
<p><img src='http://onishimura.s3.amazonaws.com/fb-aspnet.png' alt='Facebook ASPNET Sample'  width='500px' height='259px' /></p>
<p><span id="more-116"></span><br />
As I mentioned earlier, the facebookconnect class included is just a helper class I used to pull values out of the fbs_[appid] cookie. You can get the access_token out of the cookie directly if you want using something like the following:</p>
<p>string accessToken = HttpContext.Current.Request.Cookies["fbs_" + ConfigurationManager.AppSettings["AppID"]]["\"access_token"];</p>
<p>Assuming you have AppID as an appsetting in your web.config. Also, as usual you should change the app id in the sample project to match whatever your current app is using.</p>
<p><a href='http://onishimura.s3.amazonaws.com/code/FacebookSampleASPNETApp.zip'>Download the code here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/07/19/8-facebook-c-sample-asp-net-application-and-access-tokens/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Official Facebook C# SDK Released</title>
		<link>http://onishimura.com/2010/07/17/official-facebook-c-sdk-released/</link>
		<comments>http://onishimura.com/2010/07/17/official-facebook-c-sdk-released/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 05:53:11 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Facebook]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=109</guid>
		<description><![CDATA[Looks like a brand new SDK to play with for facebook. While they have other sdks for python, php, javascript, etc, this is their first official C# SDK. Previously the [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F17%2Fofficial-facebook-c-sdk-released%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2010%2F07%2F17%2Fofficial-facebook-c-sdk-released%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Looks like a <a href='http://developers.facebook.com/blog/post/395'>brand new SDK</a> to play with for facebook. While they have other sdks for python, php, javascript, etc, this is their first official C# SDK. Previously the primary SDK that was available was the <a href='http://facebooktoolkit.codeplex.com/'>Facebook Developers Toolkit</a>, which hasn&#8217;t been updated in some time (and hasn&#8217;t been updated to support the open graph api as far as I can tell).</p>
<p>You can grab the code from github at <a href='http://github.com/facebook/csharp-sdk'>http://github.com/facebook/csharp-sdk</a>. </p>
<p><span id="more-109"></span><br />
One interesting thing to note, the current alpha build doesn&#8217;t provide a method to get an access token for the current user. The access token allows you to perform authorized requests on behalf of a user, and can be obtained via a redirect from Facebook, after the user has authenticated themselves. Without that token you can only access public data for a given user. The code is fairly simple in that case (this is taken directly from the console sample application on github):</p>
<pre style="border: 1px solid #888; background-color: #ddf; width: 95%; overflow: scroll; height: 115px; padding: 5px;">
string token = null;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(token);
JSONObject me = api.Get("/4");
Console.WriteLine(me.Dictionary["name"].String);
</pre>
<p>Essentially, when you pass in a null token you can only access a user&#8217;s public data by passing in the user&#8217;s Facebook ID. 4 is apparently Mark Zuckerberg&#8217;s FB ID, makes me wonder who the <a href='http://en.wikipedia.org/wiki/Eduardo_Saverin'>first</a> <a href='http://en.wikipedia.org/wiki/Dustin_Moskovitz'>three</a> <a href='http://en.wikipedia.org/wiki/Chris_Hughes_(Facebook)'>were</a>.</p>
<p>In any case, the lack of a way to obtain a user&#8217;s access_token makes sense since the SDK is meant to be used in multiple types of apps. This sounds like an opportunity to write some code, YAY! I&#8217;ve actually already detailed some of this <a href='http://onishimura.com/2010/06/07/converting-a-facebook-connect-site-to-open-graph-step-by-step/'>previously</a>. </p>
<p>Retrieving the access_token is pretty straightforward, since it&#8217;s available in a cookie that the user gets after authenticating. The name of this cookie is fbs_[AppID], where [AppID] is whatever <a href='http://www.facebook.com/developers/'>application id facebook assigned to you</a>. I&#8217;ve created a sample ASP.NET MVC 2 application that demonstrates this. It uses a simple wrapper class (FacebookConnect) to pull out the access_token for the currently logged in user, available as a property. Once you have the access_token you can then make authorized requests for the user:</p>
<pre style="border: 1px solid #888; background-color: #ddf; width: 95%; overflow: scroll; height: 115px; padding: 5px;">
FacebookConnect fbConnect = new FacebookConnect();
if (fbConnect.IsConnected)
{
    Facebook.FacebookAPI api = new Facebook.FacebookAPI(fbConnect.AccessToken);
    JSONObject me = api.Get("/" + fbConnect.UserID);
    name = me.Dictionary["name"].String;
}
</pre>
<p>I did run into an issue when setting the access_token on the FacebookAPI object. When the url is constructed it passes the Dictionary to an EncodeDictionary method (line 205 in FacebookAPI.cs), which encodes the key-value pairs using the HttpUtility.UrlEncode method. This caused problems when making calls to the graph, specifically an OAuthException : Invalid OAuth access token. Calls typically look like the following url (note that I&#8217;ve personally tweaked these urls so they wont actually work now, I&#8217;ve listed them just to demonstrate the issue):</p>
<p>https://graph.facebook.com/727440495?access_token=132568260112276|2.Z_FaL6rzoNMt2D3jfnEaWP__.3600.1279345500-727440495|77SIciuK333BmipPho0EIdJ8bwl.</p>
<p>or, after encoding</p>
<p>https://graph.facebook.com/727440495?access_token=132568260112276%7C2.Z_FaL6rzoNMt2D3jfnEaWP__.3600.1279345500-727440495%7C77SIciuK333BmipPho0EIdJ8bwl.</p>
<p>After the call to the EncodeDictionary method the url looks like this:</p>
<p>https://graph.facebook.com/727440495?access_token=132568260112276%257C2.Z_FaL6rzoNMt2D3jfnEaWP__.3600.1279345500-727440495%257C77SIciuK333BmipPho0EIdJ8bwl.</p>
<p>The pipe character in the original url is being double encoded to %257C. So when you try calling this url you get this returned:</p>
<pre style="border: 1px solid #888; background-color: #ddf; width: 95%; overflow: scroll; height: 115px; padding: 5px;">
{
   "error": {
      "type": "OAuthException",
      "message": "Invalid OAuth access token."
   }
}
</pre>
<p>The web exception thrown in the project is slightly more vague &#8220;The remote server returned an error: (400) Bad Request.&#8221;</p>
<p>For the time being I&#8217;ve just modified the FacebookAPI.cs class in the project to check for &#8220;access_token&#8221;, and skip encoding if an access token is passed in, though I guess another solution could be to just make sure you UrlDecode any access token you pass into the constructor:</p>
<pre style="border: 1px solid #888; background-color: #ddf; width: 95%; overflow: scroll; height: 115px; padding: 5px;">
if (kvp.Key.ToLower() == "access_token")
{
	sb.Append(kvp.Value);
}
else
{
	sb.Append(HttpUtility.UrlEncode(kvp.Value));
}
</pre>
<p>A couple of other things to note:<br />
1. This is a MVC 2 web app, in Visual Studio 2010<br />
2. You need to set your app id in the web.config file<br />
3. I&#8217;ve also included two classes that I&#8217;ve used on previous projects to make calls to the open graph api, DEMOOpenGraph and DEMOFacebookUser. These use a DataContract and the DataContractJsonSerializer class to populate a strongly typed object. Below is some sample code showing it&#8217;s use:</p>
<pre style="border: 1px solid #888; background-color: #ddf; width: 95%; overflow: scroll; height: 115px; padding: 5px;">
OpenGraph graph = new OpenGraph();
facebookUser = graph.GetCurrentUser(FacebookConnect.AccessToken);
string firstName = facebookUser.First_Name;
</pre>
<p>This is obviously less flexible than the dictionary that the official API uses<br />
4. You should also set the AppID value in web.config to your own value, I&#8217;ve left my own sample appid in there.</p>
<p><a href='http://onishimura.s3.amazonaws.com/code/FacebookSampleMVC2App.zip'>Download the code here</a></p>
<p><b>UPDATE</b><br />
I&#8217;ve reworked the sample and provided a description for some of the new functionality here </p>
<p><a href='http://onishimura.com/2010/08/11/facebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts/'>http://onishimura.com/2010/08/11/facebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2010/07/17/official-facebook-c-sdk-released/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

