Exemple #1
0
        public async static Task <string> DownloadFileAsync(this LiveConnectClient client, string directory, string fileName)
        {
            string skyDriveFolder = await OneDriveHelper.CreateOrGetDirectoryAsync(client, directory, "me/skydrive");

            var result = await client.DownloadAsync(skyDriveFolder);

            var operation = await client.GetAsync(skyDriveFolder + "/files");

            var    items = operation.Result["data"] as List <object>;
            string id    = string.Empty;

            // Search for the file - add handling here if File Not Found
            foreach (object item in items)
            {
                IDictionary <string, object> file = item as IDictionary <string, object>;
                if (file["name"].ToString() == fileName)
                {
                    id = file["id"].ToString();
                    break;
                }
            }

            var downloadResult = await client.DownloadAsync(string.Format("{0}/content", id));

            var    reader = new StreamReader(downloadResult.Stream);
            string text   = await reader.ReadToEndAsync();

            return(text);
        }
        public async Task <Stream> GetFile(string id, CancellationToken?ct = null)
        {
            LiveDownloadOperationResult res;

            if (ct != null)
            {
                res = await _liveConnectClient.DownloadAsync(id + "/content", ct.Value, null);
            }
            else
            {
                res = await _liveConnectClient.DownloadAsync(id + "/content");
            }

            return(res.Stream);
        }
Exemple #3
0
        public void Start(IEnumerable <object> files)
        {
            var loadedItems = new List <ListItem>(10);
            var forDelete   = new List <ListItem>(10);

            foreach (IDictionary <string, object> content in files)
            {
                var filename = (string)content["name"];
                if (!filename.EndsWith(".txt"))
                {
                    continue;
                }
                string   name       = filename.Substring(0, filename.Length - 4);
                ListItem newGroup   = _cache.FindItem(name);
                DateTime updateTime = Convert.ToDateTime(content["updated_time"]);
                if (newGroup != null)
                {
                    //проверим время модификации

                    if (newGroup.ModifyTime < updateTime)
                    {
                        _downloadCounter++;
                        _client.DownloadAsync(String.Format("{0}/content", (string)content["id"]), newGroup);
                    }
                }
                else
                {
                    newGroup = new ListItem {
                        Name = name, ModifyTime = updateTime
                    };
                    _cache.Items.Add(newGroup);
                    _downloadCounter++;
                    _client.DownloadAsync(String.Format("{0}/content", (string)content["id"]), newGroup);
                }

                loadedItems.Add(newGroup);
            }

            forDelete.AddRange(_cache.Items.Where(item => !loadedItems.Contains(item) && item.ModifyTime <= item.LastSyncTime));

            foreach (var item in forDelete)
            {
                _cache.Delete(item);
            }

            _downloadCounter++;
            ClientDownloadCompleted(this, new LiveDownloadCompletedEventArgs(null, null));
        }
Exemple #4
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;
        }
Exemple #5
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);
        }
