Ejemplo n.º 1
0
        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);
                }
            }
        }
Ejemplo n.º 2
0
        private async void btnSelectDownloadFile_Click(object sender, RoutedEventArgs e)
        {
            if (this.liveClient == null)
            {
                this.ShowMessage("Please sign in first.");
                return;
            }

            if (string.IsNullOrEmpty(this.tbdownloadUrl.Text))
            {
                this.ShowMessage("Please specify the link to the file to be downloaded.");
                return;
            }

            try
            {
                string fileLink = this.tbdownloadUrl.Text;

                var roamingSettings = ApplicationData.Current.RoamingSettings;
                roamingSettings.Values["FileName"] = this.fileName;

                var appSettingContainer = roamingSettings.CreateContainer(
                    "FileUploadDownload Settings", 
                    ApplicationDataCreateDisposition.Always);
                appSettingContainer.Values[this.fileName] = true;

                var roamingFolder = ApplicationData.Current.RoamingFolder;
                var storageDir = await roamingFolder.CreateFolderAsync(
                    "FileUploadDownload sample", 
                    CreationCollisionOption.OpenIfExists);

                var storageFile =
                    await storageDir.CreateFileAsync(this.fileName, CreationCollisionOption.ReplaceExisting);

                if (storageFile != null)
                {
                    this.progressBar.Value = 0;
                    var progressHandler = new Progress<LiveOperationProgress>(
                        (progress) => { this.progressBar.Value = progress.ProgressPercentage; });

                    this.ShowProgress();
                    this.cts = new CancellationTokenSource();

                    LiveDownloadOperation operation = await this.liveClient.CreateBackgroundDownloadAsync(
                        fileLink, 
                        storageFile);
                    LiveDownloadOperationResult result = await operation.StartAsync(this.cts.Token, progressHandler);

                    this.ShowMessage("Download completed.");
                }
            }
            catch (TaskCanceledException)
            {
                this.ShowMessage("User has cancelled the operation.");
            }
            catch (Exception exp)
            {
                this.ShowMessage(exp.ToString());
            }
        }
Ejemplo n.º 3
0
        private async void OnAuthCompleted(AuthResult authResult)
        {
            this.CleanupBrowser();
            if (authResult.AuthorizeCode != null)
            {
                try
                {
                    LiveConnectSession session = await this.AuthClient.ExchangeAuthCodeAsync(authResult.AuthorizeCode);

                    this.liveConnectClient = new LiveConnectClient(session);
                    LiveOperationResult meRes = await this.liveConnectClient.GetAsync("me");

                    dynamic meData = meRes.Result;
                    this.nameLabel.Text = meData.name;
                    LiveDownloadOperationResult meImgResult = await this.liveConnectClient.DownloadAsync("me/picture");

                    this.meImage.Image = Image.FromStream(meImgResult.Stream);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error", e.Message);
                }
                updateTree();
            }
        }
Ejemplo n.º 4
0
        public virtual async Task <bool> DownloadPasswords()
        {
            if (!IsConnected)
            {
                await Login();
            }
            if (!IsConnected)
            {
                return(false);
            }

            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            string passwordFileId        = await GetPasswordFileId();

            if (passwordFileId == null)
            {
                return(false);
            }
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("accounts.dat", FileMode.OpenOrCreate, isoStore))
            {
                LiveDownloadOperationResult result = await _connectClient.DownloadAsync(passwordFileId + "/content");

                result.Stream.CopyTo(isoStream);
            }
            return(true);
        }
Ejemplo n.º 5
0
        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)
                {
                    this.LogOutput("Failed to retrieve access token. Error: " + aex.Message);
                }
                catch (LiveConnectException cex)
                {
                    this.LogOutput("Failed to retrieve the user's data. Error: " + cex.Message);
                }
            }
            else
            {
                this.LogOutput(string.Format("Error received. Error: {0} Detail: {1}", result.ErrorCode, result.ErrorDescription));
            }
        }
        private void CompleteOperation(Exception error)
        {
            LiveDownloadOperationResult opResult;

            if (this.response != null)
            {
                this.response.Close();
            }

            if (this.IsCancelled)
            {
                opResult = new LiveDownloadOperationResult(null, true);
            }
            else if (error != null)
            {
                opResult = new LiveDownloadOperationResult(error, false);
            }
            else
            {
                this.outputStream.Seek(0, 0);
                opResult = new LiveDownloadOperationResult(this.outputStream);
            }

            Action <LiveDownloadOperationResult> callback = this.OperationCompletedCallback;

            if (callback != null)
            {
                callback(opResult);
            }
        }
