using System;
using System.Collections.Generic;
using System.Windows.Input;
using Microsoft.Phone.Controls;
using Microsoft.Live;
using Microsoft.Live.Controls;
namespace MiniSkyDriveExplorer
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private LiveConnectClient client = null;
private void btnSignIn_SessionChanged(object sender,
LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
DirItem.LiveSession = e.Session;
client = new LiveConnectClient(e.Session);
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(
client_GetCompleted);
//呼叫me/skydrive,取得根目錄folderId
client.GetAsync("me/skydrive",
new MyUserState(ApiMethod.SkyDriveProp));
}
}
private const string goUpperSymbol = "\t";
//所有的REST API呼叫動作完成後,都會觸發此段解析回傳結果
//為降低範例程式複雜度,以下並未包含防呆容錯的邏輯,實際開發時應補上
void client_GetCompleted(object
sender, LiveOperationCompletedEventArgs e)
{
MyUserState state = e.UserState as MyUserState;
if (state == null) return;
switch (state.Method)
{
//取得SkyDrive主資料夾的folderId
case ApiMethod.SkyDriveProp:
//取出id,列出根目錄下的項目
ListFiles(e.Result["id"].ToString());
break;
//取得目錄清單
case ApiMethod.SkyDriveDir:
//由data取得陣列
List<object> items =
e.Result["data"] as List<object>;
if (items != null)
{
DirList.Items.Clear();
DirList.DisplayMemberPath = "DisplayName";
//加入回上層的邏輯
if (folderIdStack.Count > 1)
{
DirItem di = new DirItem(goUpperSymbol, "[..]");
DirList.Items.Add(di);
}
foreach (Dictionary<string, object> item in items)
{
DirItem di = new DirItem(
item["id"].ToString(),
item["name"].ToString()
);
//資料夾時額外取得子項目數
if (di.IsFolder)
di.Count = int.Parse(item["count"].ToString());
else //檔案則取得下載網址
di.SrcUrl = item["source"].ToString();
//加入清單
DirList.Items.Add(di);
}
}
break;
}
}
//用以保存上層目錄的folderId
private Stack<string> folderIdStack = new Stack<string>();
private void ListFiles(string folderId)
{
if (client == null) return;
if (folderId == goUpperSymbol)
{
folderIdStack.Pop();
folderId = folderIdStack.Peek();
}
else folderIdStack.Push(folderId);
client.GetAsync(folderId + "/files",
new MyUserState(ApiMethod.SkyDriveDir));
}
private void DirList_MouseLeftButtonUp(object sender,
MouseButtonEventArgs e)
{
DirItem di = DirList.SelectedItem as DirItem;
//資料夾的話,繼續展開
if (di.IsFolder || di.Id == goUpperSymbol) ListFiles(di.Id);
//否則試著下載回來檢視
else
{
DirItem.Current = di; //將此DirItem設為Current
NavigationService.Navigate(
new Uri("/Viewer.xaml", UriKind.Relative));
}
}
}
}