<?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 &#187; Silverlight</title>
	<atom:link href="http://onishimura.com/category/silverlight/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>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>Silverlight 3 &#8211; Simple consumption of a WCF Service</title>
		<link>http://onishimura.com/2009/03/29/silverlight-3-wcf-service/</link>
		<comments>http://onishimura.com/2009/03/29/silverlight-3-wcf-service/#comments</comments>
		<pubDate>Sun, 29 Mar 2009 23:59:28 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=41</guid>
		<description><![CDATA[Last night we were *supposed* to watch Monsters vs. Aliens but unfortunately those plans went out the window once I realized I was missing a credit card. I managed to [...]]]></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%2F2009%2F03%2F29%2Fsilverlight-3-wcf-service%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2009%2F03%2F29%2Fsilverlight-3-wcf-service%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_354251666833c9af8376ce38ad1460f1&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Last night we were *supposed* to watch Monsters vs. Aliens but unfortunately those plans went out the window once I realized I was missing a credit card. I managed to find it eventually but since we had missed the movie I figured I&#8217;d spend some time playing around with Silverlight 3 and WCF to see if there were any big changes in the beta (other than the obvious <a href="http://blogs.msdn.com/brada/archive/2009/03/19/what-is-net-ria-services.aspx">new RIA Services</a>). I&#8217;ve used WCF in past silverlight projects and for the most part there were no real changes in Silverlight 3. A quick rundown of the steps involved:</p>
