加载中

Introduction

Microsoft provides a Windows Live Connect SDK which allows you to easily connect, upload and download files from and to OneDrive (previously called Skydrive).

Background

Before starting, we have to download the latest Live SDK for Windows, Windows Phone 8, and .NET from http://msdn.microsoft.com/en-us/live/ff621310.aspx.

Start Creating Your Own Windows Phone 8 App

After downloading the version 5.5, we are going to create a new Windows Phone 8 application called « SkyDrive Example » in which the user can register using his Microsoft Live Account in order to send the file to Skydrive.

介绍

Microsoft 提供了一个 Windows Live Connect SDK ,允许你轻松连接 OneDrive(之前叫作 Skydrive) ,并从其下载文件或上传文件到其上。

背景

在开始之前,我们必须下载用于 Windows, Windows Phone 8, 和 .NET 的最新版 Live SDK: http://msdn.microsoft.com/en-us/live/ff621310.aspx

开始创建你自己的 Windows Phone 8 App

下载目前最新版 5.5 之后,我们将创建一个新的 Windows Phone 8 应用,名为SkyDrive Example”,在里面,用户可以用其 Microsoft Live 帐号注册,并向 Skydrive 发送文件。

Left click on «References under your project in the Solution Explorer Windows and add these essential references to your project:

Change the title of our application to be more significant and add «SignInButton » to Toolbox to make the authentification process.

So, you will find many components, so Write « SignInButton » in the filter zone to find this functionality as shown below:

Well done. Now, we want to create a Client Id in order to store the user’s authorization information to not sign in every time the app opens.

Go to https://account.live.com/developers/applications/create and we will enter the name of our application and accept the term of uses.

After doing that, you will find your own client ID as shown in the picture below:

在Solution Explorer窗口中鼠标左键点击你项目下面的References,添加这些必要的引用到你的项目中:

修改我们应用的标题使其更显著,添加 SignInButton 到 Toolbox 使认证可被处理。

你会发现许多组件,所以可在过滤区写上 SignInButton 来找到它,功能如下所示:

干得好!现在,我们要创建一个客户ID用来存储用户的授权信息,免得每次打开应用都要签入。

访问 https://account.live.com/developers/applications/create ,输入我们的应用名称,接受使用条款。

做完之后,你会发现自己的客户端ID,如下图所示:

Now, you need to add this code into the MainPage.xaml in order the add the signInButton and don’t forget to add your own client ID in Client Id Zone:

<StackPanel x:Name="TitlePanel" 
Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="SkyDrive Example" 
            Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
            <TextBlock Text="Upload a File" Margin="9,-7,0,0" 
            Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <Controls:SignInButton Name="loginButton" 
            Content="SignInButton" HorizontalAlignment="Left" 
            Margin="110,75,0,0" VerticalAlignment="Top" 
            Scopes="wl.signin wl.offline_access wl.skydrive_update" 
            SessionChanged="loginButton_SessionChanged" Visibility="Visible"/>
            <Button Content="Upload" HorizontalAlignment="Left" 
            Margin="110,256,0,0" VerticalAlignment="Top" 
            Width="211" Click="Upload_Click"/>

        </Grid>

Now, it is time for managing our MainPage.cs. So that we don’t want to register every time the application launches, we are going to add the code below starting with adding the essential libraries:

using Microsoft.Live;
using Microsoft.Live.Controls;

Don’t forget to declare the LiveConnectClient.

private LiveConnectClient client;

Add the following code for the loginButton_SessionChanged helper method.

private void loginButton_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
        {
           
        if (e != null && e.Status == LiveConnectSessionStatus.Connected)
        {
        //the session status is connected so we need to set this session status to client
        this.client = new LiveConnectClient(e.Session);        
        }
        else
        {    
        this.client = null;
        }

        }

If the user clicks on download, he will send a file called ‘sample.txt’ that contains ‘hello world’ to his Onedrive Account.

private async void Upload_Click(object sender, RoutedEventArgs e)
        {
            if (client != null)
            {
                try
                {
                    string fileName = "sample.txt";
                    IsolatedStorageFile myIsolatedStorage = 
                    IsolatedStorageFile.GetUserStoreForApplication();//deletes the file if it already exists
                    if (myIsolatedStorage.FileExists(fileName))
                    {
                        myIsolatedStorage.DeleteFile(fileName);
                    }//now we use a StreamWriter to write inputBox.Text to the file and save it to IsolatedStorage
                    using (StreamWriter writeFile = new StreamWriter
                    (new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
                    {
                        writeFile.WriteLine("Hello world");
                        writeFile.Close();
                    }
                    IsolatedStorageFileStream isfs = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                    var res = await client.UploadAsync("me/skydrive", fileName, isfs, OverwriteOption.Overwrite);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Please sign in with your Microsoft Account.");
            }
        }

Conclusion

Well done! We have seen together how to implement the OneDrive API in your Windows Phone 8 application and how to send a simple file to the OneDrive.

现在,你需要把这些代码加入 MainPage.xaml 文件中,以加入 signInButton,不要忘记把你的 client ID 加入到 Client Id 区中:

<StackPanel x:Name="TitlePanel" 
Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="SkyDrive Example" 
            Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
            <TextBlock Text="Upload a File" Margin="9,-7,0,0" 
            Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <Controls:SignInButton Name="loginButton" 
            Content="SignInButton" HorizontalAlignment="Left" 
            Margin="110,75,0,0" VerticalAlignment="Top" 
            Scopes="wl.signin wl.offline_access wl.skydrive_update" 
            SessionChanged="loginButton_SessionChanged" Visibility="Visible"/>
            <Button Content="Upload" HorizontalAlignment="Left" 
            Margin="110,256,0,0" VerticalAlignment="Top" 
            Width="211" Click="Upload_Click"/>

        </Grid>

现在,该处理 MainPage.cs 了。我们不想每次启动应用时注册,所以我们把下面的代码加入进去,开始是引用一些必要的库:

using Microsoft.Live;
using Microsoft.Live.Controls;

别忘记声明 LiveConnectClient.

private LiveConnectClient client;

为 loginButton_SessionChanged 助手方法添加如下代码:

private void loginButton_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
        {
           
        if (e != null && e.Status == LiveConnectSessionStatus.Connected)
        {
        //the session status is connected so we need to set this session status to client
        this.client = new LiveConnectClient(e.Session);        
        }
        else
        {    
        this.client = null;
        }

        }

如果点击了 download,他会发送一个内容是‘hello world’、名为‘sample.txt’的文件到他的 Onedrive 帐号上。

private async void Upload_Click(object sender, RoutedEventArgs e)
        {
            if (client != null)
            {
                try
                {
                    string fileName = "sample.txt";
                    IsolatedStorageFile myIsolatedStorage = 
                    IsolatedStorageFile.GetUserStoreForApplication();//deletes the file if it already exists
                    if (myIsolatedStorage.FileExists(fileName))
                    {
                        myIsolatedStorage.DeleteFile(fileName);
                    }//now we use a StreamWriter to write inputBox.Text to the file and save it to IsolatedStorage
                    using (StreamWriter writeFile = new StreamWriter
                    (new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
                    {
                        writeFile.WriteLine("Hello world");
                        writeFile.Close();
                    }
                    IsolatedStorageFileStream isfs = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                    var res = await client.UploadAsync("me/skydrive", fileName, isfs, OverwriteOption.Overwrite);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Please sign in with your Microsoft Account.");
            }
        }

结论

干得好!我们一起看到了如何在你的Windows Phone 8应用程序中实现OneDrive API和如何发送一个简单的文件到OneDrive上。

返回顶部
顶部