Ejemplo n.º 7
0
        private async Task DownloadFile(SkyDriveListItem item, LiveConnectClient client)
        {
            var indicator = SystemTray.GetProgressIndicator(this);

            indicator.IsIndeterminate = true;
            indicator.Text            = String.Format(AppResources.DownloadingProgressText, item.Name);

            item.Downloading = true;
            try
            {
                LiveDownloadOperationResult e = await client.DownloadAsync(item.SkyDriveID + "/content");

                if (e != null)
                {
                    item.Stream = e.Stream;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK);
            }

#if GBC
            indicator.Text = AppResources.ApplicationTitle2;
#else
            indicator.Text = AppResources.ApplicationTitle;
#endif
            indicator.IsIndeterminate = false;

            item.Downloading = false;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Calls the OperationCompletedCallback with the given result.
        /// This should be called when the TailoredDownloadOperation is completed.
        /// </summary>
        protected void OnOperationCompleted(LiveDownloadOperationResult result)
        {
            Action <LiveDownloadOperationResult> callback = this.OperationCompletedCallback;

            if (callback != null)
            {
                callback(result);
            }
        }
Ejemplo n.º 9
0
        private async void OnPhotoChooserTaskCompleted(object sender, PhotoResult e)
        {
            if (e.Error != null)
            {
                this.ShowMessage(e.Error.ToString());
            }
            else if (e.OriginalFileName == null)
            {
                this.ShowMessage("No Photo Choosen.");
            }
            else
            {
                string[] filePathSegments = e.OriginalFileName.Split('\\');
                string   fileName         = filePathSegments[filePathSegments.Length - 1];

                try
                {
                    var progressHandler = new Progress <LiveOperationProgress>((LiveOperationProgress progress) =>
                    {
                        this.progressBar.Value = progress.ProgressPercentage;
                    });
                    this.ShowProgress();

                    LiveOperationResult operationResult = await this.liveClient.UploadAsync(
                        this.tbUrl.Text,
                        fileName,
                        e.ChosenPhoto,
                        OverwriteOption.Rename,
                        new CancellationToken(false),
                        progressHandler);

                    e.ChosenPhoto.Dispose();

                    this.progressBar.Value = 0;
                    dynamic result       = operationResult.Result;
                    string  fileLocation = result.source;
                    LiveDownloadOperationResult downloadOperationResult =
                        await this.liveClient.DownloadAsync(fileLocation, new CancellationToken(false), progressHandler);

                    using (Stream downloadStream = downloadOperationResult.Stream)
                    {
                        if (downloadStream != null)
                        {
                            var imgSource = new BitmapImage();
                            imgSource.SetSource(downloadStream);
                            this.imgPreview.Source = imgSource;

                            this.ShowImage();
                        }
                    }
                }
                catch (Exception exp)
                {
                    this.ShowMessage(exp.ToString());
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            BT.BackgroundDownloader downloader;
            if (this.Url.OriginalString.StartsWith(this.LiveClient.ApiEndpoint, StringComparison.OrdinalIgnoreCase))
            {
                if (base.RefreshTokenIfNeeded())
                {
                    return;
                }

                downloader = new BT.BackgroundDownloader();
                if (this.LiveClient.Session != null)
                {
                    downloader.SetRequestHeader(
                        ApiOperation.AuthorizationHeader,
                        AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken);
                }
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());
            }
            else
            {
                downloader = new BT.BackgroundDownloader();
            }

            downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
            this.cts         = new CancellationTokenSource();
            this.downloadOp  = downloader.CreateDownload(this.Url, this.OutputFile);
            var progressHandler = new Progress <BT.DownloadOperation>(this.OnDownloadProgress);

            LiveDownloadOperationResult result = null;
            Exception webError = null;

            try
            {
                this.downloadOp = await this.downloadOp.StartAsync().AsTask(this.cts.Token, progressHandler);

                result = this.OutputFile != null ?
                         new LiveDownloadOperationResult(this.OutputFile) :
                         new LiveDownloadOperationResult(this.downloadOp.GetResultStreamAt(0));
            }
            catch (TaskCanceledException)
            {
                result = new LiveDownloadOperationResult(null, true);
            }
            catch (Exception error)
            {
                webError = error;
            }

            if (webError != null)
            {
                result = await this.ProcessDownloadErrorResponse(webError);
            }

            this.OnOperationCompleted(result);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Downloads the contents of a file represented by this OneDriveItem.
        /// </summary>
        /// <param name="btp"></param>
        /// <param name="progress"></param>
        /// <returns></returns>
        public async Task <System.IO.Stream> DownloadContentsAsync(IBackgroundTransferProvider btp = null, IProgress <LiveOperationProgress> progress = null)
        {
            if (this.ItemType != OneDriveItemType.GenericFile)
            {
                throw new InvalidOperationException("Cannot download items that are not files");
            }

            LiveDownloadOperationResult result = await Client.LiveClient.DownloadAsync(string.Format("/{0}/content", this.Identifier), btp, progress);

            return(result.Stream);
        }
Ejemplo n.º 12
0
        private async void DownloadFile()
        {
            if (this.liveClient == null)
            {
                this.ShowMessage("Please sign in first.");
                return;
            }

            try
            {
                string filePath = this.tbUrl.Text;
                if (string.IsNullOrEmpty(filePath))
                {
                    this.ShowMessage("Please specify a file id or a url.");
                }
                else
                {
                    this.progressBar.Value = 0;
                    this.ShowProgress();
                    var progressHandler = new Progress <LiveOperationProgress>(
                        (progress) => { this.progressBar.Value = progress.ProgressPercentage; });

                    this.cts = new CancellationTokenSource();
                    LiveDownloadOperation op =
                        await this.liveClient.CreateBackgroundDownloadAsync(filePath);

                    LiveDownloadOperationResult downloadResult = await op.StartAsync(this.cts.Token, progressHandler);

                    if (downloadResult.Stream != null)
                    {
                        using (IRandomAccessStream ras = await downloadResult.GetRandomAccessStreamAsync())
                        {
                            var imgSource = new BitmapImage();
                            imgSource.SetSource(ras);
                            this.imgPreview.Source = imgSource;

                            this.ShowImage();
                        }
                    }
                    else
                    {
                        this.ShowMessage("Download failed.");
                    }
                }
            }
            catch (TaskCanceledException)
            {
                this.ShowMessage("User has cancelled the operation.");
            }
            catch (Exception exp)
            {
                this.ShowMessage(exp.ToString());
            }
        }
Ejemplo n.º 13
0
        public async Task <Stream> DownloadFileAsStream(string fileId)
        {
            LiveConnectSessionStatus connectStatus;

            if (client != null || (connectStatus = await Connect()) == LiveConnectSessionStatus.Connected)
            {
                LiveDownloadOperationResult fileDownloadResult = await client.DownloadAsync(fileId + "/content");

                return(fileDownloadResult.Stream);
            }
            return(null);
        }
Ejemplo n.º 14
0
        public async Task RestoreBackupfile(Backupfile file)
        {
            RestoreLock = true;
            string tmpPathDatabase = "downloadedDatabase.sdf";
            //release all resources from DB

            LiveConnectClient liveClient = new LiveConnectClient(oneDriveAuthClient.Session);

            try
            {
                LiveDownloadOperationResult downloadResult = await liveClient.DownloadAsync(file.FileID + "/content");

                using (Stream downloadStream = downloadResult.Stream)
                {
                    if (downloadStream != null)
                    {
                        using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream output = storage.CreateFile(tmpPathDatabase))
                            {
                                // Initialize the buffer.
                                byte[] readBuffer = new byte[4096];
                                int    bytesRead  = -1;

                                // Copy the file from the installation folder to the local folder.
                                while ((bytesRead = downloadStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                                {
                                    output.Write(readBuffer, 0, bytesRead);
                                }
                            }
                        }
                    }
                }
                MessageBox.Show("Download successful. Restore started.");

                IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();

                App.AppViewModel.RestoreDatabase(tmpPathDatabase);

                if (iso.FileExists(tmpPathDatabase))
                {
                    iso.DeleteFile(tmpPathDatabase);
                }

                MessageBox.Show("Restore succesfull.");
                RestoreLock = false;
            }
            catch (LiveConnectException ex)
            {
                App.AppViewModel.SendExceptionReport(ex);
                RestoreLock = false;
            }
        }
Ejemplo n.º 15
0
        private async void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LiveDownloadOperationResult downloadOperationResult =
                    await this.liveClient.DownloadAsync(this.id + "/content", new CancellationToken(false), this);

                this.SaveToStorage(downloadOperationResult.Stream);
            }
            catch (LiveConnectException exception)
            {
                this.TextBox.Text = exception.Message;
            }
        }
Ejemplo n.º 16
0
        // Summary:
        //     Download a file by file id.
        //
        // Parameters:
        //  sourceFileId:
        //      The id of the file you want to download.
        //
        // Returns:
        //     The input stream to download file.
        public async Task <Stream> DownloadFileStreamAsync(string sourceFileId)
        {
            System.Threading.CancellationTokenSource ctsDownload = new System.Threading.CancellationTokenSource();
            LiveDownloadOperationResult result = null;

            try
            {
                //result = await this.LiveClient.DownloadAsync(sourceFileId + "/content");
                result = await this.LiveClient.BackgroundDownloadAsync(sourceFileId + "/content");
            }
            catch
            {
                throw new ShareException(sourceFileId, ShareException.ShareType.DOWNLOAD);
            }
            return(result.Stream.AsStreamForRead());
        }
Ejemplo n.º 17
0
        private async Task <byte[]> GetProfileImageData(LiveConnectClient client)
        {
            byte[] imgData = null;
            try
            {
                LiveDownloadOperationResult meImgResult = await client.DownloadAsync("me/picture");

                imgData = new byte[meImgResult.Stream.Length];
                await meImgResult.Stream.ReadAsync(imgData, 0, imgData.Length);
            }
            catch
            {
                // Failed to download image data.
            }

            return(imgData);
        }
Ejemplo n.º 18
0
        private async void LoadFileAsync(string fileID, AsyncContext context)
        {
            try
            {
                LiveConnectClient skyDrive = await _liveLogin.Login();

                if (skyDrive == null)
                {
                    context.Error = new Exception("Login Required");
                    return;
                }

                LiveOperationResult fileData = await skyDrive.GetAsync(fileID);

                string path = FixSkyDriveUrl((string)fileData.Result["source"]);

                LiveDownloadOperationResult downloadResult = await skyDrive.DownloadAsync(path);

                var buffer       = new byte[4096];
                var memoryStream = new MemoryStream();
                StreamUtils.Copy(downloadResult.Stream, memoryStream, buffer);
                memoryStream.Position = 0L;
                context.Stream        = memoryStream;
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.RequestCanceled)
                {
                    context.Error = new RestartException(e.Message, e);
                    return;
                }
                context.Error = e;
            }
            catch (TaskCanceledException e)
            {
                context.Error = new RestartException(e.Message, e);
            }
            catch (Exception e)
            {
                context.Error = e;
            }
            finally
            {
                context.WaitHandle.Set();
            }
        }
