Beispiel #1
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;
        }
        async void skydriveList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SkyDriveListItem item = this.skydriveList.SelectedItem as SkyDriveListItem;

            if (item == null)
            {
                return;
            }

            try
            {
                LiveConnectClient client = new LiveConnectClient(this.session);
                if (item.Type == SkyDriveItemType.Folder)
                {
                    if (this.session != null)
                    {
                        this.skydriveList.ItemsSource = null;
                        this.currentFolderBox.Text    = item.Name;
                        LiveOperationResult result = await client.GetAsync(item.SkyDriveID + "/files");

                        this.client_GetCompleted(result);
                    }
                }
                else if (item.Type == SkyDriveItemType.ROM)
                {
                    // Download
                    if (!item.Downloading)
                    {
                        try
                        {
                            this.downloadsInProgress++;
                            item.Downloading = true;
                            await this.DownloadFile(item, client);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK);
                        }
                        finally
                        {
                            this.downloadsInProgress--;
                        }
                    }
                    else
                    {
                        MessageBox.Show(AppResources.AlreadyDownloadingText, AppResources.ErrorCaption, MessageBoxButton.OK);
                    }
                }
                this.statusLabel.Height = 0;
            }
            catch (LiveConnectException)
            {
                this.statusLabel.Height = this.labelHeight;
                this.statusLabel.Text   = AppResources.SkyDriveInternetLost;
            }
        }
Beispiel #3
0
        async void skydriveList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SkyDriveListItem item = this.skydriveList.SelectedItem as SkyDriveListItem;

            if (item == null)
            {
                return;
            }

            ROMDatabase db = ROMDatabase.Current;


            try
            {
                LiveConnectClient client = new LiveConnectClient(this.session);
                if (item.Type == SkyDriveItemType.Folder)
                {
                    if (this.session != null)
                    {
                        this.skydriveList.ItemsSource = null;
                        this.currentFolderBox.Text    = item.Name;
                        LiveOperationResult result = await client.GetAsync(item.SkyDriveID + "/files");

                        this.client_GetCompleted(result);
                    }
                }

                else if (item.Type == SkyDriveItemType.Zip || item.Type == SkyDriveItemType.Rar || item.Type == SkyDriveItemType.SevenZip)
                {
                    if (this.session != null)
                    {
                        this.skydriveList.ItemsSource = null;
                        this.currentFolderBox.Text    = item.Name;
                        this.downloadsInProgress++;

                        await this.DownloadFile(item, client);

                        try
                        {
                            List <SkyDriveListItem> listItems;

                            listItems = this.GetFilesInArchive(item);

                            this.skydriveStack.Add(listItems);
                            this.skydriveList.ItemsSource = listItems;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, AppResources.ErrorCaption, MessageBoxButton.OK);
                        }

                        this.downloadsInProgress--;
                    }
                }

                else if (item.Type == SkyDriveItemType.ROM)
                {
                    // Download
                    if (!item.Downloading)
                    {
                        this.downloadsInProgress++;
                        if (item.Stream == null)
                        {
                            await this.DownloadFile(item, client);
                        }


                        await ImportROM(item, this);

                        this.downloadsInProgress--;
                    }
                    else
                    {
                        MessageBox.Show(AppResources.AlreadyDownloadingText, AppResources.ErrorCaption, MessageBoxButton.OK);
                    }
                }
                else if (item.Type == SkyDriveItemType.Savestate || item.Type == SkyDriveItemType.SRAM)
                {
                    //check to make sure there is a rom with matching name
                    ROMDBEntry entry = null;

                    if (item.Type == SkyDriveItemType.Savestate)
                    {
                        entry = db.GetROMFromSavestateName(item.Name);
                    }
                    else if (item.Type == SkyDriveItemType.SRAM)
                    {
                        entry = db.GetROMFromSRAMName(item.Name);
                    }

                    if (entry == null) //no matching file name
                    {
                        MessageBox.Show(AppResources.NoMatchingNameText, AppResources.ErrorCaption, MessageBoxButton.OK);
                        return;
                    }

                    //determine the slot number
                    if (item.Type == SkyDriveItemType.Savestate)
                    {
                        string slot       = item.Name.Substring(item.Name.Length - 1, 1);
                        int    parsedSlot = 0;
                        if (!int.TryParse(slot, out parsedSlot))
                        {
                            MessageBox.Show(AppResources.ImportSavestateInvalidFormat, AppResources.ErrorCaption, MessageBoxButton.OK);
                            return;
                        }
                    }
                    // Download
                    if (!item.Downloading)
                    {
                        this.downloadsInProgress++;

                        if (item.Stream == null)
                        {
                            await this.DownloadFile(item, client);
                        }

                        await ImportSave(item, this);

                        this.downloadsInProgress--;
                    }
                    else
                    {
                        MessageBox.Show(AppResources.AlreadyDownloadingText, AppResources.ErrorCaption, MessageBoxButton.OK);
                    }
                }


                this.statusLabel.Height = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, AppResources.ErrorCaption, MessageBoxButton.OK);
            }
        }