Exemple #6
0
        private void BeginDownloadFile(OneDriveFile file)
        {
            // Sync Step 3: We're scheduling some files to be downloaded.

            // Adds the file id to the list of currently downloading files.
            lock (_syncRoot)
            {
                _dlFiles.Add(file);
            }

            // Starts downloading the cartridge to the isostore.
            bool shouldDirectDownload = !IsBackgroundDownloadAllowed;

            Log(file.ToString() + ", directDownload = " + shouldDirectDownload);
            string fileAttribute = file.Id + "/content";

            if (shouldDirectDownload)
            {
                // Direct download.
                Log("Starts DownloadAsync");
                StartTaskAndContinueWith(
                    () => _liveClient.DownloadAsync(fileAttribute),
                    t => OnLiveClientDownloadCompleted(t, file));
            }
            else
            {
                try
                {
                    // Tries to perform a background download.
                    Log("Starts BackgroundDownloadAsync");
                    StartTaskAndContinueWith(
                        () => _liveClient.BackgroundDownloadAsync(
                            fileAttribute,
                            new Uri(GetTempIsoStorePath(file.Name), UriKind.RelativeOrAbsolute)
                            ),
                        t => OnLiveClientBackgroundDownloadCompleted(t, file));
                }
                catch (Exception)
                {
                    // Tries the direct download method.
                    Log("Starts DownloadAsync (fallback)");
                    StartTaskAndContinueWith(
                        () => _liveClient.DownloadAsync(fileAttribute),
                        t => OnLiveClientDownloadCompleted(t, file));
                }
            }
        }
        private void ApplicationBarMenuItem_Click_2(object sender, EventArgs e)
        {
            // Download the zip

            // Connect to live API
            LiveAuthClient auth = new LiveAuthClient("00000000440E7119");

            auth.InitializeAsync();
            auth.InitializeCompleted += (e1, e2) =>
            {
                // Show login dialog
                auth.LoginAsync(new string[] { "wl.skydrive_update", "wl.skydrive" });

                auth.LoginCompleted += (e3, e4) =>
                {
                    if (e4.Status == LiveConnectSessionStatus.Connected)
                    {
                        LiveConnectClient client = new LiveConnectClient(e4.Session);

                        // Upload that zip we just made
                        client.GetAsync("me/skydrive/files");
                        client.GetCompleted += (getSender, getEvents) =>
                        {
                            Dictionary <string, object> fileData = (Dictionary <string, object>)getEvents.Result;
                            List <object> files = (List <object>)fileData["data"];

                            foreach (object item in files)
                            {
                                Dictionary <string, object> file = (Dictionary <string, object>)item;
                                if (file["name"].ToString() == "wphfolders.zip")
                                {
                                    System.Diagnostics.Debug.WriteLine(file["name"]);
                                    client.DownloadAsync(file["id"].ToString() + "/content");
                                    client.DownloadCompleted += (downloadSender, downloadEventArgs) =>
                                    {
                                        SharpGIS.UnZipper unzipper = new SharpGIS.UnZipper(downloadEventArgs.Result);
                                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            foreach (string name in unzipper.FileNamesInZip)
                                            {
                                                var storefile = store.OpenFile(name, FileMode.Create, FileAccess.Write);
                                                unzipper.GetFileStream(name).CopyTo(storefile);
                                                storefile.Close();
                                            }
                                        }
                                        MessageBox.Show("Restored.");
                                        regenerateList();
                                    };
                                }
                            }
                        };
                    }
                    else
                    {
                        MessageBox.Show("Not connected to SkyDrive");
                    }
                };
            };
        }
        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;
            }
        }
Exemple #9
0
        internal void OpenSelectedFileCommand()
        {
            if (_selectedWalletFile == null)
            {
                return;
            }

            IsProgressing = true;
            _clientFolder.DownloadAsync(_selectedWalletFile.FileId + "/content");
        }
Exemple #10
0
 private void Folder_Download_Click(object sender, EventArgs e)
 {
     if (client == null)
     {
         MessageBox.Show("Veuillez vous connecter !");
     }
     else
     {
         if (MessageBox.Show("Voulez-vous vraiment télécharger tous les fichiers ?", "Attention !", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
         {
             if (wait_async == false)
             {
                 progress_multiple = true;
                 Progress_Init();
                 wait_async = true;
                 int loop_count = 0;
                 client.DownloadCompleted += new EventHandler <LiveDownloadCompletedEventArgs>(Folder_Download_Completed);
                 foreach (object entry in list_files_skydrive)
                 {
                     if (My_Isolated_Storage.FileExists("GPX\\" + list_files_skydrive.ElementAt(loop_count).Name.ToString()) == false)
                     {
                         progress_list.Add(0);
                         client.DownloadAsync(list_files_skydrive.ElementAt(loop_count).Id + "/content", loop_count);
                     }
                     else
                     {
                         progress_list.Add(100);
                     }
                     loop_count = loop_count + 1;
                 }
                 if (progress_list.Average() == 100)
                 {
                     wait_async = false;
                     client.DownloadCompleted -= Folder_Download_Completed;
                     SystemTray.ProgressIndicator.IsVisible = false;
                     //MessageBox.Show("Tous les fichiers sont déjà téléchargés.");
                 }
             }
         }
     }
 }
Exemple #11
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);
        }
