none
[UWP] Download Bundle File into a folder inside another folder - C#

    Question

  • I made an application to download files into a folder inside another folder.

    The name for the folder obtained from DataFile name from database and match the name of the image that has been downloaded.

    I'm having a problem, that when downloading to a folder for the first bundle of data is fine, but at the time of downloading the data bundle again the previous folder and the new folder also download both files.

    When downloading the files that differ it will create a new folder again and the two previous folders are also downloaded the file. For more details, can see in the image below:

    folder

    folders

    And should one folder contains two files.

    JSON: 

    JSON

    RHData Class:

    PrimaryKey]
            public string SKU { get; set; }
    
            public string Judul { get; set; }
            public string Tipe { get; set; }
            public string Harga { get; set; }
            public string Gratis { get; set; }
            public string DataFile { get; set; }

    RHViewModel class:

    class RHViewModel
        {
            private string sku = string.Empty;
    
            public string SKU
            {
                get { return sku; }
                set
                {
                    if (sku == value)
                        return;
                    sku = value;
                    RaisePropertyChanged("SKU");
                }
            }
    
            private string judul = string.Empty;
    
            public string Judul
            {
                get { return judul; }
                set
                {
                    if (judul == value)
                        return;
                    judul = value;
                    RaisePropertyChanged("Judul");
                }
            }
    
            private string tipe = string.Empty;
    
            public string Tipe
            {
                get { return tipe; }
                set
                {
                    if (tipe == value)
                        return;
                    tipe = value;
                    RaisePropertyChanged("Tipe");
                }
            }
    
            private string harga = string.Empty;
    
            public string Harga
            {
                get { return harga; }
                set
                {
                    if (harga == value)
                        return;
                    harga = value;
                    RaisePropertyChanged("Harga");
                }
            }
    
            private string cover = string.Empty;
    
            private string gratis = string.Empty;
    
            public string Gratis
            {
                get { return gratis; }
                set
                {
                    if (gratis == value)
                        return;
                    gratis = value;
                    RaisePropertyChanged("Gratis");
                }
            }
    
    
            private string dataFile = string.Empty;
    
            public string DataFile
            {
                get { return dataFile; }
                set
                {
                    if (dataFile == value)
                        return;
                    dataFile = value;
                    RaisePropertyChanged("DataFile");
                }
            }
            public RHViewModel GetItem(string itemSku)
            {
                var item = new RHViewModel();
                using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
                {
                    var _item = (db.Table<RHData>().Where(
                        c => c.SKU == itemSku)).Single();
                    item.SKU = _item.SKU;
                    item.Judul = _item.Judul;
                    item.Tipe = _item.Tipe;
                    item.Harga = _item.Harga;
                    item.Gratis = _item.Gratis;
                    item.DataFile = _item.DataFile;
                }
                return item;
            }
    
            public string SaveItem(RHViewModel item)
            {
                string result = string.Empty;
                using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
                {
                    try
                    {
                        var existingItem = (db.Table<RHData>().Where(
                            c => c.SKU == item.sku)).SingleOrDefault();
    
                        if (existingItem != null)
                        {
                            existingItem.SKU = item.SKU;
                            existingItem.Judul = item.Judul;
                            existingItem.Tipe = item.Tipe;
                            existingItem.Harga = item.Harga;
                            existingItem.Gratis = item.Gratis;
                            existingItem.DataFile = item.DataFile;
    
                            int success = db.Update(existingItem);
                        }
                        else
                        {
                            int success = db.Insert(new RHData()
                            {
                                SKU = item.SKU,
                                Judul = item.Judul,
                                //Deskripsi = item.Deskripsi,
                                Tipe = item.Tipe,
                                Harga = item.Harga,
                                Gratis = item.Gratis,
                                //Cover = item.Cover,
                                //File = item.File,
                                DataFile = item.DataFile
                            });
                        }
                        result = "Success";
                    }
                    catch
                    {
                        result = "This item was not saved.";
                    }
                }
                return result;
            }
    
            public string DeleteItem(string itemDataFile)
            {
    
                string result = string.Empty;
                using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
                {
                    var existingItem = dbConn.Query<RHData>("select * from RH where DataFile =" + itemDataFile).FirstOrDefault();
                    if (existingItem != null)
                    {
                        dbConn.RunInTransaction(() =>
                        {
                            dbConn.Delete(existingItem);
    
    
                            if (dbConn.Delete(existingItem) > 0)
                            {
                                result = "Success";
                            }
                            else
                            {
                                result = "This item was not removed";
                            }
    
                        });
                    }
    
                    return result;
                }
            }
    
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected virtual void RaisePropertyChanged(string propertyName)
            {
                var handler = this.PropertyChanged;
                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    }

    RHItemsViewModel Class:

    class RHItemsViewModel : RHViewModel
        {
            private ObservableCollection<RHViewModel> items;
            public ObservableCollection<RHViewModel> Items
            {
                get
                {
                    return items;
                }
    
                set
                {
                    items = value;
                    RaisePropertyChanged("Items");
                }
            }
    
            public ObservableCollection<RHViewModel> GetItems()
            {
                items = new ObservableCollection<RHViewModel>();
                using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
                {
                    var query = db.Table<RHData>().OrderBy(c => c.SKU);
                    foreach (var _item in query)
                    {
                        var item = new RHViewModel()
                        {
                            //SKU = _item.SKU,
                            SKU = _item.SKU,
                            Judul = _item.Judul,
                            //Deskripsi = _item.Deskripsi,
                            Tipe = _item.Tipe,
                            Harga = _item.Harga,
                            Gratis = _item.Gratis,
                            //Cover = _item.Cover,
                            //File = _item.File,
                            DataFile = _item.DataFile
                        };
                        items.Add(item);
                    }
                }
                return items;
            }
        }
    }

    App.Xaml.CS

    public static string DB_PATH = Path.Combine(ApplicationData.Current.LocalFolder.Path, "RH.sqlite");
            public static SQLite.Net.Platform.WinRT.SQLitePlatformWinRT SQLITE_PLATFORM;
            public App()
            {
                Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
                    Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
                    Microsoft.ApplicationInsights.WindowsCollectors.Session);
                this.InitializeComponent();
                this.Suspending += OnSuspending;
                SQLITE_PLATFORM = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
                if (!CheckFileExists("RH.sqlite").Result)
                {
                    using (var db = new SQLiteConnection(SQLITE_PLATFORM, DB_PATH))
                    {
                        db.CreateTable<RHData>();
                    }
                }
            }
            private async Task<bool> CheckFileExists(string fileName)
            {
                try
                {
                    var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                    return true;
                }
                catch
                {
                }
                return false;
            }

    Code:

    protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                //GC.Collect();
                BukuAudio dlList = e.Parameter as BukuAudio;
                if (dlList != null)
                {
                    Queue<DownloadOperation> downloadOperationList = new Queue<DownloadOperation>();
                    BackgroundDownloader downloader = new BackgroundDownloader();
                    DownloadProgress.Visibility = Visibility.Visible;
                    downloadfilename.Visibility = Visibility.Visible;
                    statusdownload.Visibility = Visibility.Visible;
                    deleteBtn.Visibility = Visibility.Collapsed;
                    viewBtn.Visibility = Visibility.Collapsed;
                    foreach (var path in dlList.BundlePath)
                    {
                        DownloadBuku(path);
    
                        for (int i = 0; i<dlList.BundlePath.Count;i++)
                        {
                            downloadfilename.Text = dlList.BundleName.ElementAt(i);
                            Uri uri = new Uri(path);
                            string filename = path.Substring(uri.LocalPath.LastIndexOf("/") + 1);
                            downloadfilename.Text = String.Format("Unduh '{0}'", filename);
                        }
    
                    }
                    DownloadGambar(dlList.Cover);
                }
                else
                {
                    DownloadProgress.Visibility = Visibility.Collapsed;
                    downloadfilename.Visibility = Visibility.Collapsed;
                    statusdownload.Visibility = Visibility.Collapsed;
                    deleteBtn.Visibility = Visibility.Visible;
                    viewBtn.Visibility = Visibility.Visible;
                }
                bookAudio = e.Parameter as BookAudio;
    
    
            }
    
    private async void downloadClicked(object sender, RoutedEventArgs e)
                {
                    Uri uri = new Uri(itemDetail.BundlePath.First());
                    string filename = System.IO.Path.GetFileName(uri.LocalPath);
                    string statustext = String.Format("Download Buku '{0}'?", itemDetail.Judul);
                        string sudahada = String.Format("Buku '{0}' sudah ada/sedang didownload", itemDetail.Judul);
                        MessageDialog messageDialog;
                        try
                        {
                            StorageFolder library = await ApplicationData.Current.LocalFolder.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);
                            var file = await library.GetFileAsync(filename);
    
                            messageDialog = new MessageDialog(sudahada, "Buku sudah ada");
                            messageDialog.Commands.Add(new UICommand("Library", (command) =>
                            {
                                this.Frame.Navigate(typeof(library.LibraryPage));
                            }));
                            messageDialog.Commands.Add(new UICommand("Batal", (command) =>
                            {
                                //rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
                            }));
                        }
                        catch (FileNotFoundException ex)
                        {
                            //file not exists show download dialog
                            // Create the message dialog and set its content and title
    
                            messageDialog = new MessageDialog(statustext, "Download");
                            // Add commands and set their callbacks
    
                            messageDialog.Commands.Add(new UICommand("Download", (command) =>
                            {
                                itemsViewModel = new RHItemsViewModel();
                                itemsViewModel.SaveItem(new RHViewModel()
                                {
                                    SKU = itemDetail.SKU.ToString(),
                                    Judul = itemDetail.Judul.ToString(),
                                    Tipe = itemDetail.Tipe.ToString(),
                                    Harga = itemDetail.Harga.ToString(),
                                    Gratis = itemDetail.Gratis.ToString(),
                                    DataFile = itemDetail.DataFile.ToString()
                                });
                                this.Frame.Navigate(typeof(library.LibraryPage), itemDetail);
                            }));
    
                            messageDialog.Commands.Add(new UICommand("Batal", (command) =>
                            {
                                //rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
                            }));
                        }
                        // Show the message dialog
                        await messageDialog.ShowAsync();
                    }
                }

    LibraryPage:

    private async void DownloadBuku(string fileLocation)
            {
                itemsViewModel = new RHItemsViewModel();
                items = new ObservableCollection<RHViewModel>();
                using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
                {
                    var existingItem = dbConn.Table<RHData>().OrderBy(c => c.DataFile);
                    if (existingItem != null)
                    {
                        foreach (var _item in existingItem)
                        {
                            var item = new RHViewModel()
                            {
                                DataFile = _item.DataFile
                            };
    
                            items.Add(item);
                            var uri = new Uri(fileLocation);
                            var downloader = new BackgroundDownloader();
                            StorageFolder library = await installedLocation.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);
                            StorageFolder pdf = await library.CreateFolderAsync(item.DataFile.ToString(), CreationCollisionOption.OpenIfExists);
                            string filename = System.IO.Path.GetFileName(uri.LocalPath);
                            StorageFile file = await pdf.CreateFileAsync(filename,
                                CreationCollisionOption.ReplaceExisting);
    
                            DownloadOperation download = downloader.CreateDownload(uri, file);
                            await StartDownloadAsync(download);
                        }
                    }
                }
            }

    BukuAudio Class:

    class BukuAudio
        {
            public string SKU { get; set; }
    
            public string Judul { get; set; }
    
            public string Deskripsi { get; set; }
    
            public string Tipe { get; set; }
    
            public string NamaTipe { get; set; }
    
            public string Harga { get; set; }
    
            public string Cover { get; set; }
    
            public string File { get; set; }
    
            public string Gratis { get; set; }
    
            public string Tanggal { get; set; }
    
            public string DataFile { get; set; }
    
            public JsonArray Bundle_file { get; set; }
    
            public List<string> BundleName { get; set; }
    
            public List<string> BundlePath { get; set; }
    
        }

    How to handle it?

    Note:

    • First Bundle File downloaded in the folder "bundle.24b"
    • Second Bundle file downloaded files in the folder "bundle.23b"
    • Third Bundle downloaded file in the folder "bundle.22b
    • Supposedly the file name "bundle.24b ....." downloaded in folder bundle.24b, the file name "bundle.23b ....." downloaded in folder bundle.23b, the file name "bundle.22b ....." downloaded in folder bundle.22b

    Monday, July 11, 2016 3:20 AM

All replies