Windows Phone SkyDrive Note Sample (CSWP7SkydriveNote)


Windows Phone 7
Windows Phone 7
Desktop
en-US
5/28/2012

Windows Phone SkyDrive Note Sample (CSWP7SkydriveNote)

Introduction

This sample demonstrates two features:

1. A Windows Phone Notebook
2. Uploading notes to SkyDrive.

CSWP7SkydriveNote project contains two pages:  MainPage.xaml shows the note list in a Listbox control,and MyNote.xaml is used for note editing. When the sample starts up, the following processes will occur:

1. Collect all note file name,
                2. Deserialize the xml contained in the note files into .net objects.
                3. Show note titles and creation datetime in the note list.

When you press a note in the list. The action will navigate page to the MyNote.xaml, so that you can edit and save it. By pressing the ��Connect�� button, you can save the note to SkyDrive.

Building the Sample

1. Visual Studio 2010 with Windows phone SDK 7.1.you can get start by checking this link: http://create.msdn.com/en-us/home/getting_started

2. Download and install the Live SDK, if you haven't already done so.
     By default, the Live SDK is installed in the \Live\v5.0\ folder in \Program Files\Microsoft SDKs\ (on 32-bit computers) or \Program Files (x86)\Microsoft SDKs\ (on 64-bit computers).

3. Get a Live Client Id from here and then open MyNote.xaml, replace ��ClientId�� property with your Id.

Running the Sample

Press Ctrl+F5 to run the sample in Windows Phone Emulator.

 

You can find the uploaded files in the Documents folder of your SkyDrive.

Using the Code

1. Create a new ��Silverlight for Windows Phone�� project.

2. Add Reference to Microsoft.Live.Controls and Microsoft.Live.
    You can also copy these two dlls out from Live SDK installation folder; see also the ��Building the Sample�� part.

3.  Open MainPage.xaml file, replace layout gird xaml with the following code:

XAML
Edit|Remove
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>


    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28" Orientation="Horizontal">
        <TextBlock x:Name="ApplicationTitle" Text="SkyDrive NoteBook" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock x:Name="PageTitle" Text="Note List" Style="{StaticResource PhoneTextNormalStyle}"/>
    </StackPanel>


    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,0,0,0">
        <ListBox x:Name="listBox_NoteList" 
                 ItemsSource="StaticResource noteList"
                 Margin="0,0,0,60"
                 BorderThickness="1" Hold="listBox_NoteList_Hold" Tap="listBox_NoteList_Tap">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Margin="0,5,0,0"
                                Background="DarkRed"  Width="450">
                        <TextBlock Text="{Binding Title}"></TextBlock>
                        <TextBlock Text="{Binding LastEditTime}"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button x:Name="btn_NewNote" Content="New Note" Margin="0,620,0,0" 
                Background="DarkRed" BorderThickness="0"
                Click="btn_NewNote_Click"></Button>
    </Grid>
</Grid>

 

4.Open MainPage.xaml.cs file and replace code with the following:

C#
Edit|Remove
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;


using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.IO;


namespace CSWP7SkydriveNote
{
    public partial class MainPage : PhoneApplicationPage
    {
        public static List<Note> CreateTestList()
        {
            List<Note> list = new List<Note>();
            Note note = new Note();


            //Get files from isolated store.
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            XmlSerializer serializer = new XmlSerializer(typeof(Note));
            var filesName = store.GetFileNames();
            if (filesName.Length > 0)
            {
                foreach (string fileName in filesName)
                {
                    if (fileName == "__ApplicationSettings") continue;
                    using (var file = store.OpenFile(fileName, FileMode.Open))
                    {
                        note = (Note)serializer.Deserialize(file);
                        list.Add(note);
                    }
                }
            }


            store.Dispose();
            return list;
        }


        public MainPage()
        {
            InitializeComponent();
        }


        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            listBox_NoteList.ItemsSource = CreateTestList();
        }


        private void listBox_NoteList_Hold(object sender, GestureEventArgs e)
        {
            //Get item data.
            FrameworkElement element = (FrameworkElement)e.OriginalSource;
            Note item = (Note)element.DataContext;
            //Get element data.
            ListBox listBox = sender as ListBox;
            var selectedItem = listBox.SelectedItem;


            MessageBox.Show(item.Title);
        }


        private void listBox_NoteList_Tap(object sender, GestureEventArgs e)
        {
            //Get item data
            FrameworkElement element = (FrameworkElement)e.OriginalSource;
            Note item = (Note)element.DataContext;
            if (item == null)
            {
                return;
            }


            string urlWithData = string.Format("/MyNote.xaml?NoteId={0}", item.NoteID);
            NavigationService.Navigate(new Uri(urlWithData, UriKind.Relative));
        }


        private void btn_NewNote_Click(object sender, RoutedEventArgs e)
        {
            //Navigate to MyNote.xaml page
            NavigationService.Navigate(new Uri("/MyNote.xaml", UriKind.Relative));
        }
    }
}

 

5. Create a new ��Windows Phone Portrait Page�� page, name it ��MyNote.xaml��, and fill the file with the following code. Next, replace ��your client id here�� with your own Client Id.