<ol>
<li>Add a new Silverlight project</li>
<li>Add a new Linq to Sql class (Add New Item &#8211; Linq to Sql Classes) and add a table from an existing database to the designer (e.g. Orders from Northwind)</li>
<li>Add a new WCF Service to the web project and modify your service implemntation to return a list of orders. (Add New Item &#8211; WCF Service). Note that this is a standard WCF service and not a Silverlight-enabled WCF Service.</li>
<li>Modify the endpoint element in your web.config so that it used basicHttpBinding instead of wsHttpBinding (Silverlight only supports basic binding)</li>
<li>Add a datagrid to your MainPage.xaml</li>
<li>Add a Service Reference to the Silverlight project for brevity&#8217;s sake. Ensure the ServiceReferences.ClientConfig has the proper values for the endpoint (especially the address and contract attributes). David Betz has a good <a href="http://www.netfxharmonics.com/2008/11/Understanding-WCF-Services-in-Silverlight-2">overview of WCF</a> and <a href="http://www.netfxharmonics.com/2008/12/Reusing-NET-Assemblies-in-Silverlight">assembly reuse</a> in Silverlight.</li>
<li>Modify the MainPage.xaml.cs to load the appropriate data on the load event. For example:</li>
</ol>
<p><span id="more-41"></span></p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
ServiceReference1.Service1Client svc = new SL2WCF.ServiceReference1.Service1Client();
svc.GetAllOrdersCompleted += (object aSender, SL2WCF.ServiceReference1.GetAllOrdersCompletedEventArgs args) =&gt;
{
dgMain.ItemsSource = args.Result;
};
svc.GetAllOrdersAsync();
}
</pre>
<p>No real issues compared to SL 2, but a few gotchas you might run into&#8230;.</p>
<p>1. When a new service reference is added to a Silverlight 3 project, a ServiceReferences.ClientConfig file is automatically created. However, it seems to set the default contract attribute on the endpoint element to the wrong value. When you run the project for the first time after adding a reference, you&#8217;ll likely get the following error:</p>
<div style="border:1px solid #888;color:red;width:95%;padding:5px;">
Could not find default endpoint element that references contract &#8216;ProjectName.ServiceReference1.IService1&#8242; in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
</div>
<p>If you look at the config file you&#8217;ll see contract=&#8221;ServiceReference1.IService1&#8243;. This needs to be a fully qualified namespace, and should be changed to contract=&#8221;ProjectName.ServiceReference1.IService1&#8243; (or whatever namespace is specified in your Reference.cs file)</p>
<p>2. If you&#8217;re using the dbml designer and have relationships defined between your objects, you&#8217;ll likely get an error thrown during the serialization process due to a circular reference. You may get an exception like the following:</p>
<div style="border:1px solid #888;color:red;width:95%;padding:5px;">
ex = {&#8220;Object graph for type &#8216;System.Data.Linq.EntitySet`1[[SL2WCF.Web.ListInvite, SL2WCF.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]&#8217; contains cycles and cannot be serialized if reference tracking is disabled.&#8221;}
</div>
<p>The primary symptom of this is that your service is called properly without errors, but nothing is returned to the silverlight client. You need to do 2 things in order to <a href="http://www.codeexperiment.com/post/Returning-LINQ-to-SQL-Entities-From-WCF.aspx">resolve</a> the circular reference</p>
<ul>
<li>Use DataLoadOptions with the DataContext before executing the linq command</li>
<li>Set the Serialization Mode for the dbml to Unidirectional &#8211; Essentially this will add the DataContract attribute to your generated classes in ListDb.designer.cs</li>
</ul>
<p>3. Silverlight cannot handle faults so if your Silverlight WCF Web Service call returns the following:</p>
<div style="border:1px solid #888;color:red;width:95%;padding:5px;">
The remote server returned an error: NotFound
</div>
<p>it could be for a number of reasons. To help debug this you can use <a href="http://timheuer.com/blog/archive/2008/06/10/silverlight-services-cross-domain-404-not-found.aspx">Web Development Helper</a> or <a href="http://www.bbits.co.uk/blog/archive/2008/09/12/debugging-wcf-services-in-silverlight-2.aspx">turn on tracing</a></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2009/03/29/silverlight-3-wcf-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with Silverlight 3 &#8211; Hello Bouncing Ball</title>
		<link>http://onishimura.com/2009/03/25/getting-started-with-silverlight-3-hello-bouncing-ball/</link>
		<comments>http://onishimura.com/2009/03/25/getting-started-with-silverlight-3-hello-bouncing-ball/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 19:44:25 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[BouncingBalls]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=14</guid>
		<description><![CDATA[I&#8217;ve been playing with Silverlight 3 lately and thought I&#8217;d post a quick guide on getting started. Note that once installed you can only develop silverlight 3 applications since VS doesn&#8217;t [...]]]></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%2F2009%2F03%2F25%2Fgetting-started-with-silverlight-3-hello-bouncing-ball%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2009%2F03%2F25%2Fgetting-started-with-silverlight-3-hello-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>I&#8217;ve been playing with Silverlight 3 lately and thought I&#8217;d post a quick guide on getting started. Note that once installed you can only develop silverlight 3 applications since VS doesn&#8217;t support multi-targeting for Silverlight apps.</p>
<p>Also, in order to start the initial install you&#8217;ll have to uninstall any previous betas of Blend you may have installed. I had Expression Blend 2.5 installed and received this: Beta and preview versions of Microsoft Expression Blend must be uninstalled before installation can continue. Don&#8217;t worry about Silverlight 2, it will automatically uninstall Silverlight 2 for you. All of the links below are available at <a href="http://silverlight.net/getstarted/silverlight3/default.aspx">http://silverlight.net/getstarted/silverlight3/default.aspx</a>, I&#8217;ve just added direct links to the files.</p>
<ol>
<li><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=11dc7151-dbd6-4e39-878f-5081863cbb5d&amp;displaylang=en">Download and install Silverlight 3 Tools</a>  (which will also install the SDK and runtime) : Silverlight 3 Toolkit March 2009.msi. Installs to C:Program FilesMicrosoft Silverlight</li>
<li><a href="http://www.microsoft.com/expression/try-it/blendpreview.aspx">Download and install Expression Blend 3 Preview</a> : Blend_Trial_en.exe. Installs to Installs to C:Program FilesMicrosoft Expression</li>
<li><a href="http://silverlight.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=20430">Download and install the Silverlight 3 Toolkit</a> : Silverlight3_Tools.exe.  Installs to C:Program FilesMicrosoft SDKsSilverlightv3.0ToolkitMarch 2009</li>
<li><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&amp;displaylang=en">Download and install .NET RIA Services preview</a> : RiaServices.msi. Installs to C:Program FilesMicrosoft SDKsRIA Services</li>
</ol>
<p>Siverlight 3 Videos : <a href="http://silverlight.net/learn/videocat.aspx?cat=12#sl3">http://silverlight.net/learn/videocat.aspx?cat=12#sl3</a><br />
Silverlight 3 Labs : <a href="http://silverlight.net/learn/labs.aspx">http://silverlight.net/learn/labs.aspx</a></p>
<p><span id="more-14"></span><br />
One thing to keep in mind, with any new silverlight install, you may need to add the .xap MIME type to IIS (or the web project&#8217;s web.config) if you&#8217;re running it via IIS instead of casini. This is usually the case when you get a Sys.InvalidOperationException : Could not download the Silverlight application. To do this, add .xap to the MIME types under the IIS category on the main page, and map it to application/x-silverlight-app.</p>
<p>To verify the install worked, let&#8217;s create a Hello World application. Create a new project in Silverlight 3 and select &#8216;Silverligh Application&#8217; as it&#8217;s type. Select the defaults for hosting the project in a new asp.net web site. Once the project has loaded modify the MainPage.xaml file so that it looks like this:</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
&lt;UserControl xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" x:Class="SilverlightHelloWorld.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="500" Height="700"&gt;
	&lt;controls:Label Content="Hello World"&gt;&lt;/controls:Label&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;
</pre>
<p>Essentially all I&#8217;ve done here is to add the controls namespace to the UserControl, and added a label with &#8216;Hello World&#8217; as it&#8217;s content. While this is great for verifying an install it&#8217;s pretty boring considering the cool things silverlight is capable of, so I decided to add a bouncing ball to play a bit with the animations in Silverlight. First let&#8217;s add a game loop in the form of a storyboard to MainPage.xaml:</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">
&lt;UserControl.Resources&gt;
	&lt;!-- Game loop --&gt;
	&lt;Storyboard x:Name="ellipseStoryboard" Completed="ellipseStoryboard_Completed"&gt;
	&lt;/Storyboard&gt;
&lt;/UserControl.Resources&gt;
</pre>
<p>Note that there&#8217;s really no animations defined here so it will just call the Completed event immediately. Next, add a canvas and an ellipse to the LayoutRoot of the page:</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">&lt;Canvas Name="canvasMain" Background="Gray"&gt;
	&lt;Ellipse Fill="Blue" Canvas.Left="350" Canvas.Top="150"
		Width="50" Height="50" Name="ellipseObject"&gt;
	&lt;/Ellipse&gt;
&lt;/Canvas&gt;
</pre>
<p>The designer should show a blue ball on a gray background. Now modify the MainPage class to begin the storyboard and move the ball in the ellipseStoryboard_Completed event:</p>
<pre style="border:1px solid #888;background-color:#ddf;width:95%;overflow:scroll;padding:5px;">public partial class MainPage : UserControl
    {
        private int xVelocity = 5;
        private int yVelocity = 5;

        public MainPage()
        {
            InitializeComponent();

            ellipseStoryboard.Begin();
        }

        ///
        /// Storyboard loop : this plays continuously since we have nothing defined for the storyboard
        ///
        ///
        ///
        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
            if (ellipseX >= (canvasMain.ActualWidth - ellipseObject.ActualWidth) || ellipseX <= 0)
            {
                xVelocity *= -1;
            }
            if (ellipseY >= ((canvasMain.ActualHeight) + ellipseObject.ActualHeight) || ellipseY <= 0)
            {
                yVelocity *= -1;
            }

            ellipseX += xVelocity;
            ellipseY += yVelocity;

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

            ellipseStoryboard.Begin();
        }
    }
</pre>
<p>This starts the storyboard in the page's constructor, modifies the position and velocity of the ellipse based on it's current position, and reverses velocity if a border has been reached. Note that we call storyboard.begin() again at the end of the completed event, in order to ensure it continuously loops. There's a lot of different ways to implement this, such as using a DispatcherTimer</p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2009/03/25/getting-started-with-silverlight-3-hello-bouncing-ball/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Big news day from Mix 09</title>
		<link>http://onishimura.com/2009/03/18/mix-09-news/</link>
		<comments>http://onishimura.com/2009/03/18/mix-09-news/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 09:04:19 +0000</pubDate>
		<dc:creator>onishimura</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://onishimura.com/?p=62</guid>
		<description><![CDATA[Lots of news coming out of Mix 09&#8230;. ASP.NET MVC Released Scott Guthrie recently posted a great (and free) tutorial from his upcoming book here. Not a whole 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%2F2009%2F03%2F18%2Fmix-09-news%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fonishimura.com%2F2009%2F03%2F18%2Fmix-09-news%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 news coming out of Mix 09&#8230;.</p>
<h2><span style="font-weight:normal;">ASP.NET MVC Released</span></h2>
<p><span style="font-weight:normal;">Scott Guthrie recently posted a great (and free) tutorial from his upcoming book <a href="http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx">here</a>. Not a whole lot of changes from RC2, but you&#8217;ll have to uninstall previous versions obviously. You can get the installer <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=53289097-73ce-43bf-b6a6-35e00103cb4b&amp;displaylang=en">here</a>. Note that some addins can cause problems during the install (notably Azure tools), but there&#8217;s a <a href="https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=16827&amp;wa=wsignin1.0">hotfix</a> available for it.</span></p>
<h2><span style="font-weight:normal;">Silverlight</span></h2>
<p><span style="font-weight:normal;">Silverlight 3 beta announced : <a href="http://silverlight.net/GetStarted/silverlight3/default.aspx">Getting started with Silverlight 3</a>. <a href="http://timheuer.com/blog/archive/2009/03/18/silverlight-3-whats-new-a-guide.aspx">Tim Heuer</a> has a pretty detailed post regarding the new featuresLooks like there&#8217;s a ton of features in the works, new codecs (H.264, AAC,MPEG-4), improved graphics support (3D transform effects). hardware acceleration, and even standalone silverlight apps. Interestingly the download for the silverlight 3 install is smaller than the current silverlight 2 install.</span></p>
<p><span id="more-62"></span></p>
<h2><span style="font-weight:normal;">.NET RIA Services</span></h2>
<p>An overview can be found <a href="http://download.microsoft.com/download/F/B/8/FB8CA635-296B-487F-965C-8148F08B5319/riaservicesoverviewpreview.pdf">here</a>. Essentially a product/framework that will ease data access for silverlight apps via asp.net. Seems analogous to <a href="http://www.adobe.com/products/livecycle/dataservices/">Adobe&#8217;s LiveCycle Data Services</a></p>
<h2><span style="font-weight:normal;">Azure</span></h2>
<p><span style="font-weight:normal;">You can download the latest <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=b44c10e8-425c-417f-af10-3d2839a5a362&amp;displaylang=en">SDK </a>and <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=59e8fc0c-c399-4ab7-8a93-882d8e74b67a&amp;displaylang=en">Visual Studio tools</a>. On track to release this year, apparently. Some new CTP features have been added, notably <a href="http://blogs.msdn.com/windowsazure/archive/2009/03/18/using-3rd-party-programming-languages-via-fastcgi.aspx">FastCGI</a> , <a href="http://blogs.msdn.com/windowsazure/archive/2009/03/18/hosting-roles-under-net-full-trust.aspx">.NET full trust</a>., and <a href="http://blogs.msdn.com/windowsazure/archive/2009/03/18/geo-location-enables-developers-to-choose-data-centers-and-group-applications-storage.aspx">geolocation </a>(currently limited to two locations in the US). PHP in Azure! This is some needed good news after they suffered a <a href="http://blogs.msdn.com/windowsazure/archive/2009/03/18/the-windows-azure-malfunction-this-weekend.aspx">day long outage</a> over the weekend</span></p>
]]></content:encoded>
			<wfw:commentRss>http://onishimura.com/2009/03/18/mix-09-news/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

