Last active
August 29, 2015 14:03
-
-
Save ynotdraw/ec59efae3465f829dd43 to your computer and use it in GitHub Desktop.
Nice little extension methods when using the Live 5.6 SDK to interact with OneDrive in a Windows Phone project. I needed a way to upload/download an encrypted text file from a user's OneDrive account for data backup for my app, #PassSafe. Feel free to let me know if I missed anything or if I can help you integrate this into your app!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.IO.IsolatedStorage; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Microsoft.Live; | |
// https://stackoverflow.com/questions/23715282/onedrive-upload-download-to-specified-directory | |
namespace OneDriveEx.Helpers | |
{ | |
public static class OneDriveHelper | |
{ | |
/// <summary> | |
/// Creates or gets the directory ID from OneDrive. Provided by colleague Ertay Shashko. | |
/// </summary> | |
/// <param name="client">The current Live Connect session object.</param> | |
/// <param name="folderName">Folder name to create or get.</param> | |
/// <param name="parentFolder">The parent folder to query.</param> | |
/// <returns>Directory ID from OneDrive.</returns> | |
public async static Task<string> CreateOrGetDirectoryAsync(this LiveConnectClient client, string folderName, string parentFolder) | |
{ | |
string folderId = null; | |
// Retrieves all the directories. | |
var queryFolder = parentFolder + "/files?filter=folders,albums"; | |
var opResult = await client.GetAsync(queryFolder); | |
dynamic result = opResult.Result; | |
foreach (dynamic folder in result.data) | |
{ | |
// Checks if current folder has the passed name. | |
if (folder.name.ToLowerInvariant() == folderName.ToLowerInvariant()) | |
{ | |
folderId = folder.id; | |
break; | |
} | |
} | |
if (folderId == null) | |
{ | |
// Directory hasn't been found, so creates it using the PostAsync method. | |
var folderData = new Dictionary<string, object>(); | |
folderData.Add("name", folderName); | |
opResult = await client.PostAsync(parentFolder, folderData); | |
result = opResult.Result; | |
// Retrieves the id of the created folder. | |
folderId = result.id; | |
} | |
return folderId; | |
} | |
/// <summary> | |
/// Uploads a text file to the specified directory on a user's OneDrive account. | |
/// </summary> | |
/// <param name="client">The current Live Connect session object.</param> | |
/// <param name="directory">Directory name to upload the file to. If the directory does not exist, it will be created.</param> | |
/// <param name="fileName">Name of the text file to write.</param> | |
/// <param name="textToWrite">Text to write into the text file.</param> | |
/// <returns /> | |
public async static Task UploadFileAsync(this LiveConnectClient client, string directory, string fileName, string textToWrite) | |
{ | |
using (var isoStoreFile = IsolatedStorageFile.GetUserStoreForApplication()) | |
{ | |
// Creates the text file in Isolated Storage | |
using (var writeFile = new StreamWriter(new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, isoStoreFile))) | |
{ | |
await writeFile.WriteLineAsync(textToWrite); | |
} | |
// Uses the iso file created above to upload it to OneDrive | |
using (var isoStoreFileStream = isoStoreFile.OpenFile(fileName, FileMode.Open, FileAccess.Read)) | |
{ | |
string oneDriveDirectory = await OneDriveHelper.CreateOrGetDirectoryAsync(client, directory, "me/skydrive"); | |
var result = await client.UploadAsync(oneDriveDirectory, fileName, | |
isoStoreFileStream, OverwriteOption.Overwrite); | |
} | |
} | |
} | |
/// <summary> | |
/// Downloads a text file from OneDrive, reads it, and returns the text. | |
/// </summary> | |
/// <param name="client">The current Live Connect session object.</param> | |
/// <param name="directory">Directory name to download the file from.</param> | |
/// <param name="fileName">Name of the text file to read.</param> | |
/// <returns>Text read from the specified file.</returns> | |
public async static Task<string> DownloadFileAsync(this LiveConnectClient client, string directory, string fileName) | |
{ | |
// Get the directory ID we want | |
string oneDriveDirectoryId = await OneDriveHelper.CreateOrGetDirectoryAsync(client, directory, "me/skydrive"); | |
var result = await client.DownloadAsync(oneDriveDirectoryId); | |
// Get the files inside of the directory ID we specified above | |
var operation = await client.GetAsync(oneDriveDirectoryId + "/files"); | |
// Look at the data return list | |
var items = operation.Result["data"] as List<object>; | |
// We will store the OneDrive file ID in the var "id" | |
string id = string.Empty; | |
// Search for the file name we want to read, as specified by the overload "fileName" | |
foreach (object item in items) | |
{ | |
var file = item as IDictionary<string, object>; | |
if (file["name"].ToString() == fileName) | |
{ | |
// If we find the file, assign the OneDrive ID to the id var | |
id = file["id"].ToString(); | |
break; | |
} | |
} | |
// If the file name was not found, throw ex | |
if (string.IsNullOrEmpty(id)) | |
throw new FileNotFoundException("Could not locate the file on the OneDrive account."); | |
// Download the contents of the file | |
var downloadResult = await client.DownloadAsync(string.Format("{0}/content", id)); | |
// Read the file and return the text | |
using (var reader = new StreamReader(downloadResult.Stream, Encoding.UTF8)) | |
{ | |
string text = await reader.ReadToEndAsync(); | |
return text; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Shows usage of OneDriveExtensions | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Navigation; | |
using Microsoft.Phone.Controls; | |
using Microsoft.Phone.Shell; | |
using Microsoft.Live; | |
namespace OneDriveEx.Views | |
{ | |
public partial class OneDriveView : PhoneApplicationPage | |
{ | |
private LiveConnectClient _client; | |
public OneDriveView() | |
{ | |
InitializeComponent(); | |
} | |
private void SignInButton_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e) | |
{ | |
if (e != null && e.Status == LiveConnectSessionStatus.Connected) | |
{ | |
_client = new LiveConnectClient(e.Session); | |
} | |
else | |
{ | |
_client = null; | |
} | |
} | |
private async void ApplicationBarBackup_Click(object sender, EventArgs e) | |
{ | |
try | |
{ | |
await Helpers.OneDriveHelper.UploadFileAsync(_client, "Example", "backup.txt", "Super awesome test!!!"); | |
MessageBox.Show("Data backup completed successfully!", "Hooray!", MessageBoxButton.OK); | |
} | |
catch (Exception ex) | |
{ | |
MessageBox.Show(ex.Message, "Uh-oh!", MessageBoxButton.OK); | |
} | |
} | |
private async void ApplicationBarRestore_Click(object sender, EventArgs e) | |
{ | |
try | |
{ | |
var result = await Helpers.OneDriveHelper.DownloadFileAsync(_client, "Example", "backup.txt"); | |
if (result == "Super awesome test!!!") | |
MessageBox.Show("Data restore completed successfully!", "Hooray!", MessageBoxButton.OK); | |
else | |
MessageBox.Show("That didn't work....", "Oops!", MessageBoxButton.OK); | |
} | |
catch (Exception ex) | |
{ | |
MessageBox.Show(ex.Message, "Uh-oh!", MessageBoxButton.OK); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment