private async Task <dynamic> GetUserLogged() { var liveIdClient = new LiveAuthClient(); Task <LiveLoginResult> tskLoginResult = liveIdClient.LoginAsync(new string[] { "wl.signin" }); tskLoginResult.Wait(); switch (tskLoginResult.Result.Status) { case LiveConnectSessionStatus.Connected: try { LiveConnectClient client = new LiveConnectClient(tskLoginResult.Result.Session); LiveOperationResult liveOperationResult = await client.GetAsync("me"); dynamic operationResult = liveOperationResult.Result; return(operationResult); } catch (Exception ex) { throw new Exception(string.Format("ERRO, {0}", ex.Message), ex); } case LiveConnectSessionStatus.NotConnected: break; } return(null); }
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); } }
public async Task Restore(string filename) { if (await SignInSkydrive()) { await LoadData(); try { StorageFile restoreFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); LiveConnectClient client = new LiveConnectClient(_session); LiveOperationResult liveOpResult2 = await client.GetAsync(_skyDriveFolderId + "/files"); dynamic result = liveOpResult2.Result; string backupFileID = null; foreach (var item in result.data) { if (item.name == filename) { backupFileID = item.id; break; } } if (backupFileID != null) { LiveDownloadOperationResult operationResult = await client.BackgroundDownloadAsync(backupFileID + "/content", restoreFile); } } catch (Exception exception) { throw new Exception("Error during restore: " + exception.Message); } } }
public static Task <LiveOperationResult> GetResponseAsync(this LiveConnectClient client, string param) { TaskCompletionSource <LiveOperationResult> tcs = new TaskCompletionSource <LiveOperationResult>(); EventHandler <LiveOperationCompletedEventArgs> handler = null; handler = (sender, arg) => { client.GetCompleted -= handler; if (arg.Cancelled) { tcs.TrySetCanceled(); } else if (arg.Error != null) { tcs.TrySetException(arg.Error); } else { LiveOperationResult result = new LiveOperationResult(arg.Result, arg.RawResult); tcs.TrySetResult(result); } }; client.GetCompleted += handler; client.GetAsync(param); return(tcs.Task); }
private async void OnFileSelected(object sender, RoutedEventArgs e) { var fileButton = sender as Button; var fileName = fileButton.Content as string; using (IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication()) { var isoFileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, myStore); string uploadLocation = this.TextBoxUrl.Text; this.ShowProgress(); try { LiveOperationResult operationResult = await this.liveClient.UploadAsync( uploadLocation, fileName, isoFileStream, OverwriteOption.Rename, new CancellationToken(false), this); isoFileStream.Dispose(); dynamic result = operationResult.Result; if (result.source != null) { this.ShowMessage("file uploaded \n" + result.source); } } catch (LiveConnectException exception) { this.ShowMessage(exception.Message); } } }
private static async Task <string> GetFolder(LiveConnectClient client, string parentFolder, string folderName) { string skyDriveFolderId = null; LiveOperationResult liveOpResult = await client.GetAsync(parentFolder + "/files?filter=folders"); dynamic appResult = liveOpResult.Result; List <object> folderData = appResult.data; foreach (dynamic folder in folderData) { string name = folder.name; if (name == folderName) { skyDriveFolderId = folder.id; } } //Create your Folder on SkyDrive if does not exist if (string.IsNullOrEmpty(skyDriveFolderId)) { var skyDriveFolderData = new Dictionary <string, object>(); skyDriveFolderData.Add("name", folderName); LiveOperationResult operationResult = await client.PostAsync(parentFolder, skyDriveFolderData); dynamic result = operationResult.Result; skyDriveFolderId = result.id; } return(skyDriveFolderId); }
private async Task <T> GetObjectFromRequest <T>(string getPath, Func <string, T> converter) { LiveOperationResult result = await this.LiveClient.GetAsync(getPath); System.Diagnostics.Debug.WriteLine("json: {0}", result.RawResult); return(converter(result.RawResult)); }
private async void UploadButton_Click(object sender, RoutedEventArgs e) { this.SetBackgroundTransferPreferences(); var file = this.fileList.SelectedItem as FileItem; string path = "me/skydrive"; var uploadLocation = new Uri(Path.Combine(this.currentDirectory, file.Name), UriKind.RelativeOrAbsolute); var overwriteOption = OverwriteOption.Rename; this.PrepareForUpload(); try { LiveOperationResult operationResult = await this.connectClient.BackgroundUploadAsync( path, uploadLocation, overwriteOption, cts.Token, this); dynamic result = operationResult.Result; MessageBox.Show("Upload successful. Uploaded to " + result.source); } catch (TaskCanceledException) { MessageBox.Show("Upload canceled."); } this.CleanUpAfterUpload(); }
public async Task BackupLocalDatabase() { string toUploadDatabaseName = "toUploadDatabase.sdf"; //release all resources from DB App.AppViewModel.DisposeCurrentDB(); // Obtain the virtual store for the application. IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication(); iso.CopyFile(AppResources.DatabaseName + ".sdf", toUploadDatabaseName, true); App.AppViewModel.ConnectDB(); LiveConnectClient liveClient = new LiveConnectClient(oneDriveAuthClient.Session); try { using (Stream uploadStream = iso.OpenFile(toUploadDatabaseName, FileMode.Open)) { if (uploadStream != null) { LiveOperationResult uploadResult = await liveClient.UploadAsync(oneDriveFolderId, databaseBackupname + ".sdf", uploadStream, OverwriteOption.Overwrite); MessageBox.Show("Upload successful."); } } iso.DeleteFile(toUploadDatabaseName); await getFileFromBackupFolderAsync(); } catch (LiveConnectException ex) { App.AppViewModel.SendExceptionReport(ex); } }
private async Task <DateTime> GetDateTime(string cloudpath, string filename, LiveConnectClient liveConnectClient) { DateTime ddt = new DateTime(); try { LiveOperationResult lor = await liveConnectClient.GetAsync(cloudpath); DirectoryInfo dirin = new DirectoryInfo(@"C:\users\nico\desktop\office365 key.txt"); DateTime dt = dirin.LastWriteTime; var iEnum = lor.Result.Values.GetEnumerator(); iEnum.MoveNext(); string temp = ""; foreach (dynamic var in iEnum.Current as IEnumerable) { if (var.name.Equals(filename)) { temp = var.updated_time; } } DateTimeConverter dtc = new DateTimeConverter(); ddt = (DateTime)dtc.ConvertFromString(temp); } catch (Exception) { } return(ddt); }
private async System.Threading.Tasks.Task Authenticate() { var liveIdClient = new LiveAuthClient(MobileServiceConfig.LiveClientId); while (session == null) { LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" }); if (result.Status == LiveConnectSessionStatus.Connected) { session = result.Session; MobileServiceUser user = await authenticationService.LoginAsync(result.Session.AuthenticationToken); var client = new LiveConnectClient(session); LiveOperationResult meResult = await client.GetAsync("me"); CurrentUser = new User(); CurrentUser.UserId = user.UserId; CurrentUser.Name = meResult.Result["first_name"].ToString(); } else { session = null; // TODO Login required } } }
private async Task PopulateMSAccountData(MSAccountPageModel model, AccountDataContent content) { string errorText = null; LiveConnectClient client = new LiveConnectClient(this.MSAuthClient.Session); LiveOperationResult meResult = await QueryUserData(client, "me"); if (meResult != null) { dynamic meInfo = meResult.Result; model.Name = meInfo.name; model.ProfileImage = await GetProfileImageData(client); } else { errorText = "There was an error while retrieving the user's information. Please try again later."; } if (errorText == null && (content & AccountDataContent.Contacts) == AccountDataContent.Contacts) { LiveOperationResult contactsResult = await QueryUserData(client, "me/contacts"); if (contactsResult != null) { dynamic contacts = contactsResult.Result; model.Contacts = contacts.data; } else { errorText = "There was an error while retrieving the user's contacts data. Please try again later."; } } model.Error = errorText; }
/// <summary> /// folderListClient event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void FolderListClient_GetCompleted(LiveOperationResult e, SkydriveAlbum album) { album.Photos.Clear(); List <object> data = (List <object>)e.Result["data"]; NumberOfImages = data.Count; if (NumberOfImages == 0) { HideProgressBar(); return; } foreach (IDictionary <string, object> photo in data) { var item = new SkydrivePhoto(); item.Title = (string)photo["name"]; item.Subtitle = (string)photo["name"]; item.PhotoUrl = (string)photo["source"]; item.Description = (string)photo["description"]; item.ID = (string)photo["id"]; if (album != null) { album.Photos.Add(item); } } }
/// <summary> /// To create an Event object on the user's default calendar by using the Live Connect REST API, make a POST request to /me/events. Pass the properties for the event in the request body, as shown here. /// Content-Type: application/json /// /// { /// "name": "Global Project Risk Management Meeting", /// "description": "Generate and assess risks for the project", /// "start_time": "2011-04-20T01:00:00-07:00", /// "end_time": "2011-04-20T02:00:00-07:00", /// "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599", /// "is_all_day_event": false, /// "availability": "busy", /// "visibility": "public" /// } /// </summary> /// <param name="newEvent"></param> /// <returns></returns> public async Task <Event> CreateEvent(Event newEvent, string calendarId, string[] scopes = null) { var client = await GetConnectClientAsync(scopes); var eventDictionary = new Dictionary <string, object>() { { "name", newEvent.Name }, { "description", newEvent.Description }, { "start_time", newEvent.StartTime.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) }, { "end_time", newEvent.EndTime.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) }, { "location", newEvent.Location }, { "is_all_day_event", newEvent.IsAllDayEvent }, { "availability", newEvent.Availability.ToLowerInvariant() }, { "visibility", newEvent.Visibility ?? "public" } }; string path = "{0}/events"; path = string.Format(CultureInfo.InvariantCulture, path, calendarId ?? "me"); LiveOperationResult operationResult = await client.PostAsync(path, eventDictionary); string result = operationResult.RawResult; return(result.TryJsonParse <Event>()); }
/// <summary> /// Return a collection of items that are shared with the logged in user. /// </summary> /// <returns></returns> public async Task <OneDriveItem[]> GetSharedItems() { LiveOperationResult result = await this.LiveClient.GetAsync("/me/skydrive/shared"); System.Diagnostics.Debug.WriteLine("json: {0}", result.RawResult); return(ConvertDataResponseToItems(result.RawResult, this)); }
/// <summary> /// Delete an event by its id. To delete an Event, make a DELETE request to /EVENT_ID. /// </summary> /// <param name="eventId"></param> /// <returns></returns> public async Task DeleteEvent(string eventId, string[] scopes = null) { var client = await GetConnectClientAsync(scopes); string path = $"/{eventId}"; LiveOperationResult operationResult = await client.DeleteAsync(path); }
private async void OnLoaded(object sender, RoutedEventArgs routedEventArgs) { // Look for any previously existing BackgroundUploads. // This must be called to clear old requests out of the system. foreach (LivePendingUpload pendingUpload in this.connectClient.GetPendingBackgroundUploads()) { this.PrepareForUpload(); try { LiveOperationResult operationResult = await pendingUpload.AttachAsync(this.cts.Token, this); dynamic result = operationResult.Result; MessageBox.Show("Upload successful. Uploaded to " + result.source); } catch (TaskCanceledException) { MessageBox.Show("Upload canceled."); } this.CleanUpAfterUpload(); } this.currentDirectory = "/"; this.LoadFileList(this.currentDirectory); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { if (!this.initialPageLoaded) { try { if (this.session != null) { LiveConnectClient client = new LiveConnectClient(this.session); LiveOperationResult result = await client.GetAsync(this.skydriveStack[0][0].SkyDriveID + "/files"); this.client_GetCompleted(result); this.statusLabel.Height = 0; this.initialPageLoaded = true; } } catch (LiveConnectException) { this.statusLabel.Height = this.labelHeight; this.statusLabel.Text = AppResources.SkyDriveInternetLost; } } base.OnNavigatedTo(e); }
/// <summary> /// Performs the BackgroundDownloadOperation. /// </summary> public async Task <LiveOperationResult> ExecuteAsync() { Debug.Assert(this.status != OperationStatus.Completed, "Cannot execute on a completed operation."); var builder = new BackgroundDownloadRequestBuilder { AccessToken = this.accessToken, DownloadLocationOnDevice = this.downloadLocationOnDevice, RequestUri = this.requestUri, TransferPreferences = this.transferPreferences }; this.request = builder.Build(); var eventAdapter = new BackgroundDownloadEventAdapter(this.backgroundTransferService, this.tcs); Task <LiveOperationResult> task = this.progress == null? eventAdapter.ConvertTransferStatusChangedToTask(this.request) : eventAdapter.ConvertTransferStatusChangedToTask(this.request, this.progress); Debug.Assert(this.tcs.Task == task, "EventAdapter returned a different task. This could affect cancel."); // if the request has already been cancelled do not add it to the service. if (this.status != OperationStatus.Cancelled) { this.backgroundTransferService.Add(this.request); this.status = OperationStatus.Started; } LiveOperationResult result = await task; this.status = OperationStatus.Completed; return(result); }
/// <summary> /// Upload a file from local storage to a SkyDrive's folder /// </summary> public async Task <OperationStatus> UploadFile(string localPath, string cloudPath) { using ( var fileStream = FileSystemService.OpenFile(localPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { try { if (_liveClient == null) { await SignIn(); } var tuple = await GetFolderIdAndFileName(cloudPath); LiveOperationResult res = await _liveClient.UploadAsync(tuple.Item1, tuple.Item2, fileStream, OverwriteOption.Overwrite); return(OperationStatus.Completed); } catch (Exception ex) { return(OperationStatus.Failed); } } }
private async void Upload_Btn_Click(object sender, EventArgs e) { if (ListPhotos.SelectedItems.Count > 0) { StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("shared", CreationCollisionOption.OpenIfExists); folder = await folder.CreateFolderAsync("transfers", CreationCollisionOption.OpenIfExists); using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { for (int i = 0; i < ListPhotos.SelectedItems.Count; i++) { var entry = ListPhotos.SelectedItems[i] as Entry; // copy to shared/transfers folder if (isoStore.FileExists(entry.ImgSrc)) { try { isoStore.CopyFile(entry.ImgSrc, "/shared/transfers/" + entry.ImgSrc); LiveOperationResult res = await App.ViewModelData.LiveClient.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + entry.ImgSrc, UriKind.Relative), OverwriteOption.Rename); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } } } } }
/// <summary> /// DownloadPictures downs picutre link from sky dirve /// </summary> /// <param name="albumItem"></param> private async void DownloadPictures(SkydriveAlbum albumItem) { LiveConnectClient folderListClient = new LiveConnectClient(App.Session); LiveOperationResult result = await folderListClient.GetAsync(albumItem.ID + "/files"); FolderListClient_GetCompleted(result, albumItem); }
private async void OnAuthCompleted(AuthResult result) { this.CleanupAuthForm(); if (result.AuthorizeCode != null) { try { LiveConnectSession session = await this.AuthClient.ExchangeAuthCodeAsync(result.AuthorizeCode); this.liveConnectClient = new LiveConnectClient(session); LiveOperationResult meRs = await this.liveConnectClient.GetAsync("me"); dynamic meData = meRs.Result; this.meNameLabel.Text = meData.name; LiveDownloadOperationResult meImgResult = await this.liveConnectClient.DownloadAsync("me/picture"); this.mePictureBox.Image = Image.FromStream(meImgResult.Stream); } catch (LiveAuthException aex) { MessageBox.Show("Failed to retrieve access token. Error: " + aex.Message); } catch (LiveConnectException cex) { MessageBox.Show("Failed to retrieve the user's data. Error: " + cex.Message); } } else { MessageBox.Show(string.Format("Error received. Error: {0} Detail: {1}", result.ErrorCode, result.ErrorDescription)); } }
private static void ValidateFile(LiveOperationResult result) { Assert.IsNotNull(result, "ValidateFiles failed. result is null."); Assert.IsNotNull(result.Result, "ValidateFiles failed. result.Result is null."); ValidateFileProperties(result.Result); }
/// <summary> /// PopulateBookmarksData /// </summary> /// <param name="path"></param> /// <returns></returns> private async Task <bool> PopulateBookmarksData(string path) { try { LiveConnectClient liveConnectClient = new LiveConnectClient(App.Session); LiveOperationResult liveOperationResult = await liveConnectClient.GetAsync(path); JsonObject jsonObject = JsonObject.Parse(liveOperationResult.RawResult); JsonArray jsonBookmarksArray = jsonObject.GetNamedArray("data"); if (jsonBookmarksArray.Count > 0) { foreach (JsonValue value in jsonBookmarksArray) { if (value.GetObject().GetNamedString("type") == "folder") { string folderPath = value.GetObject().GetNamedString("id") + "/files"; await PopulateBookmarksData(folderPath); } jsonBookmarksData.Add(value); } } } catch (Exception e) { string msg = e.Message; } return(true); }
/// <summary> /// Tests logging into MobileService with Live SDK token. App needs to be assosciated with a WindowsStoreApp /// </summary> private async Task TestLiveSDKLogin() { try { LiveAuthClient liveAuthClient = new LiveAuthClient(GetClient().ApplicationUri.ToString()); LiveLoginResult result = await liveAuthClient.InitializeAsync(new string[] { "wl.basic", "wl.offline_access", "wl.signin" }); if (result.Status != LiveConnectSessionStatus.Connected) { result = await liveAuthClient.LoginAsync(new string[] { "wl.basic", "wl.offline_access", "wl.signin" }); } if (result.Status == LiveConnectSessionStatus.Connected) { LiveConnectSession session = result.Session; LiveConnectClient client = new LiveConnectClient(result.Session); LiveOperationResult meResult = await client.GetAsync("me"); MobileServiceUser loginResult = await GetClient().LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken); Log(string.Format("{0} is now logged into MobileService with userId - {1}", meResult.Result["first_name"], loginResult.UserId)); } } catch (Exception exception) { Log(string.Format("ExceptionType: {0} Message: {1} StackTrace: {2}", exception.GetType().ToString(), exception.Message, exception.StackTrace)); Assert.Fail("Log in with Live SDK failed"); } }
private static void ValidateFiles(LiveOperationResult result) { Assert.IsNotNull(result, "ValidateFiles failed. result is null."); Assert.IsNotNull(result.Result, "ValidateFiles failed. result.Result is null."); var data = result.Result["data"] as IList; Assert.IsNotNull(data, "ValidateFiles failed. 'data' is null."); Assert.AreEqual(data.Count, 6, "ValidateFiles failed. 'data' count is incorrect."); foreach (object value in data) { var fileProperties = value as IDictionary <string, object>; Assert.IsTrue(!string.IsNullOrEmpty(fileProperties["id"] as string), "ValidateFiles failed. 'id' is null or empty."); string type = fileProperties["type"] as string; Assert.IsTrue(!string.IsNullOrEmpty(type), "ValidateFiles failed. 'type' is null or empty."); if (string.CompareOrdinal(type, "folder") == 0 || string.CompareOrdinal(type, "album") == 0) { Assert.IsTrue(!string.IsNullOrEmpty(fileProperties["name"] as string), "ValidateFiles failed. 'name' is null or empty."); Assert.IsTrue(!string.IsNullOrEmpty(fileProperties["upload_location"] as string), "ValidateFiles failed. 'upload_location' is null or empty."); } else { ValidateFileProperties(fileProperties); } } }
public async Task <string> GetUsersEmailAddress(CancellationToken ct) { LiveConnectSessionStatus connectStatus; if (client != null || (connectStatus = await Connect()) == LiveConnectSessionStatus.Connected) { LiveOperationResult operationResult; try { operationResult = meResult != null ? meResult : meResult = await client.GetAsync("me", ct); } catch (TaskCanceledException) { return(string.Empty); } if (ct.IsCancellationRequested) { return(string.Empty); } dynamic result = operationResult.Result; if (result.emails != null) { return(result.emails.account); } } return(string.Empty); }
public async Task <string> GetUsersFullName(CancellationToken ct) { LiveConnectSessionStatus connectStatus; if (client != null || (connectStatus = await Connect()) == LiveConnectSessionStatus.Connected) { LiveOperationResult operationResult; try { operationResult = meResult != null ? meResult : meResult = await client.GetAsync("me", ct); } catch (TaskCanceledException) { return(string.Empty); } if (ct.IsCancellationRequested) { return(string.Empty); } dynamic result = operationResult.Result; if (result.first_name != null && result.last_name != null) { return(string.Format(CultureInfo.CurrentCulture, "{0} {1}", result.first_name, result.last_name)); } } return(string.Empty); }
public static async Task <String> CreateExportFolder(LiveConnectClient client) { LiveOperationResult opResult = await client.GetAsync("me/skydrive/files"); var result = opResult.Result; IList <object> results = result["data"] as IList <object>; if (results == null) { throw new LiveConnectException(); } object o = results .Where(d => (d as IDictionary <string, object>)["name"].Equals(EXPORT_FOLDER)) .FirstOrDefault(); string id = null; if (o == null) { var folderData = new Dictionary <string, object>(); folderData.Add("name", EXPORT_FOLDER); opResult = await client.PostAsync("me/skydrive", folderData); dynamic postResult = opResult.Result; id = postResult.id; } else { IDictionary <string, object> folderProperties = o as IDictionary <string, object>; id = folderProperties["id"] as string; } return(id); }
private void OnGetUploadLinkCompleted(LiveOperationResult result) { if (result.Error != null || result.IsCancelled) { this.OnOperationCompleted(result); return; } this.Url = new Uri(result.RawResult, UriKind.Absolute); // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes, // and suppress_redirect query parameters set. Debug.Assert(this.Url.Query != null); Debug.Assert(this.Url.Query.Contains(QueryParameters.Overwrite)); Debug.Assert(this.Url.Query.Contains(QueryParameters.SuppressRedirects)); Debug.Assert(this.Url.Query.Contains(QueryParameters.SuppressResponseCodes)); if (this.PrepareRequest()) { try { var httpRequest = this.Request as HttpWebRequest; if (httpRequest != null && this.InputStream.CanSeek) { httpRequest.AllowWriteStreamBuffering = false; httpRequest.ContentLength = this.InputStream.Length; } this.Request.BeginGetRequestStream(this.OnGetRequestStreamCompleted, null); } catch (WebException exception) { if (exception.Status == WebExceptionStatus.RequestCanceled) { this.OnCancel(); } else { this.OnWebResponseReceived(exception.Response); } } } }
protected override void OnWebResponseReceived(WebResponse response) { // We are done with the HttpWebRequest so let's remove our reference to it. // If we hold on to it and Cancel is called, our parent class, WebOperation, will call this.Request.Abort // and this causes a Deadlock in the stream.BeginRead call in StreamCopyOperation. Not fun. this.Request = null; HttpStatusCode status = ((HttpWebResponse)response).StatusCode; if (status != HttpStatusCode.OK) { var result = this.CreateOperationResultFrom(response); if (result.Error is FormatException) { // We do expect non-JSON errors from other data providers for download requests. // If we can't understand the response body, we'll just return a generic error message. var error = new LiveConnectException( ApiOperation.ApiServerErrorCode, string.Format( CultureInfo.CurrentUICulture, ResourceHelper.GetString("ServerErrorWithStatus"), status.ToString())); result = new LiveOperationResult(error, false); } this.CompleteOperation(result.Error); } else if (((HttpWebResponse)response).StatusCode != HttpStatusCode.OK) { var result = this.CreateOperationResultFrom(response); this.CompleteOperation(result.Error); } else { this.response = response; Stream responseStream = this.response.GetResponseStream(); this.outputStream = new MemoryStream(); long totalBytesToReceive; string contentLength = response.Headers[DownloadOperation.HttpHeaderContentLength]; if (!string.IsNullOrEmpty(contentLength)) { if (!long.TryParse(contentLength, out totalBytesToReceive)) { totalBytesToReceive = DownloadOperation.UnknownFileSize; } } else { totalBytesToReceive = DownloadOperation.UnknownFileSize; } this.streamCopyOperation = new StreamCopyOperation( this.LiveClient, ApiMethod.Download, responseStream, this.outputStream, totalBytesToReceive, this.progress, this.Dispatcher, (isCancelled, error) => { if (isCancelled) { this.Cancel(); } this.CompleteOperation(error); }); Platform.RegisterForCancel(null, this.streamCopyOperation.Cancel); this.streamCopyOperation.Execute(); } }
/// <summary> /// Called when a BackgroundTransferRequet's TransferStatus is set to Completed. /// This method will remove the request from the BackgroundTransferService and call /// the LiveOperationEventArgs event handler. /// </summary> /// <param name="request">request with a TransferStatus that is set to Completed</param> private void OnTransferStatusComplete(BackgroundTransferRequest request) { Debug.Assert(request.TransferStatus == TransferStatus.Completed); Debug.Assert(BackgroundTransferHelper.IsDownloadRequest(request)); this.OnBackgroundTransferRequestCompleted(request); // Remove the transfer request in order to make room in the queue for more transfers. // Transfers are not automatically removed by the system. // Cancelled requests have already been removed from the system and cannot be removed twice. if (!BackgroundTransferHelper.IsCanceledRequest(request)) { try { this.backgroundTransferService.Remove(request); } catch (Exception exception) { this.tcs.TrySetException(new LiveConnectException( ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("BackgroundTransferServiceRemoveError"), exception)); return; } } if (request.TransferError != null) { var exception = new LiveConnectException(ApiOperation.ApiServerErrorCode, ResourceHelper.GetString("ServerError"), request.TransferError); this.tcs.TrySetException(exception); } else if (!BackgroundTransferHelper.IsSuccessfulStatusCode(request.StatusCode)) { var exception = new LiveConnectException(ApiOperation.ApiServerErrorCode, ResourceHelper.GetString("ServerError")); this.tcs.TrySetException(exception); } else { string jsonResponse = string.Format(JsonResponse, request.DownloadLocation.OriginalString.Replace("\\", "\\\\")); var jsonReader = new JsonReader(jsonResponse); var jsonObject = jsonReader.ReadValue() as IDictionary<string, object>; var result = new LiveOperationResult(jsonObject, jsonResponse); this.tcs.TrySetResult(result); } }
private async void OnGetUploadLinkCompleted(LiveOperationResult result) { if (this.Status == OperationStatus.Cancelled) { base.OnCancel(); return; } if (result.Error != null || result.IsCancelled) { this.OnOperationCompleted(result); return; } var uploadUrl = new Uri(result.RawResult, UriKind.Absolute); // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes, // and suppress_redirect query parameters set. Debug.Assert(uploadUrl.Query != null); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.Overwrite)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressRedirects)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressResponseCodes)); var uploader = new BT.BackgroundUploader(); uploader.Group = LiveConnectClient.LiveSDKUploadGroup; if (this.LiveClient.Session != null) { uploader.SetRequestHeader( ApiOperation.AuthorizationHeader, AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken); } uploader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue()); uploader.Method = HttpMethods.Put; this.uploadOpCts = new CancellationTokenSource(); Exception webError = null; LiveOperationResult opResult = null; try { if (this.InputStream != null) { this.uploadOp = await uploader.CreateUploadFromStreamAsync(uploadUrl, this.InputStream); } else { this.uploadOp = uploader.CreateUpload(uploadUrl, this.InputFile); } var progressHandler = new Progress<BT.UploadOperation>(this.OnUploadProgress); this.uploadOp = await this.uploadOp.StartAsync().AsTask(this.uploadOpCts.Token, progressHandler); } catch (TaskCanceledException exception) { opResult = new LiveOperationResult(exception, true); } catch (Exception exp) { // This might be an server error. We will read the response to determine the error message. webError = exp; } if (opResult == null) { try { IInputStream responseStream = this.uploadOp.GetResultStreamAt(0); if (responseStream == null) { var error = new LiveConnectException( ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("ConnectionError")); opResult = new LiveOperationResult(error, false); } else { var reader = new DataReader(responseStream); uint length = await reader.LoadAsync(MaxUploadResponseLength); opResult = ApiOperation.CreateOperationResultFrom(reader.ReadString(length), ApiMethod.Upload); if (webError != null && opResult.Error != null && !(opResult.Error is LiveConnectException)) { // If the error did not come from the api service, // we'll just return the error thrown by the uploader. opResult = new LiveOperationResult(webError, false); } } } catch (COMException exp) { opResult = new LiveOperationResult(exp, false); } catch (FileNotFoundException exp) { opResult = new LiveOperationResult(exp, false); } } this.OnOperationCompleted(opResult); }
private async void OnGetUploadLinkCompleted(LiveOperationResult result) { if (result.Error != null) { this.taskCompletionSource.SetException(result.Error); return; } var uploadUrl = new Uri(result.RawResult, UriKind.Absolute); // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes, // and suppress_redirect query parameters set. Debug.Assert(uploadUrl.Query != null); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.Overwrite)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressRedirects)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressResponseCodes)); var uploader = new BackgroundUploader(); uploader.Group = LiveConnectClient.LiveSDKUploadGroup; if (this.LiveClient.Session != null) { uploader.SetRequestHeader( ApiOperation.AuthorizationHeader, AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken); } uploader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue()); uploader.Method = HttpMethods.Put; UploadOperation uploadOperation; if (this.InputStream != null) { uploadOperation = await uploader.CreateUploadFromStreamAsync(uploadUrl, this.InputStream); } else { uploadOperation = uploader.CreateUpload(uploadUrl, this.InputFile); } this.taskCompletionSource.SetResult(new LiveUploadOperation(uploadOperation)); }
/// <summary> /// Parses the WebResponse's body and creates a LiveOperationResult object from it. /// </summary> protected LiveOperationResult CreateOperationResultFrom(WebResponse response) { LiveOperationResult opResult; bool nullResponse = (response == null); try { Stream responseStream = (!nullResponse) ? response.GetResponseStream() : null; if (nullResponse || responseStream == null) { var error = new LiveConnectException( ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("ConnectionError")); opResult = new LiveOperationResult(error, false); } else { using (var sr = new StreamReader(responseStream)) { string rawResult = sr.ReadToEnd(); opResult = this.CreateOperationResultFrom(rawResult); } } } finally { if (!nullResponse) { ((IDisposable)response).Dispose(); } } return opResult; }
/// <summary> /// Calls the OperationCompletedCallback delegate. /// This method is called when the ApiOperation is completed. /// </summary> protected void OnOperationCompleted(LiveOperationResult opResult) { Action<LiveOperationResult> callback = this.OperationCompletedCallback; if (callback != null) { callback(opResult); } }
protected override void OnWebResponseReceived(WebResponse response) { LiveOperationResult opResult = this.CreateOperationResultFrom(response); if (opResult.Error != null) { this.OnOperationCompleted(opResult); return; } string uploadLink = null; if (opResult.Result != null && opResult.Result.ContainsKey(UploadLocationKey)) { uploadLink = opResult.Result[UploadLocationKey] as string; } if (string.IsNullOrEmpty(uploadLink)) { var error = new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("NoUploadLinkFound")); opResult = new LiveOperationResult(error, false); } else { try { Uri resourceUploadUrl = this.ConstructUploadUri(uploadLink); opResult = new LiveOperationResult(null, resourceUploadUrl.OriginalString); } catch (LiveConnectException exp) { opResult = new LiveOperationResult(exp, false); } } this.OnOperationCompleted(opResult); }