Exemple #12
0
        public async static Task <string> DownloadAsync(string folderId, string fileName)
        {
            try
            {
                string fileId = await GetFileIdAsync(folderId, fileName);

                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);
        }
Exemple #13
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;
            }
        }
Exemple #14
0
        private void download(Note selected)
        {
            if (selected.FileID != null)
            {
                itemname = selected.Name;
                client.DownloadAsync(selected.FileID + "/content");
            }

            else
            {
                MessageBox.Show("该文件不存在", "Error", MessageBoxButton.OK);
            }
        }
        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");
        }
 /// <summary>
 /// http://msdn.microsoft.com/en-us/live/hh561740.aspx#downloading_files
 /// The wl.skydrive scope is required.
 /// </summary>
 public void DownloadFile()
 {
     if (session == null)
     {
         Debug.WriteLine("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");
         client.DownloadAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!137/content");
     }
 }
        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();
            }
        }
        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);
        }
Exemple #19
0
 private void Signin_Get_Session(object sender, LiveConnectSessionChangedEventArgs e)
 {
     if (e.Status == LiveConnectSessionStatus.Connected)
     {
         session = e.Session;
         client  = new LiveConnectClient(session);
         textBlockStatus.Text = "Informations...";
         client.GetCompleted += Signin_Get_Infos;
         client.GetAsync("me", null);
         client.DownloadCompleted += new EventHandler <LiveDownloadCompletedEventArgs>(Signin_Get_Picture);
         client.DownloadAsync("me/picture");
     }
     else
     {
         textBlockStatus.Text           = "Déconnecté";
         ListBox_SkyContent.ItemsSource = "";
         client             = null;
         session            = null;
         sky_base_folder_id = null;
     }
 }
        private void PerformCloudToDeviceSync(LiveConnectSession session, string syncFilename, string syncInternalFilename, Action <BookmarkserviceImportCompletedEventArgs> completedAction, BookmarkserviceImportCompletedEventArgs completedEventArgs)
        {
            //get cloud bookmarks
            LiveConnectClient downloadClient = new LiveConnectClient(session);

            downloadClient.DownloadCompleted += delegate(object sender, LiveDownloadCompletedEventArgs d)
            {
                HashSet <Bookmark> externalBookmarks = new HashSet <Bookmark>();

                if (d.Error == null)
                {
                    string fileContents;
                    //parse downloaded file
                    using (StreamReader reader = new StreamReader(d.Result))
                        fileContents = reader.ReadToEnd();

                    ParseHtml(fileContents, true, externalBookmarks, completedEventArgs);
                }

                List <Bookmark>        deviceBookmarks        = RetrieveDeviceBookmarks();
                IEnumerable <Bookmark> deviceBookmarksRemoved = externalBookmarks.Except(externalBookmarks, new UrlComparer <Bookmark>());

                //remove items that have been removed since
                foreach (Bookmark bookmark in deviceBookmarksRemoved)
                {
                    DeleteDeviceBookmark(bookmark.Title);
                }

                //add the newly discovered bookmarks to the device
                foreach (Bookmark bookmark in externalBookmarks)
                {
                    CreateOrUpdateDeviceBookmark(bookmark.Title, bookmark);
                }

                completedEventArgs.StatusCode = ImportStatusCode.Success;
                completedAction(completedEventArgs);
            };

            downloadClient.DownloadAsync(string.Concat(syncInternalFilename, "/content"));
        }
        protected override IEnumerable <SynchProgress> UploadPhotos(List <ODItem> fileList)
        {
            TotalFileCount = fileList.Count;

            Index = 1;
            foreach (var file in fileList)
            {
                if (file.Name.ToLower().EndsWith("jpg"))
                {
                    var fileContent = Client.DownloadAsync("drive/items/" + file.Id + "/content").Result;
                    var photo       = UploadPhoto(fileContent.Stream, new List <ODItem>()
                    {
                        file
                    });
                    yield return(new SynchProgress()
                    {
                        Photo = photo, Index = Index, TotalFileCount = TotalFileCount
                    });

                    Index++;
                }
            }
        }
        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);
            }
        }
