使用 Live Connect SDK 编写 Windows 8.1 应用商店应用的开发者指南






4.73/5 (9投票s)
使用 Live Connect SDK 访问 SkyDrive 文件夹和文件的简单 C# 函数
引言
Windows 应用商店现在拥有超过 50,000 个应用,而且还在不断增长。与此同时,这些应用的数据云存储已成为允许多个设备之间数据漫游的基本要求。在本文中,我们将讨论如何从 Windows 应用商店应用访问 SkyDrive 云存储。
我将带您了解 5 个基本操作
- 创建应用商店应用
- 通过应用登录 SkyDrive
- 在 SkyDrive 上创建文件夹
- 上传文件到 SkyDrive
- 从 SkyDrive 下载文件
创建 SkyDrive Windows 应用商店应用
- 从 此处获取 Windows 应用商店开发者帐户
- 在 Windows 8.1 PC 上安装 Visual Studio 2013
- 从 此处安装 Live Connect SDK
- 使用 Visual Studio 2013 创建新的 Windows 应用商店 C# 项目
- 添加 Live Connect API 的引用
- 将应用与应用商店关联
- 在 MainPage.xaml.cs 中包含 Live Connect SDK
//live connect SDK
using Microsoft.Live;
现在,您的应用已准备好使用 SkyDrive Live Connect SDK。
- 在 MainPage.xaml 中添加按钮
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBox Name="infoTextBlock" HorizontalAlignment="Left" Height="29"
Margin="10,10,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="1346"/>
<Button Content="Sign In" HorizontalAlignment="Left" Margin="7,58,0,0"
VerticalAlignment="Top" Width="138" Height="50" Click="Button_SignIn_Click"/>
<Button Content="Create Folder" HorizontalAlignment="Left" Margin="7,126,0,0"
VerticalAlignment="Top" Height="50" Width="138" Click="Button_CreateFolder_Click"/>
<Button Content="Upload File" HorizontalAlignment="Left" Margin="7,197,0,0"
VerticalAlignment="Top" Height="50" Width="138" Click="Button_UploadFile_Click"/>
<Button Content="Upload Cancel" HorizontalAlignment="Left" Margin="170,197,0,0"
VerticalAlignment="Top" Height="50" Width="165" Click="Button_UploadFileCancel_Click"/>
<Button Content="Download File" HorizontalAlignment="Left" Margin="7,264,0,0"
VerticalAlignment="Top" Height="50" Width="138" Click="Button_DownloadFile_Click"/>
<Button Content="Download Cancel" HorizontalAlignment="Left" Margin="170,264,0,0"
VerticalAlignment="Top" Height="50" Width="165" Click="Button_DownloadFileCancel_Click"/>
</Grid>
使用演示应用登录 SkyDrive
要使用演示应用程序登录,请单击“登录”按钮。
在 Windows 8.0/8.1 中,有一个称为“已连接帐户”的概念,如果用户已使用已连接帐户登录,则此应用将使用当前的 Microsoft 帐户登录 SkyDrive。当应用首次运行时,用户将看到一个同意屏幕,以授予对 SkyDrive 资源的访问权限。
在此示例中,我们有以下访问请求:“wl.signin
”、“wl.basic
”、“wl.skydrive
”、“wl.skydrive_update
”。
//LiveConnectClient object will be used for all future transactions
private LiveConnectClient liveClient;
此应用中的第一个操作应该是单击“登录”按钮以创建 LiveConnectClient 对象,该对象在 Button_SignIn_Click
方法内部创建,将用于其他文件/文件夹访问方法。
private async void Button_SignIn_Click(object sender, RoutedEventArgs e)
{
try
{
LiveAuthClient auth = new LiveAuthClient();
loginResult = await auth.LoginAsync(new string[]
{ "wl.signin", "wl.basic", "wl.skydrive", "wl.skydrive_update"});
liveClient = new LiveConnectClient(loginResult.Session);
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
this.infoTextBlock.Text = "Signed in.";
}
}
catch (LiveAuthException exception)
{
this.infoTextBlock.Text = "Error signing in: "
+ exception.Message;
}
}
如果您注意到,我们没有任何用户界面来接收用户名和密码,这要归功于 Windows 已连接帐户 :) 来管理集成的身份验证 UI。
使用 SkyDrive 文件夹
通常,我们会编写基于 SkyDrive 的 Windows 应用商店应用来将用户文件/数据存储在云中,因此我们可以将用户数据保存在云中,并可以从任何设备访问。以下是创建 SkyDrive 文件夹的代码片段。LiveConnectClient::PostAsync
方法用于创建新文件夹。
private async void Button_CreateFolder_Click(object sender, RoutedEventArgs e)
{
try
{
var folderData = new Dictionary<string, object>();
folderData.Add("name", "testfolderLevel1");
LiveOperationResult operationResult =
await liveClient.PostAsync("me/skydrive", folderData);
dynamic result = operationResult.Result;
this.infoTextBlock.Text = string.Join(" ",
"Created folder: ", result.name, "ID: ", result.id);
}
catch (LiveConnectException exception)
{
this.infoTextBlock.Text = "Error creating folder: " + exception.Message;
}
}
几行代码即可创建文件夹。非常简单!感谢 Live Connect SDK。:)
当您单击“登录”按钮然后单击“创建文件夹”时,您将看到图中标记的文件夹 ID。
如上所示,创建文件夹时,该文件夹会被赋予一个唯一的 ID,例如“folder.8b922582dc2j7b71.8B922451DC2F7B71!811”。由于文件和文件夹是使用 ID 而不是完整路径访问的,因此我编写了一个帮助函数来使用完整路径创建文件夹和子文件夹。
Create_Folder()
方法算法
- 使用“/”分隔符将路径拆分为一个数组
- 使用
getAsync
方法检查文件夹是否存在 - 在
getAsync
方法中使用“/files”获取文件夹 ID - 重复步骤 2 和 3,直到处理完数组中的所有文件夹名称。
- 处理完完整路径后,使用
postAsync
方法创建文件夹
//code
private async Task<string> Create_Folder(string sNewFoldername, string sRoot)
{
try
{
string sCurrentRootID = "me/skydrive";
bool bFolderFound = true;
if (sRoot != "")
{
string[] Folderhierarchy = sRoot.Split('/');
LiveOperationResult result;
foreach (string sFolder in Folderhierarchy)
{
bFolderFound = false;
result = await liveClient.GetAsync(sCurrentRootID +"/files");
dynamic files = result.Result;
List<object> data = (List<object>)files.data;
bFolderFound = false;
if (data == null)
break;
foreach (dynamic item in data)
{
if (item.name == sFolder)
{
sCurrentRootID = (string)item.id;
bFolderFound = true;
break;
}
}
if (bFolderFound != true )
{
this.infoTextBlock.Text = "Invalid path";
break;
}
}
}
if(bFolderFound == true)
{
var folderData = new Dictionary<string, object>();
folderData.Add("name", sNewFoldername);
LiveOperationResult operationResult = await liveClient.PostAsync(sCurrentRootID, folderData);
dynamic DynResult = operationResult.Result;
this.infoTextBlock.Text = string.Join
("Created folder: ", DynResult.name, "ID: ", DynResult.id);
return (string)DynResult.id;
}
return null;
}
catch (LiveConnectException exception)
{
this.infoTextBlock.Text = "Error creating folder: " + exception.Message;
return null;
}
}
您可以按如下方式调用上述函数
Create_Folder("TestFolderLevel1", "");
Create_Folder("TestFolderLevel2", "TestFolderLevel1");
Create_Folder("TestFolderLevel3", "TestFolderLevel1/TestFolderLevel2");
我希望上述帮助函数能让文件夹访问像本地驱动器文件夹访问一样轻松。
上传文件到 SkyDrive
现在演示应用程序已登录,并且我们能够创建文件夹,接下来的任务是将文件上传到新创建的文件夹中。我提供了一个将文件上传到 SkyDrive 根目录的代码片段,但您可以编写自己的函数上传到特定文件夹。
private async void Button_UploadFile_Click(object sender, RoutedEventArgs e)
{
try
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add("*");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
this.ctsUpload = new System.Threading.CancellationTokenSource();
await liveClient.BackgroundUploadAsync("me/skydrive",
"TestUploadedPicture.jpg", file,
OverwriteOption.Overwrite, this.ctsUpload.Token, null);
this.infoTextBlock.Text = "Upload completed.";
}
}
catch (System.Threading.Tasks.TaskCanceledException)
{
this.infoTextBlock.Text = "Upload cancelled.";
}
catch (LiveConnectException exception)
{
this.infoTextBlock.Text = "Error uploading file: " + exception.Message;
}
}
上述函数可能包含很多行,但大部分代码是关于选择要上传的文件。上传是通过 LiveConnectClient 对象中的 BackgroundUploadAsync
方法启动的。
private void Button_UploadFileCancel_Click(object sender, RoutedEventArgs e)
{
if (this.ctsUpload != null)
{
this.ctsUpload.Cancel();
}
}
由于大文件上传可能需要更长时间才能完成,因此这是异步完成的,并且可以使用取消上传按钮取消。
从 SkyDrive 下载文件
下载文件只需要创建一个 LiveConnectClient
对象并调用 BackgroundDownloadAsync
,使用 Live Connect SDK 就是这么简单。
private System.Threading.CancellationTokenSource ctsDownload;
private async void Button_DownloadFile_Click(object sender, RoutedEventArgs e)
{
try
{
var picker = new Windows.Storage.Pickers.FileSavePicker();
picker.SuggestedFileName = "TestDownloadedPicutre.jpg";
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads;
picker.FileTypeChoices.Add("Picture", new List<string>(new string[] { ".jpg" }));
StorageFile file = await picker.PickSaveFileAsync();
if (file != null)
{
this.ctsDownload = new System.Threading.CancellationTokenSource();
await liveClient.BackgroundDownloadAsync("<file id to download>", file,
this.ctsDownload.Token, null);
this.infoTextBlock.Text = "Download completed.";
}
}
catch (System.Threading.Tasks.TaskCanceledException)
{
this.infoTextBlock.Text = "Download cancelled.";
}
catch (LiveConnectException exception)
{
this.infoTextBlock.Text = "Error getting file contents: " + exception.Message;
}
}
与上传一样,根据网络速度,下载过程可能需要一些时间,并且应用需要响应用户的操作,因此我们调用 BackgroundDownloadAsync
方法并提供如下所示的下载取消处理程序。
private void Button_DownloadFileCancel_Click(object sender, RoutedEventArgs e)
{
if (this.ctsDownload != null)
{
this.ctsDownload.Cancel();
}
}
注意:要完全下载文件内容,请在末尾使用“/content”。
BackgroundDownloadAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129/content",
file,ctsDownload.Token, null);
如果不使用“/content”,则图片文件可能只会下载缩略图。
摘要
我在本文中附带了 MainPage.xaml.cs 和 MainPage.xaml。您可以创建自己的项目,然后替换上述文件,以获得一个功能齐全的 Windows 8.1 应用商店应用示例。使用 Live Connect SDK 非常简单,但还有其他访问 SkyDrive 文件的方法,如 此处所述。感谢您的时间和宝贵的反馈。
历史
- 2014 年 1 月 19 日:初次发布