Beispiel #4
0
        void client_GetCompleted(LiveOperationResult e)
        {
            if (e != null)
            {
                List <object> list = e.Result["data"] as List <object>;

                if (list == null)
                {
                    return;
                }
                List <SkyDriveListItem> listItems = new List <SkyDriveListItem>();
                foreach (var item in list)
                {
                    IDictionary <string, object> dict = item as IDictionary <string, object>;
                    if (dict == null)
                    {
                        continue;
                    }

                    if (this.skydriveStack.Count == 1)
                    {
                        this.skydriveStack.Last()[0].SkyDriveID = dict["parent_id"].ToString();
                    }

                    String           name = dict["name"].ToString();
                    SkyDriveItemType type;
                    if (dict["type"].Equals("folder") || dict["type"].Equals("album"))
                    {
                        type = SkyDriveItemType.Folder;
                    }
                    else
                    {
                        type = SkyDriveItemType.File;
                        int dotIndex = -1;
                        if ((dotIndex = name.LastIndexOf('.')) != -1)
                        {
                            String substrName = name.Substring(dotIndex).ToLower();

                            type = GetSkyDriveItemType(substrName);
                        }
                    }

                    if (type == SkyDriveItemType.File)
                    {
                        continue;
                    }

                    SkyDriveListItem listItem = new SkyDriveListItem()
                    {
                        Name       = dict["name"].ToString(),
                        SkyDriveID = dict["id"].ToString(),
                        Type       = type,
                        ParentID   = dict["parent_id"].ToString()
                    };
                    if (type == SkyDriveItemType.Folder)
                    {
                        int count = 0;
                        int.TryParse(dict["count"].ToString(), out count);
                        listItem.FolderChildrenCount = count;
                    }

                    listItems.Add(listItem);
                }
                this.skydriveStack.Add(listItems);
                this.skydriveList.ItemsSource = listItems;
            }
            else
            {
                MessageBox.Show(String.Format(AppResources.SkyDriveGeneralError, "Api Error"), AppResources.ErrorCaption, MessageBoxButton.OK);
            }
        }
Beispiel #5
0
        private List <SkyDriveListItem> GetFilesInArchive(SkyDriveListItem item)
        {
            List <SkyDriveListItem> listItems = new List <SkyDriveListItem>();

            if (item.Stream != null)
            {
                //get list of file
                IArchive archive = null;

                if (item.Type == SkyDriveItemType.Rar)
                {
                    archive = SharpCompress.Archive.Rar.RarArchive.Open(item.Stream);
                }
                else if (item.Type == SkyDriveItemType.Zip)
                {
                    archive = SharpCompress.Archive.Zip.ZipArchive.Open(item.Stream);
                }
                else if (item.Type == SkyDriveItemType.SevenZip)
                {
                    archive = SharpCompress.Archive.SevenZip.SevenZipArchive.Open(item.Stream);
                }

                foreach (var entry in archive.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        Stream data = new MemoryStream();
                        entry.WriteTo(data);
                        data.Position = 0;
                        String name = entry.FilePath;

                        SkyDriveItemType type = SkyDriveItemType.File;
                        int dotIndex          = -1;
                        if ((dotIndex = name.LastIndexOf('.')) != -1)
                        {
                            String substrName = name.Substring(dotIndex).ToLower();
                            type = GetSkyDriveItemType(substrName);
                        }

                        if (type == SkyDriveItemType.File)
                        {
                            data.Close();
                            continue;
                        }

                        SkyDriveListItem listItem = new SkyDriveListItem()
                        {
                            Name       = name,
                            SkyDriveID = "",
                            Type       = type,
                            ParentID   = item.SkyDriveID,
                            Stream     = data
                        };

                        listItems.Add(listItem);
                    }
                }

                //close the zip stream since we have the stream of each item inside it already
                item.Stream.Close();
                item.Stream = null;
            }

            return(listItems);
        }
        void client_GetCompleted(LiveOperationResult e)
        {
            if (e != null)
            {
                List<object> list = e.Result["data"] as List<object>;

                if (list == null)
                {
                    return;
                }
                List<SkyDriveListItem> listItems = new List<SkyDriveListItem>();
                foreach (var item in list)
                {
                    
                    IDictionary<string, object> dict = item as IDictionary<string, object>;
                    if (dict == null)
                    {
                        continue;
                    }

                    if (this.skydriveStack.Count == 1)
                    {
                        this.skydriveStack.Last()[0].SkyDriveID = dict["parent_id"].ToString();
                    }

                    String name = dict["name"].ToString();
                    SkyDriveItemType type;
                    if (dict["type"].Equals("folder") || dict["type"].Equals("album"))
                    {
                        type = SkyDriveItemType.Folder;
                    }
                    else
                    {
                        type = SkyDriveItemType.File;
                        int dotIndex = -1;
                        if ((dotIndex = name.LastIndexOf('.')) != -1)
                        {
                            String substrName = name.Substring(dotIndex).ToLower();
#if GBC
                            if (substrName.Equals(".gb") || substrName.Equals(".gbc"))
#else
                            if (substrName.Equals(".gba"))
#endif
                            {
                                type = SkyDriveItemType.ROM;
                            }
                        }
                    }

                    if (type == SkyDriveItemType.File)
                    {
                        continue;
                    }

                    SkyDriveListItem listItem = new SkyDriveListItem()
                    {
                        Name = dict["name"].ToString(),
                        SkyDriveID = dict["id"].ToString(),
                        Type = type,
                        ParentID = dict["parent_id"].ToString()
                    };
                    if (type == SkyDriveItemType.Folder)
                    {
                        int count = 0;
                        int.TryParse(dict["count"].ToString(), out count);
                        listItem.FolderChildrenCount = count;
                    }

                    listItems.Add(listItem);
                }
                this.skydriveStack.Add(listItems);
                this.skydriveList.ItemsSource = listItems;
            }
            else
            {
                MessageBox.Show(String.Format(AppResources.SkyDriveGeneralError, "Api Error"), AppResources.ErrorCaption, MessageBoxButton.OK);
            }
        }
        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);
            }
        }
