private async Task UploadFileToSkydrive(StorageFile file, string eventBuddyFolderId, LiveConnectClient client) { using (var stream = await file.OpenStreamForReadAsync()) { var progressHandler = InitializeProgressBar(); var hasErrors = false; do { try { hasErrors = false; this.retrySelected = false; LiveOperationResult result = await client.BackgroundUploadAsync(eventBuddyFolderId, file.Name, stream.AsInputStream(), OverwriteOption.Overwrite, cancellationToken.Token, progressHandler); this.FileNameTextBlock.Text = file.Name; await UpdateSession(client, result); } catch (LiveConnectException) { hasErrors = true; } if (hasErrors) { var errorTitle = "Upload file error"; await ShowMessage(errorTitle, "Exception occured while trying to upload the " + file.Name + " file to Skydrive."); } uploadProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } while(this.retrySelected); } }
// Example //private async Task<LiveDownloadOperationResult> DownloadExample( // String skyDriveItemId, // IStorageFile downloadFile) //{ // var client = new LiveConnectClient(_session); // var path = String.Format("{0}/content", skyDriveItemId); // var progressHandler = // new Progress<LiveOperationProgress>(ShowProgress); // var result = await client.BackgroundDownloadAsync( // path, // downloadFile, // _cancellationTokenSource.Token, // progressHandler); // return result; // // result.File // // result.GetRandomAccessStreamAsync() // // result.Stream //} //private void ShowProgress(LiveOperationProgress liveOperationProgress) //{ // // Display progress UI, making sure to check for thread access // UpdateUserInterfaceProgress( // liveOperationProgress.BytesTransferred, // liveOperationProgress.TotalBytes, // liveOperationProgress.ProgressPercentage); //} //private void CancelDownload(CancellationTokenSource tokenSource) //{ // // Respond to UI request to cancel the download // tokenSource.Cancel(); //} public async Task <dynamic> StartBackgroundUploadAsync(String skyDriveItemId, String uploadFileName, StorageFile fileToUpload, CancellationToken cancellationToken, Progress <LiveOperationProgress> progressHandler) { // requires wl.skydrive_update scope var client = new LiveConnectClient(_session); var result = await client.BackgroundUploadAsync(skyDriveItemId, uploadFileName, fileToUpload, OverwriteOption.Rename, cancellationToken, progressHandler); return(result.Result); }
private async void UploadToSkydrive(object sender, RoutedEventArgs e) { try { var file = await storageFolder.GetFileAsync(fileInPC); var upfile = await storageFolder.GetFileAsync(fileToUpload); //StorageFile sampleFile = await storageFolder.GetFileAsync(fileInPC); string textFile = await Windows.Storage.FileIO.ReadTextAsync(file); string textUpFile = await Windows.Storage.FileIO.ReadTextAsync(upfile); //txtTemp.Text = " PC "+textFile; //txtSky.Text = "Sky "+textUpFile; try { GlobalV.tempLevel = Convert.ToInt32(textFile); GlobalV.Level = Convert.ToInt32(textUpFile); } catch (OverflowException) { } catch (FormatException) { } if (GlobalV.tempLevel > GlobalV.Level) { GlobalV.Level = GlobalV.tempLevel; StorageFile newFile = await storageFolder.CreateFileAsync(fileToUpload, CreationCollisionOption.ReplaceExisting); await Windows.Storage.FileIO.WriteTextAsync(newFile, GlobalV.Level.ToString()); } else { } string textFile1 = await Windows.Storage.FileIO.ReadTextAsync(file); string textUpFile1 = await Windows.Storage.FileIO.ReadTextAsync(upfile); //txtTemp.Text = " PC " + textFile1; //txtSky.Text = "Sky " + textUpFile1; await client.BackgroundUploadAsync("me/skydrive", fileToUpload, upfile, OverwriteOption.Overwrite); MessageDialog dlg = new MessageDialog("File uploaded success fully"); dlg.ShowAsync(); } catch (Exception ex) { Debug.WriteLine(ex.Message); MessageDialog dlg = new MessageDialog("File did not upload success fully"); dlg.ShowAsync(); } }
private async Task <int> UploadFileToOneDrive() { try { // create OneDrive auth client var authClient = new LiveAuthClient(); // ask for both read and write access to the OneDrive LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.skydrive", "wl.skydrive_update" }); // if login successful if (result.Status == LiveConnectSessionStatus.Connected) { // create a OneDrive client liveClient = new LiveConnectClient(result.Session); // create a local file StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename", CreationCollisionOption.ReplaceExisting); // copy some txt to local file MemoryStream ms = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(string)); serializer.WriteObject(ms, "Hello OneDrive World!!"); using (Stream fileStream = await file.OpenStreamForWriteAsync()) { ms.Seek(0, SeekOrigin.Begin); await ms.CopyToAsync(fileStream); await fileStream.FlushAsync(); } // create a folder string folderID = await GetFolderID("folderone"); if (string.IsNullOrEmpty(folderID)) { // return error return(0); } // upload local file to OneDrive await liveClient.BackgroundUploadAsync(folderID, file.Name, file, OverwriteOption.Overwrite); return(1); } } catch { } // return error return(0); }
public async Task <string> UploadFileToTrackTimerFolder(StorageFile localFile, bool uploadOverWifi, bool overwrite = false) { LiveConnectSessionStatus connectStatus; if (client != null || (connectStatus = await Connect()) == LiveConnectSessionStatus.Connected) { client.BackgroundTransferPreferences = uploadOverWifi ? BackgroundTransferPreferences.AllowBattery : BackgroundTransferPreferences.AllowCellularAndBattery; Exception fileUploadException = null; try { // Copy file to transfers folder var sharedFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("shared"); var transfersFolder = await sharedFolder.GetFolderAsync("transfers"); var fileToUpload = await localFile.CopyAsync(transfersFolder, localFile.Name, NameCollisionOption.ReplaceExisting); // Upload to SkyDrive await FindTrackTimerFolder(client); var localFileUri = new Uri(string.Format("/shared/transfers/{0}", fileToUpload.Name), UriKind.RelativeOrAbsolute); var result = await client.BackgroundUploadAsync(trackTimerFolderId, localFileUri, overwrite?OverwriteOption.Overwrite : OverwriteOption.Rename); // Delete local file once upload is complete if (!uploadOverWifi) { await fileToUpload.DeleteAsync(StorageDeleteOption.PermanentDelete); } // Return the OneDrive Id of the uploaded file return(result.Result != null && result.Result.ContainsKey("id") ? result.Result["id"].ToString() : string.Empty); } catch (Exception ex) { fileUploadException = ex; } if (fileUploadException != null) { var extraData = new LimitedCrashExtraDataList(); extraData.Add("Message", string.Format("Failed to upload file {0}", localFile.Name)); extraData.Add("UploadOverWifi", uploadOverWifi.ToString()); await BugSenseHandler.Instance.LogExceptionAsync(fileUploadException, extraData); } } return(string.Empty); }
internal async void RunTaskAsync(LiveConnectClient client, Action <bool> callback) { bool succeeded = true; using (var stream = await File.OpenStreamForReadAsync()) { try { const int backgroundTheshold = 1024 * 1024 * 100; if (stream.Length >= backgroundTheshold) { const string rootPath = "/shell/transfers"; var tempFilePath = string.Format("{0}/{1}/{2}", rootPath, FolderId, FileName); using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!storage.DirectoryExists(rootPath)) { storage.CreateDirectory(rootPath); } if (storage.FileExists(tempFilePath)) { storage.DeleteFile(tempFilePath); } using (var file = storage.CreateFile(tempFilePath)) { var position = stream.Position; await stream.CopyToAsync(file); stream.Position = position; } } client.BackgroundTransferPreferences = BackgroundTransferPreferences.None; await client.BackgroundUploadAsync(FolderId, new Uri(tempFilePath, UriKind.Relative), OverwriteOption.Overwrite); } else { await client.UploadAsync(FolderId, FileName, stream, OverwriteOption.Overwrite); } } catch (Exception) { succeeded = false; } } if (callback != null) { callback(succeeded); } }
private async Task <Dictionary <string, string> > UploadFile(StorageFile file) { Upload Upload = new Upload(file); try { if (file != null) { Dictionary <string, string> fileInfoDict = new Dictionary <string, string>(); Upload.ProgressHandler = new Progress <LiveOperationProgress>((progress) => Upload.SetProgressValue(progress.ProgressPercentage)); Upload.CancellationToken = new System.Threading.CancellationTokenSource(); PendingUploads.Add(Upload); await LiveConnectClient.BackgroundUploadAsync(SkyDriveFolderToUpload, Upload.File.Name, Upload.File, OverwriteOption.Rename, Upload.CancellationToken.Token, Upload.ProgressHandler); Upload.SetProgressValue(100); fileInfoDict.Add("name", Upload.File.Name); string fileID = await GetSkyDriveFileID(Upload.File.Name); Debug.WriteLine("Upload completed, file name: " + Upload.File.Name + " file ID: " + fileID); string fileLink = await GetLinkOfFile(fileID); fileInfoDict.Add("link", fileLink); friendsPage.HidePendingUploadsPopup(); PendingUploads.Remove(Upload); return(fileInfoDict); } } catch (TaskCanceledException) { PendingUploads.Remove(Upload); friendsPage.HidePendingUploadsPopup(); var dialog = new MessageDialog("Upload of file " + file.Name + " has been cancelled."); dialog.Commands.Add(new UICommand("Ok")); dialog.ShowAsync(); } catch (LiveConnectException exception) { PendingUploads.Remove(Upload); friendsPage.HidePendingUploadsPopup(); var dialog = new MessageDialog("Error uploading file: " + exception.Message); dialog.Commands.Add(new UICommand("Ok")); dialog.ShowAsync(); } return(null); }
public void TestUploadEmptyStringPath() { var connectClient = new LiveConnectClient(new LiveConnectSession()); try { connectClient.BackgroundUploadAsync( string.Empty, "fileName.txt", new InMemoryRandomAccessStream(), OverwriteOption.Overwrite); Assert.Fail("Expected ArguementException to be thrown."); } catch (ArgumentException) { } }
public void TestBackgroundUploadNullPath() { var connectClient = new LiveConnectClient(new LiveConnectSession()); try { var uploadLocation = new Uri("/shared/transfers/uploadLocation.txt", UriKind.RelativeOrAbsolute); connectClient.BackgroundUploadAsync( null, uploadLocation, OverwriteOption.Overwrite); Assert.Fail("Expected ArguementException to be thrown."); } catch (ArgumentException) { } }
/// <summary> /// Upload a file to OneDrive /// </summary> /// <param name="Filename"></param> /// <param name="Content"></param> /// <returns></returns> public static async Task <int> UploadFileAsync(String Foldername, String Filename) { try { // create OneDrive auth client var authClient = new LiveAuthClient(); // ask for both read and write access to the OneDrive LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.signin", "wl.skydrive", "wl.skydrive_update" }); // if login successful if (result.Status == LiveConnectSessionStatus.Connected) { // create a OneDrive client liveClient = new LiveConnectClient(result.Session); // create a local file StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(Filename); // create a folder string folderID = await GetFolderIDAsync(Foldername, true); if (string.IsNullOrEmpty(folderID)) { // return error return(0); } // upload local file to OneDrive await liveClient.BackgroundUploadAsync(folderID, file.Name, file, OverwriteOption.Overwrite); return(1); } } catch (Exception e) { return(e.Message.Length); } // return error return(0); }
private async void fileUpload_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(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { LiveConnectClient liveClient = new LiveConnectClient(((App)Application.Current).LiveSession); await liveClient.BackgroundUploadAsync("me/skydrive", "MyUploadedPicture.pnsg", file, OverwriteOption.Overwrite); } } catch (LiveConnectException) { // Handle exceptions. } }
private async Task DoBackup(string filename) { if (await SignInSkydrive()) { await LoadData(); StorageFile backupFile = await ApplicationData.Current.LocalFolder.GetFileAsync(filename); if (backupFile != null && _skyDriveFolderId != null) { LiveConnectClient client = new LiveConnectClient(_session); LiveOperationResult operationResult = await client.BackgroundUploadAsync(_skyDriveFolderId, filename, backupFile, OverwriteOption.Overwrite); dynamic result = operationResult.Result; } else { throw new Exception(); } } }
/// <summary> /// Uploads selected files to skydrive /// </summary> /// <returns></returns> public static async Task UploadFilesAsync(Progress <LiveOperationProgress> progress) { await CheckIfExists(); var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary; picker.FileTypeFilter.Add(".bbf"); picker.FileTypeFilter.Add(".mp3"); picker.FileTypeFilter.Add(".wav"); picker.FileTypeFilter.Add(".aac"); IReadOnlyList <Windows.Storage.StorageFile> files = await picker.PickMultipleFilesAsync(); if (files.Count > 0) { OneDriveManager.CancelToken = new System.Threading.CancellationTokenSource(); foreach (var file in files) { await _client.BackgroundUploadAsync(OneDriveManager._folderId, file.Name, file, Microsoft.Live.OverwriteOption.Overwrite, OneDriveManager.CancelToken.Token, progress); } OneDriveManager.CancelToken = null; } }
private void uploadFile() { if (String.IsNullOrEmpty(_skyDriveFolderID)) { return; } Dispatcher.BeginInvoke(() => { ApplicationTitle.Text = "Subiendo a Skydrive..."; }); this.client.BackgroundUploadCompleted += client_BackgroundUploadCompleted; // Upload file try { client.BackgroundUploadAsync(_skyDriveFolderID, new Uri(filename, UriKind.Relative), OverwriteOption.Overwrite); } catch (Exception e) { MessageBox.Show(e.Message); } }
public void TestUploadEmptyStringPath() { var connectClient = new LiveConnectClient(new LiveConnectSession()); try { connectClient.BackgroundUploadAsync( string.Empty, "fileName.txt", new InMemoryRandomAccessStream(), OverwriteOption.Overwrite); Assert.Fail("Expected ArguementException to be thrown."); } catch (ArgumentException) { } }
async public Task uploadFileBackground(String folderId, Uri localFileUri) { LiveOperationResult res = await liveConnect.BackgroundUploadAsync(folderId, localFileUri, OverwriteOption.Overwrite); }
public void TestBackgroundUploadNullPath() { var connectClient = new LiveConnectClient(new LiveConnectSession()); try { var uploadLocation = new Uri("/shared/transfers/uploadLocation.txt", UriKind.RelativeOrAbsolute); connectClient.BackgroundUploadAsync( null, uploadLocation, OverwriteOption.Overwrite); Assert.Fail("Expected ArguementException to be thrown."); } catch (ArgumentException) { } }