Ejemplo n.º 19
0
        private void OnLiveClientDownloadCompleted(System.Threading.Tasks.Task <LiveDownloadOperationResult> task, OneDriveFile file)
        {
            // Sync Step 4. The file has been downloaded as a memory stream.
            // Write it to its direct location.
            // (This runs on the emulator and on devices where the background download method failed.)

            if (!CheckTaskCompleted(task, "Download failed (" + file.Name + ")"))
            {
                PostProcessDownload(file, null, false);
                return;
            }

            LiveDownloadOperationResult result = task.Result;

            string filepath = GetIsoStorePath(file.Name, file.DownloadDirectory);
            bool   success  = false;

            try
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // Makes sure the directory exists.
                    isf.CreateDirectory(file.DownloadDirectory);

                    // Creates a file at the right place.
                    using (IsolatedStorageFileStream fs = isf.OpenFile(filepath, FileMode.Create))
                    {
                        result.Stream.CopyTo(fs);
                    }
                }

                Log("Created " + filepath);

                success = true;
            }
            catch (Exception e)
            {
                Log("Error while writing " + filepath + ": " + e.Message);
                Geowigo.Utils.DebugUtils.DumpException(e, file.ToString(), true);

                success = false;
            }

            PostProcessDownload(file, filepath, success);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Download TNS from path in Skydrive and update known routes/stops
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static async Task DownloadTNS(string path)
        {
            try
            {
                LiveDownloadOperationResult ldor = await CloudStorage.Client.DownloadAsync(path + "/content");

                //TransitNetworkSearch tns = JsonConvert.DeserializeObject<TransitNetworkSearch>("hi");
                TransitNetworkSearch tns;
                using (StreamReader sr = new StreamReader(ldor.Stream))
                {
                    string content = sr.ReadToEnd();
                    tns = JsonConvert.DeserializeObject <TransitNetworkSearch>(content);
                }
                TransitNetworkSearch.SaveTNS(tns);
            }
            catch
            {
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     Downloads the profile picture of the current user.
        /// </summary>
        private async void GetProfilePicture()
        {
            try
            {
                LiveDownloadOperationResult downloadOperationResult = await this.liveClient.DownloadAsync("me/picture");

                Stream stream = downloadOperationResult.Stream;
                if (stream != null)
                {
                    BitmapImage imgSource = new BitmapImage();
                    imgSource.SetSource(stream);
                    this.imgMe.Source = imgSource;
                }
            }
            catch (LiveConnectException e)
            {
                this.tbResponse.Text = e.ToString();
            }
        }
Ejemplo n.º 22
0
        public async static Task <string> DownloadAsync(string fileId)
        {
            try
            {
                if (fileId != null)
                {
                    LiveDownloadOperationResult operationResult = await _client.DownloadAsync(fileId + "/content");

                    if (operationResult.Stream != null)
                    {
                        operationResult.Stream.Position = 0;
                        StreamReader sr = new StreamReader(operationResult.Stream);
                        return(await sr.ReadToEndAsync());
                    }
                }
            }
            catch (Exception) { }
            return(null);
        }
Ejemplo n.º 23
0
        public static async Task<string> SetupChmFileFromOneDrive(LiveConnectClient client, 
            IProgress<LiveOperationProgress> progressHandler,
            System.Threading.CancellationToken ctoken,
            string id, string name, string path)
        {
            ChmFile ret = new ChmFile();
            ret.Key = Guid.NewGuid().ToString("N");
            ret.HasThumbnail = false;
            Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            StorageFile file = await localFolder.CreateFileAsync(ret.Key + ChmFileExtension, CreationCollisionOption.ReplaceExisting);
            LiveDownloadOperationResult result = await client.BackgroundDownloadAsync(id + "/content", file, ctoken, progressHandler);
            
            try
            {
                ret.Chm = await LoadChm(file.Path, false);
                MetaInfo meta = new MetaInfo();
                meta.SetOriginalPath(path);
                if (ret.Chm.Title != null)
                {
                    meta.SetDisplayName(ret.Chm.Title);
                }
                else
                {
                    meta.SetDisplayName(System.IO.Path.GetFileNameWithoutExtension(name));
                }
                ret.ChmMeta = meta;
                await ret.Save();
                FileHistory.AddToHistory(ret.Key);
            }
            catch
            {
                ret.Chm = null;
            }
            if (ret.Chm == null)
            {
                await MetaInfo.DeleteMetaFile(ret.Key);
                await DeleteFile(ret.Key);
                return null;
            }
            return ret.Key;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Process the error response.
        /// </summary>
        private async Task <LiveDownloadOperationResult> ProcessDownloadErrorResponse(Exception exception)
        {
            LiveDownloadOperationResult opResult;

            try
            {
                IInputStream responseStream = this.downloadOp.GetResultStreamAt(0);
                if (responseStream == null)
                {
                    var error = new LiveConnectException(
                        ApiOperation.ApiServerErrorCode,
                        ResourceHelper.GetString("ConnectionError"));
                    opResult = new LiveDownloadOperationResult(error, false);
                }
                else
                {
                    var  reader = new DataReader(responseStream);
                    uint length = await reader.LoadAsync(TailoredDownloadOperation.MaxDownloadResponseLength);

                    Exception error = CreateOperationResultFrom(reader.ReadString(length), this.Method).Error;
                    if (error is FormatException)
                    {
                        // if we cannot understand the error response,
                        // return the exception thrown by the background downloader.
                        error = exception;
                    }

                    opResult = new LiveDownloadOperationResult(error, false);
                }
            }
            catch (COMException exp)
            {
                opResult = new LiveDownloadOperationResult(exp, false);
            }
            catch (FileNotFoundException exp)
            {
                opResult = new LiveDownloadOperationResult(exp, false);
            }

            return(opResult);
        }
Ejemplo n.º 25
0
        private async void GetProfilePicture()
        {
            try
            {
                LiveDownloadOperationResult result = await this.liveClient.BackgroundDownloadAsync("me/picture");

                if (result != null && result.Stream != null)
                {
                    using (IRandomAccessStream ras = await result.GetRandomAccessStreamAsync())
                    {
                        BitmapImage imgSource = new BitmapImage();
                        imgSource.SetSource(ras);
                        this.imgMe.Source = imgSource;
                    }
                }
            }
            catch (LiveConnectException e)
            {
                this.tbResponse.Text = e.ToString();
            }
        }
Ejemplo n.º 26
0
        private async void ButtonDownload_Click(object sender, RoutedEventArgs e)
        {
            this.ShowProgress();
            try
            {
                LiveDownloadOperationResult downloadOperationResult =
                    await this.liveClient.DownloadAsync(this.id + "/content", new CancellationToken(false), this);

                Stream fileContent = downloadOperationResult.Stream;
                if (IsImageFile(this.name))
                {
                    this.ShowImage(fileContent);
                }
                else
                {
                    this.ShowText(fileContent);
                }
            }
            catch (LiveConnectException exception)
            {
                this.ShowMessage(exception.Message);
            }
        }
Ejemplo n.º 27
0
        private async Task LoadProfileImage(LiveConnectClient connectClient)
        {
            try
            {
                LiveDownloadOperation downloadOperation = await connectClient.CreateBackgroundDownloadAsync("me/picture");

                LiveDownloadOperationResult result = await downloadOperation.StartAsync();

                if (result != null && result.Stream != null)
                {
                    using (IRandomAccessStream ras = await result.GetRandomAccessStreamAsync())
                    {
                        BitmapImage imgSource = new BitmapImage();
                        imgSource.SetSource(ras);
                        profileImage.Source = imgSource;
                    }
                }
            }
            catch (LiveConnectException)
            {
                // Handle error cases.
            }
        }
Ejemplo n.º 28
0
        private async Task DownloadFile(string path)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            Stream         stream = null;

            dialog.RestoreDirectory = true;

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                throw new InvalidOperationException("No file is picked to upload.");
            }
            try
            {
                if ((stream = dialog.OpenFile()) == null)
                {
                    throw new Exception("Unable to open the file selected to upload.");
                }

                using (stream)
                {
                    LiveDownloadOperationResult result = await this.liveConnectClient.DownloadAsync(path);

                    if (result.Stream != null)
                    {
                        using (result.Stream)
                        {
                            await result.Stream.CopyToAsync(stream);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            BT.BackgroundDownloader downloader;
            if (this.Url.OriginalString.StartsWith(this.LiveClient.ApiEndpoint, StringComparison.OrdinalIgnoreCase))
            {
                if (base.RefreshTokenIfNeeded())
                {
                    return;
                }

                downloader = new BT.BackgroundDownloader();
                if (this.LiveClient.Session != null)
                {
                    downloader.SetRequestHeader(
                        ApiOperation.AuthorizationHeader,
                        AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken);
                }
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());
            }
            else
            {
                downloader = new BT.BackgroundDownloader();
            }

            downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
            this.cts = new CancellationTokenSource();
            this.downloadOp = downloader.CreateDownload(this.Url, this.OutputFile);
            var progressHandler = new Progress<BT.DownloadOperation>(this.OnDownloadProgress);

            LiveDownloadOperationResult result = null;
            Exception webError = null;
            try
            {
                this.downloadOp = await this.downloadOp.StartAsync().AsTask(this.cts.Token, progressHandler);

                result = this.OutputFile != null ?
                         new LiveDownloadOperationResult(this.OutputFile) :
                         new LiveDownloadOperationResult(this.downloadOp.GetResultStreamAt(0));
            }
            catch (TaskCanceledException)
            {
                result = new LiveDownloadOperationResult(null, true);
            }
            catch (Exception error)
            {
                webError = error;
            }

            if (webError != null)
            {
                result = await this.ProcessDownloadErrorResponse(webError);
            }

            this.OnOperationCompleted(result);
        }
        /// <summary>
        /// Process the error response.
        /// </summary>
        private async Task<LiveDownloadOperationResult> ProcessDownloadErrorResponse(Exception exception)
        {
            LiveDownloadOperationResult opResult;
            try
            {
                IInputStream responseStream = this.downloadOp.GetResultStreamAt(0);
                if (responseStream == null)
                {
                    var error = new LiveConnectException(
                        ApiOperation.ApiServerErrorCode,
                        ResourceHelper.GetString("ConnectionError"));
                    opResult = new LiveDownloadOperationResult(error, false);
                }
                else
                {
                    var reader = new DataReader(responseStream);
                    uint length = await reader.LoadAsync(TailoredDownloadOperation.MaxDownloadResponseLength);
                    Exception error = CreateOperationResultFrom(reader.ReadString(length), this.Method).Error;
                    if (error is FormatException)
                    {
                        // if we cannot understand the error response,
                        // return the exception thrown by the background downloader.
                        error = exception;
                    }

                    opResult = new LiveDownloadOperationResult(error, false);
                }
            }
            catch (COMException exp)
            {
                opResult = new LiveDownloadOperationResult(exp, false);
            }
            catch (FileNotFoundException exp)
            {
                opResult = new LiveDownloadOperationResult(exp, false);
            }

            return opResult;
        }
        private void CompleteOperation(Exception error)
        {
            LiveDownloadOperationResult opResult;

            if (this.response != null)
            {
                this.response.Dispose();
                //this.response.Close();
            }

            if (this.IsCancelled)
            {
                opResult = new LiveDownloadOperationResult(null, true);
            }
            else if (error != null)
            {
                opResult = new LiveDownloadOperationResult(error, false);
            }
            else
            {
                this.outputStream.Seek(0, 0);
                opResult = new LiveDownloadOperationResult(this.outputStream);
            }

            Action<LiveDownloadOperationResult> callback = this.OperationCompletedCallback;
            if (callback != null)
            {
                callback(opResult);
            }
        }
Ejemplo n.º 32
0
        private async Task DownloadFile(SkyDriveListItem item, LiveConnectClient client)
        {
            StorageFolder folder    = ApplicationData.Current.LocalFolder;
            StorageFolder romFolder = await folder.CreateFolderAsync(FileHandler.ROM_DIRECTORY, CreationCollisionOption.OpenIfExists);

            StorageFolder saveFolder = await romFolder.CreateFolderAsync(FileHandler.SAVE_DIRECTORY, CreationCollisionOption.OpenIfExists);

            String path     = romFolder.Path;
            String savePath = saveFolder.Path;

            ROMDatabase db = ROMDatabase.Current;

            var indicator = SystemTray.GetProgressIndicator(this);

            indicator.IsIndeterminate = true;
            indicator.Text            = String.Format(AppResources.DownloadingProgressText, item.Name);

            LiveDownloadOperationResult e = await client.DownloadAsync(item.SkyDriveID + "/content");

            if (e != null)
            {
                byte[]      tmpBuf          = new byte[e.Stream.Length];
                StorageFile destinationFile = null;

                ROMDBEntry entry = null;

                if (item.Type == SkyDriveItemType.SRAM)
                {
                    entry = db.GetROMFromSRAMName(item.Name);
                    if (entry != null)
                    {
                        destinationFile = await saveFolder.CreateFileAsync(Path.GetFileNameWithoutExtension(entry.FileName) + ".sav", CreationCollisionOption.ReplaceExisting);
                    }

                    else
                    {
                        destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);
                    }
                }
                else if (item.Type == SkyDriveItemType.Savestate)
                {
                    entry = db.GetROMFromSavestateName(item.Name);


                    if (entry != null)
                    {
                        destinationFile = await saveFolder.CreateFileAsync(Path.GetFileNameWithoutExtension(entry.FileName) + item.Name.Substring(item.Name.Length - 5), CreationCollisionOption.ReplaceExisting);
                    }
                    else
                    {
                        destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);
                    }
                }

                using (IRandomAccessStream destStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
                    using (DataWriter writer = new DataWriter(destStream))
                    {
                        while (e.Stream.Read(tmpBuf, 0, tmpBuf.Length) != 0)
                        {
                            writer.WriteBytes(tmpBuf);
                        }
                        await writer.StoreAsync();

                        await writer.FlushAsync();

                        writer.DetachStream();
                    }
                e.Stream.Close();
                item.Downloading = false;

                if (item.Type == SkyDriveItemType.Savestate)
                {
                    String number = item.Name.Substring(item.Name.Length - 5, 1);
                    int    slot   = int.Parse(number);

                    if (entry != null) //NULL = do nothing
                    {
                        SavestateEntry saveentry = db.SavestateEntryExisting(entry.FileName, slot);
                        if (saveentry != null)
                        {
                            //delete entry
                            db.RemoveSavestateFromDB(saveentry);
                        }
                        SavestateEntry ssEntry = new SavestateEntry()
                        {
                            ROM      = entry,
                            Savetime = DateTime.Now,
                            Slot     = slot,
                            FileName = item.Name
                        };
                        db.Add(ssEntry);
                        db.CommitChanges();
                    }
                }

                MessageBox.Show(String.Format(AppResources.DownloadCompleteText, item.Name));
            }
            else
            {
                MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, "Api error"), AppResources.ErrorCaption, MessageBoxButton.OK);
            }

#if GBC
            indicator.Text = AppResources.ApplicationTitle2;
#else
            indicator.Text = AppResources.ApplicationTitle;
#endif
            indicator.IsIndeterminate = false;
        }
Ejemplo n.º 33
0
        private async Task DownloadFile(SkyDriveListItem item, LiveConnectClient client)
        {
            StorageFolder folder    = ApplicationData.Current.LocalFolder;
            StorageFolder romFolder = await folder.CreateFolderAsync(FileHandler.ROM_DIRECTORY, CreationCollisionOption.OpenIfExists);

            StorageFolder saveFolder = await romFolder.CreateFolderAsync(FileHandler.SAVE_DIRECTORY, CreationCollisionOption.OpenIfExists);

            String path     = romFolder.Path;
            String savePath = saveFolder.Path;

            ROMDatabase db        = ROMDatabase.Current;
            var         indicator = new ProgressIndicator()
            {
                IsIndeterminate = true,
                IsVisible       = true,
                Text            = String.Format(AppResources.DownloadingProgressText, item.Name)
            };

            SystemTray.SetProgressIndicator(this, indicator);

            LiveDownloadOperationResult e = await client.DownloadAsync(item.SkyDriveID + "/content");

            if (e != null)
            {
                byte[]      tmpBuf          = new byte[e.Stream.Length];
                StorageFile destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream destStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
                    using (DataWriter writer = new DataWriter(destStream))
                    {
                        while (e.Stream.Read(tmpBuf, 0, tmpBuf.Length) != 0)
                        {
                            writer.WriteBytes(tmpBuf);
                        }
                        await writer.StoreAsync();

                        await writer.FlushAsync();

                        writer.DetachStream();
                    }
                e.Stream.Close();
                item.Downloading = false;
                SystemTray.GetProgressIndicator(this).IsVisible = false;

                if (item.Type == SkyDriveItemType.Savestate)
                {
                    if (!db.SavestateEntryExisting(item.Name))
                    {
                        String     number = item.Name.Substring(item.Name.Length - 5, 1);
                        int        slot   = int.Parse(number);
                        ROMDBEntry entry  = db.GetROMFromSavestateName(item.Name);
                        // Null = No ROM existing for this file -> skip inserting into database. The file will be inserted when the corresponding ROM is downloaded.
                        if (entry != null)
                        {
                            SavestateEntry ssEntry = new SavestateEntry()
                            {
                                ROM      = entry,
                                Savetime = DateTime.Now,
                                Slot     = slot,
                                FileName = item.Name
                            };
                            db.Add(ssEntry);
                            db.CommitChanges();
                        }
                    }
                }

                MessageBox.Show(String.Format(AppResources.DownloadCompleteText, item.Name));
            }
            else
            {
                SystemTray.GetProgressIndicator(this).IsVisible = false;
                MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, "Api error"), AppResources.ErrorCaption, MessageBoxButton.OK);
            }
        }
 /// <summary>
 /// Calls the OperationCompletedCallback with the given result.
 /// This should be called when the TailoredDownloadOperation is completed.
 /// </summary>
 protected void OnOperationCompleted(LiveDownloadOperationResult result)
 {
     Action<LiveDownloadOperationResult> callback = this.OperationCompletedCallback;
     if (callback != null)
     {
         callback(result);
     }
 }