Exemple #23
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);
                }
            }
        }
        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;
        }
Exemple #25
0
        private static void DownloadFileHelper(object sender, LiveOperationCompletedEventArgs e)
        {
            string clientDirectory = "C:\\UltiDrive\\";

            indexEntities db = new indexEntities();
            string guidToDownload = (string)guidToDownloadQueue.Dequeue();
            var request = from f in db.files
                          where f.guid == guidToDownload
                          select f.origFileName;

            string originalPath = request.First().ToString();

            string originalFileName = originalPath.Split('\\').Last();

            try
            {
                JavaScriptSerializer ser = new JavaScriptSerializer();
                Files.RootObject data = ser.Deserialize<Files.RootObject>(e.RawResult);

                foreach (Files.Datum listItem in data.data)
                {
                    if (listItem.name == guidToDownload)
                    {
                        LiveConnectClient client = new LiveConnectClient(Properties.session);

                        client.DownloadCompleted += UltiDrive.SkyDrive.Utilities.ConnectClient_DownloadCompleted;
                        string path = clientDirectory + originalFileName;
                        client.DownloadAsync(listItem.id + "/content", path);
                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("SkyDriveApi.DownloadFile() failed. --> " + ex.ToString());
            }
        }
Exemple #26
0
        public async Task <bool> DownloadSynchronizationAsync(List <Interfaces.FileInformation> fileInfo, object DriveServiceClient)
        {
            try
            {
                Interfaces.FileInformation[] fileArr = fileInfo.ToArray();
                LiveConnectClient            client  = DriveServiceClient as LiveConnectClient;

                foreach (var item in fileArr)
                {
                    if (!item.isFile)
                    {
                        switch (item.Mode)
                        {
                        case "cr":
                            break;

                        case "ch":
                            break;

                        case "re":
                            break;

                        case "de":
                            break;
                        }
                    }
                }


                foreach (var item in fileArr)
                {
                    switch (item.Mode)
                    {
                    case "ch":     //database entries
                        if (item.isFile)
                        {
                            using (FileStream stream = new FileStream(item.Path + item.FileName, FileMode.Open))
                            {
                                if (stream != null)
                                {
                                    LiveDownloadOperationResult result = await client.DownloadAsync(String.Format("{0}/content", item.FileID));

                                    await result.Stream.CopyToAsync(stream);
                                }
                            }
                        }


                        break;

                    case "cr":     //database entries
                        if (item.isFile)
                        {
                            //using (FileStream stream = new FileStream(item.Path + item.FileName, FileMode.Open))
                            //{
                            //    if (stream != null)
                            //    {
                            //        await client.UploadAsync(item.Path + "\\" + item.FileName, item.FileName, stream, OverwriteOption.Overwrite);
                            //    }
                            //}
                            FileStream stream = null;
                            if ((stream = new FileStream(item.Path + @"\" + item.FileName, FileMode.Create)) == null)
                            {
                                throw new Exception("Unable to open the file selected to upload.");
                            }


                            //to download the file we need to use the id + "/content"
                            LiveDownloadOperationResult result = await client.DownloadAsync(string.Format("{0}/content", item.FileID));

                            await result.Stream.CopyToAsync(stream);
                        }

                        break;

                    case "de":     //database entries
                        //await client.DeleteAsync(item.FileID);
                        break;

                    case "re":     //database entries
                        if (item.isFile)
                        {
                            using (FileStream stream = new FileStream(item.Path + item.FileName, FileMode.Open))
                            {
                                if (stream != null)
                                {
                                    await client.UploadAsync(item.Path + "\\" + item.FileName, item.FileName, stream, OverwriteOption.Overwrite);
                                }
                            }
                        }

                        break;
                    }
                }
            }
            catch (Exception) { }

            //return TaskEx.FromResult(false);

            return(false);
        }
Exemple #27
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);
            }
        }
Exemple #28
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;
        }