Exemple #1
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("path"))
            {
                this.folderPath = NavigationContext.QueryString["path"];
            }
            if (this.NavigationContext.QueryString.ContainsKey("id"))
            {
                this.fileID = NavigationContext.QueryString["id"];
            }
            if (this.NavigationContext.QueryString.ContainsKey("filename"))
            {
                this.filename = this.NavigationContext.QueryString["filename"];
                this.filenameInput.Text = this.filename;
            }

            if (this.fileID != null)
            { // try to get file contents

                this.progressIndicator = new ProgressIndicator();
                this.progressIndicator.IsIndeterminate = true;
                this.progressIndicator.IsVisible = true;
                this.progressIndicator.Text = "Looking for rain...";
                SystemTray.SetProgressIndicator(this, this.progressIndicator);

                LiveConnectClient client = new LiveConnectClient(App.Current.LiveSession);
                client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnFileDownloadComplete);
                client.DownloadAsync(this.fileID+"/content");
            }
            else
            {
                this.contentInput.IsEnabled = true;
                this.filenameInput.Focus(); // doesn't work as it is here, maybe because page isn't actually loaded yet?
            }
        }
        /// <summary>
        ///     Download a file into a stream.
        /// </summary>
        /// <param name="client">the LiveConnectClient object this method is attached to.</param>
        /// <param name="path">relative or absolute uri to the file to be downloaded.</param>
        /// <param name="progress">a delegate that is called to report the download progress.</param>
        public static Task <Stream> Download(this LiveConnectClient client, string path, IProgress <LiveOperationProgress> progress)
        {
            client.DownloadCompleted       += OnDownloadOperationCompleted;
            client.DownloadProgressChanged += OnDownloadProgressChanged;
            var tcs = new TaskCompletionSource <Stream>();

            client.DownloadAsync(path, new OperationState <Stream>(tcs, client, ApiMethod.Download)
            {
                Progress = progress
            });

            return(tcs.Task);
        }
 private void downloadButton_Click(object sender, RoutedEventArgs e)
 {
     if (session == null)
     {
         MessageBox.Show("You must sign in first.");
     }
     else
     {
         LiveConnectClient client = new LiveConnectClient(session);
         client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
         client.DownloadAsync("file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/picture?type=thumbnail");
     }
 }
        private static 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;
        }
        internal void Download()
        {
            if (SelectedPhoto == null)
                return;

            LiveConnectClient downloadClient = new LiveConnectClient(App.Session);
            downloadClient.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(downloadClient_DownloadCompleted);
            downloadClient.DownloadAsync(SelectedPhoto.ID+"/content");
        }
                private async void DownloadLatestBackupFile()
                {
                        //
                        //

                        try
                        {
                                bBackup.IsEnabled = false;
                                bRestore.IsEnabled = false;
                                pbProgress.Value = 0;
                                var progressHandler = new Progress<LiveOperationProgress>(
                                        (e) =>
                                        {
                                                pbProgress.Value = e.ProgressPercentage;

                                                pbProgress.Visibility = Visibility.Visible;
                                                lblLastBackup.Text =
                                                        string.Format(
                                                                StringResources
                                                                        .BackupAndRestorePage_Messages_DwnlProgress,
                                                                e.BytesTransferred, e.TotalBytes);
                                        });
                                _ctsDownload = new CancellationTokenSource();
                                _client = new LiveConnectClient(App.LiveSession);
                                var reqList = BackgroundTransferService.Requests.ToList();
                                foreach (var request in reqList)
                                {
                                        if (request.DownloadLocation.Equals(new Uri(@"\shared\transfers\restore.zip", UriKind.Relative)))
                                                BackgroundTransferService.Remove(BackgroundTransferService.Find(request.RequestId));
                                }
                                var token = await _client.DownloadAsync(_newestFile+"/Content", _ctsDownload.Token, progressHandler);
                                
                                lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_Restoring;
                                RestoreFromFile(token.Stream);
                        }
                        catch (TaskCanceledException)
                        {
                                lblLastBackup.Text = "Download Cancelled.";
                        }
                        catch (LiveConnectException ee)
                        {
                                lblLastBackup.Text = string.Format("Error Downloading: {0}", ee.Message);
                        }
                        catch (Exception e)
                        {
                                lblLastBackup.Text = e.Message;
                        }
                        finally
                        {
                                bBackup.IsEnabled = true;
                                bRestore.IsEnabled = true;
                                pbProgress.Value = 0;
                                pbProgress.Visibility = Visibility.Collapsed;
                        }
                }
        private async Task DownloadFile(SkyDriveListItem item, LiveConnectClient client)
        {
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFolder romFolder = await folder.CreateFolderAsync("roms", CreationCollisionOption.OpenIfExists);

            String path = romFolder.Path;

            ROMDatabase db = ROMDatabase.Current;
            var romEntry = db.GetROM(item.Name);
            bool fileExisted = false;
            if (romEntry != null)
            {
                fileExisted = true;
                //MessageBox.Show(String.Format(AppResources.ROMAlreadyExistingError, item.Name), AppResources.ErrorCaption, MessageBoxButton.OK);
                //return;
            }

            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 romFolder.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 (!fileExisted)
                {
                    var entry = FileHandler.InsertNewDBEntry(destinationFile.Name);
                    await FileHandler.FindExistingSavestatesForNewROM(entry);
                    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);
            }
        }
        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 - 2);
                        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);
            }
        }