XAML
Edit|Remove
<phone:PhoneApplicationPage 
    x:Class="CSWP7SkydriveNote.MyNote"
    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="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True"
    xmlns:live="clr-namespace:Microsoft.Live.Controls;assembly=Microsoft.Live.Controls"
    >


    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28" Orientation="Horizontal">
            <TextBlock x:Name="ApplicationTitle" Text="MY NoteBook" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTile" Text="Editing" Style="{StaticResource PhoneTextNormalStyle}"/>
        </StackPanel>


        <Button x:Name="btn_Save" Margin="0,40,240,670" Height="70" Content="Save" 
                Background="DarkRed" BorderThickness="0"
                Click="btn_Save_Click"></Button>
        <Button x:Name="btn_Delete" Margin="240,40,0,670" Height="70" Content="Delete" 
                Background="DarkRed" BorderThickness="0"
                Click="btn_Delete_Click"></Button>


        <TextBlock Text="Title:" Margin="12,120,420,610"></TextBlock>
        <TextBox x:Name="txtBox_noteTitle" Margin="50,105,0,590" AcceptsReturn="False"></TextBox>
        <TextBox x:Name="txtBox_Content" Margin="0,160,0,50" AcceptsReturn="True"></TextBox>
        <live:SignInButton Name="btn_Upload" ClientId="your client id here" Margin="0,700,0,0"
                           Scopes="wl.signin wl.basic wl.skydrive_update" Branding="Skydrive"
                           TextType="Connect" SessionChanged="btn_Upload_SessionChanged"
                           Background="DarkRed" BorderThickness="0"/>
    </Grid>
</phone:PhoneApplicationPage>

 
your client id here

6. Open MyNote.xaml.cs file, replace code with the following:

C#
Edit|Remove
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;


using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.IO;
using Microsoft.Live;


namespace CSWP7SkydriveNote
{
    public partial class MyNote : PhoneApplicationPage
    {
        Note note;


        //The isDeleteNote field is used to identify if the navigation action
        //is caused by delete, if yes, then, the note will not be saved. 
        bool isDeleteNote = false;
        string fileName;
        string noteId;


        private LiveConnectClient client;
        private LiveConnectSession session;


        public MyNote()
        {
            InitializeComponent();
            isDeleteNote = false;
        }


        /// <summary>
        /// Called when this page becomes the active page. 
        /// </summary>
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            ShowNote();
            isDeleteNote = false;
        }


        /// <summary>
        /// Called just before navigating away from this page. 
        /// </summary>
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }


        /// <summary>
        /// Called when page is navigating away. 
        /// </summary>
        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (isDeleteNote) return;
            SaveNote();
        }


        private void btn_Save_Click(object sender, RoutedEventArgs e)
        {
            if (isDeleteNote) return;
            SaveNote();
        }


        private void CreateNewNote()
        {
            note = new Note();
            note.NoteID = Guid.NewGuid();
            note.Title = txtBox_noteTitle.Text;
            note.Content = txtBox_Content.Text;
            note.CreatedDate = DateTime.Now;
            note.LastEditTime = DateTime.Now;


            noteId = note.NoteID.ToString();


            //serialize to xml and store into file
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            using (var file = store.CreateFile(note.NoteID + ".txt"))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Note));
                serializer.Serialize(file, note);
            }
            store.Dispose();
        }


        private void ShowNote()
        {
            //Get the page id
            if (this.NavigationContext.QueryString.Count < 1)
            {
                CreateNewNote();
                return;
            }
            noteId = this.NavigationContext.QueryString["NoteId"].ToString();
            fileName = noteId + ".txt";


            //Deserialized the note base on the id. 
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            XmlSerializer serializer = new XmlSerializer(typeof(Note));
            using (var file = store.OpenFile(fileName, FileMode.Open))
            {
                note = (Note)serializer.Deserialize(file);
            }


            txtBox_noteTitle.Text = note.Title;
            txtBox_Content.Text = note.Content;


            store.Dispose();
        }
        
        private void SaveNote()
        {
            fileName = noteId + ".txt";
            note.NoteID = new Guid(noteId);
            note.Title = txtBox_noteTitle.Text;
            note.Content = txtBox_Content.Text;
            note.CreatedDate = DateTime.Now;
            note.LastEditTime = DateTime.Now;


            //serialize to xml and store into file
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            using (var file = store.CreateFile(note.NoteID + ".txt"))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Note));
                serializer.Serialize(file, note);
            }
            store.Dispose();
        }


        private void DeleteNote()
        {
            string idString = noteId;
            fileName = idString + ".txt";
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(fileName))
                {
                    store.DeleteFile(fileName);
                }
            }


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


        private void btn_Delete_Click(object sender, RoutedEventArgs e)
        {
            DeleteNote();
        }


        private void btn_Upload_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
        {
            if (isDeleteNote) return;
            SaveNote();


            if (e.Status == LiveConnectSessionStatus.Connected)
            {
                session = e.Session;
                client = new LiveConnectClient(session);
                Dispatcher.BeginInvoke(() => {
                    MessageBox.Show("Connected");
                });


                client = new LiveConnectClient(session);


                //Get files from isolated store
                IsolatedStorageFile store = 
                    IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream =
                    store.OpenFile(fileName, FileMode.Open);


                //Upload files to document folder by friendly name.
                client.UploadCompleted += (obj, arg) =>
                {
                    if (arg.Error == null)
                    {
                        IDictionary<string, object> fileInfo = arg.Result;
                        string fileId = fileInfo["id"].ToString();
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(fileId);
                        });
                    }
                    else
                    {
                        string errorMessage = "Error calling API: " + arg.Error.Message;
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(errorMessage);
                        });
                    }
                };


                client.UploadAsync("me/skydrive/my_documents", fileName, fileStream);
            }


            if (e.Error != null)
            {
                Dispatcher.BeginInvoke(() => {
                    MessageBox.Show(e.Error.Message);
                });
            }
        }
    }


    public class Note
    {
        public Guid NoteID { get; set; }
        public string Title { get; set; }
        public DateTime CreatedDate { get; set; }
        public string Content { get; set; }
        public DateTime LastEditTime { get; set; }
    }
}

 

More Information

For more information about SkyDrive development, see:
http://msdn.microsoft.com/en-us/live/