Beispiel #8
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 - 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);
            }
        }
Beispiel #9
0
        async void skydriveList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SkyDriveListItem item = this.skydriveList.SelectedItem as SkyDriveListItem;

            if (item == null)
            {
                return;
            }

            try
            {
                LiveConnectClient client = new LiveConnectClient(this.session);
                if (item.Type == SkyDriveItemType.Folder)
                {
                    if (this.session != null)
                    {
                        this.skydriveList.ItemsSource = null;
                        this.currentFolderBox.Text    = item.Name;
                        LiveOperationResult result = await client.GetAsync(item.SkyDriveID + "/files");

                        this.client_GetCompleted(result);
                    }
                }
                else if (item.Type == SkyDriveItemType.Savestate || item.Type == SkyDriveItemType.SRAM)
                {
                    //check to make sure there is a rom with matching name
                    ROMDatabase db    = ROMDatabase.Current;
                    ROMDBEntry  entry = null;

                    if (item.Type == SkyDriveItemType.Savestate)
                    {
                        entry = db.GetROMFromSavestateName(item.Name);
                    }
                    else if (item.Type == SkyDriveItemType.SRAM)
                    {
                        entry = db.GetROMFromSRAMName(item.Name);
                    }

                    if (entry == null) //no matching file name
                    {
                        MessageBox.Show(AppResources.NoMatchingNameText, AppResources.ErrorCaption, MessageBoxButton.OK);
                        return;
                    }

                    //check to make sure format is right
                    if (item.Type == SkyDriveItemType.Savestate)
                    {
                        string slot       = item.Name.Substring(item.Name.Length - 5, 1);
                        int    parsedSlot = 0;
                        if (!int.TryParse(slot, out parsedSlot))
                        {
                            MessageBox.Show(AppResources.ImportSavestateInvalidFormat, AppResources.ErrorCaption, MessageBoxButton.OK);
                            return;
                        }
                    }
                    // Download
                    if (!item.Downloading)
                    {
                        try
                        {
                            item.Downloading = true;
                            await this.DownloadFile(item, client);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK);
                        }
                    }
                    else
                    {
                        MessageBox.Show(AppResources.AlreadyDownloadingText, AppResources.ErrorCaption, MessageBoxButton.OK);
                    }
                }
                this.statusLabel.Height = 0;
            }
            catch (LiveConnectException)
            {
                this.statusLabel.Height = this.labelHeight;
                this.statusLabel.Text   = AppResources.SkyDriveInternetLost;
            }
        }
Beispiel #10
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;
        }
Beispiel #11
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);
            }
        }
        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);
            }
        }