Exemple #9
0
        /// <summary>
        /// Gibt einen Isolated Storage Pfad zu einem Profilbild einer Person an.
        /// Bei Bedarf wird dieses erst von Server geladen.
        /// </summary>
        /// <param name="authenticationUserId">Nutzer dessen Profilbild geladen werden soll.</param>
        /// <returns></returns>
        internal static async Task<string> GetProfilePicture(string authenticationUserId)
        {
            if (authenticationUserId == null)
                return null;
            try
            {
                string fileName = authenticationUserId + ".png";
                using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (file.FileExists(fileName))
                    {
                        //Wenn die Datei weniger als einen Monat alt ist vewende sie.
                        if ((file.GetCreationTime(fileName).DateTime - DateTime.Now) < TimeSpan.FromDays(30))
                            return fileName;
                        else //Ansonsten löschen und neu downloaden, dadurch immer schön aktuell.
                            file.DeleteFile(fileName);
                    }

                    //LiveConnectClient bereitstellen
                    LiveConnectClient client = new LiveConnectClient(session);

                    //Pfad des Profilbildes von Windows Live abrufen.
                    var path = authenticationUserId + "/picture";

                    var task = client.DownloadAsync((string)(await client.GetAsync(path)).Result["location"]);
                    using (var fileStream = (await task).Stream)

                    //Filestream auf Platte abspeichern
                    {
                        using (FileStream fileStreamSave = file.CreateFile(fileName))
                        {
                            byte[] buffer = new byte[8 * 1024];
                            int length;

                            while ((length = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                                fileStreamSave.Write(buffer, 0, length);

                            fileStreamSave.Flush();
                        }
                    }

                    return fileName;
                }
            }
            catch (Exception e)
            {
                //Wenn Debugger vorhanden ist, Fehler beachten ansonsten Silent einfach ohne Profilbild arbeiten.
                if (System.Diagnostics.Debugger.IsAttached)
                    throw new Exception("Could not load profile picture.", e);
                else
                    return null;
            }
        }
        /// <summary>
        /// Download the selected file to local storage
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        private async void DownloadFile(string path, string fileName)
        {
            try
            {
                //Get a reference to the list item
                OneDriveObject lstItem = new OneDriveObject();

                switch(ringtonePanorama.SelectedIndex)
                {
                    case MyFiles:
                        lstItem = (OneDriveObject)lstMyFiles.SelectedItem;
                        break;
                    case SharedFiles:
                        lstItem = (OneDriveObject)lstSharedFiles.SelectedItem;
                        break;
                }
                
                Progress<LiveOperationProgress> downloadProgress = new Progress<LiveOperationProgress>(
                    (p) =>
                    {
                        if (lstItem != null)
                        {
                            lstItem.DownloadProgress = p.ProgressPercentage;
                        }
                    });

                //Fetch the file from the user's One Drive account
                LiveConnectClient downloadClient = new LiveConnectClient(Session.CurSession);
                LiveDownloadOperationResult downloadResult = await downloadClient.DownloadAsync(
                        string.Concat(path, "/content"), CancellationToken.None, downloadProgress );
                
                //Move the file to the apps local storage
                Stream fileStream = downloadResult.Stream;
                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream fileToSave = storage.OpenFile(fileName, FileMode.Create, FileAccess.ReadWrite))
                    {
                        fileStream.CopyTo(fileToSave);
                        fileStream.Flush();
                        fileStream.Close();                      
                    }                   

                    using (Stream isoStream = storage.OpenFile(fileName, FileMode.Open))
                    {
                        mediaPlayer.SetSource(isoStream);
                    }
                }

                //Clear the download progress
                lstItem.DownloadProgress = 0;

                //Enable the save and share buttons
                appBarSaveButton.IsEnabled = true;
                appBarShareButton.IsEnabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }