locked
how to download multiple file using background transfer in windows store 8.1

    Question



  • public sealed partial class MainPage : Page
    {
        LicenseChangedEventHandler licenseChangeHandler = null;
    
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();
    
        AlphabetData alphabetData = null;
        StoreData storeData = null;
    
        private List<DownloadOperation> activeDownloads;
        private CancellationTokenSource cts;
        StorageFolder localFolder = null;
    
        string destination =  null;
        string VideoName = null;
        string serveraddressField = null;
    
    
        public MainPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
          //  this.NavigationCacheMode = NavigationCacheMode.Enabled;
    
            alphabetData = new AlphabetData();
            ItemListView.ItemsSource = alphabetData.Collection;
            storeData = new StoreData();
            // setting the ListView source to the sample data 
            DetailsItemListView.ItemsSource = storeData.Collection;
            // making sure the first item is the selected item
            DetailsItemListView.SelectedIndex = 0;
            // DetailsItemListView.SelectionMode = ListViewSelectionMode.Single;
            this.setTermsByAlphabet("A");
    
    
            cts = new CancellationTokenSource();
            localFolder = ApplicationData.Current.LocalFolder;
    
        }
    
        public void Dispose()
        {
            if (cts != null)
            {
                cts.Dispose();
                cts = null;
            }
            GC.SuppressFinalize(this);
        }
    
    
        #region NavigationHelper registration
    
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
            await DiscoverActiveDownloadsAsync();
        }
    
        private async Task DiscoverActiveDownloadsAsync()
        {
            activeDownloads = new List<DownloadOperation>();
    
            IReadOnlyList<DownloadOperation> downloads = null;
            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Discovery error", ex))
                {
                    throw;
                }
                return;
            }
    
            if (downloads.Count > 0)
            {
                List<Task> tasks = new List<Task>();
                foreach (DownloadOperation download in downloads)
                {
                    // Attach progress and completion handlers.
                    tasks.Add(HandleDownloadAsync(download, false));
                }
    
    
                await Task.WhenAll(tasks);
            }
        }
        #endregion
    
        private async void ItemListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            Item _item = e.ClickedItem as Item;
            this.setTermsByAlphabet(_item.Title as string);
    
            VideoName = _item.Title;
            StorageFolder dataFolder = await localFolder.CreateFolderAsync("VideoFolder",
            CreationCollisionOption.OpenIfExists);
    
          //  string[] serveraddressArray = { "", "" };
    
            switch (VideoName)
                {
                    case "A":
                        serveraddressField = "http://192.168.1.10/AA/jaa/eng/repsys.mp4";
                        destination = "repsys.mp4";
                        break;
                    case "B":
                        serveraddressField = "http://192.168.1.10/AA/jaa/eng/csys.mp4";
                        destination = "csys.mp4";
                        break;
                    case "C":
                        break;   
                    case "E":
                        break;
                    case "F":
                        break;
                    case "G":
                        break;
                    case "H":
                        break;
                    case "I":
                        break;
                    case "L":
                        break;
                    case "M":
                        break;
                    case "N":
                        break;
                    case "P":
                        break;
                    case "R":
                        break;
                    case "S":
                        break;
                    case "T":
                        break;
                    case "U":
                        break;
                    case "V":
                        break;
                    case "W":
                        break;
    
                    default:
                        break;
                }
    
              if (await FileExistsAsync(dataFolder, destination))
              {
                  StartDownloadButton.Visibility = Visibility.Collapsed;
                  Progressbox.Visibility = Visibility.Collapsed;
                  System.Diagnostics.Debug.WriteLine("Download Collapsed");
              }
              else
              {
                  StartDownloadButton.Visibility = Visibility.Visible;
                  Progressbox.Visibility = Visibility.Visible;       
                  System.Diagnostics.Debug.WriteLine("Download Visible");
    
              }
    
        }
    
        public void NotifyUser(string strMessage, NotifyType type)
        {
        }
        public enum NotifyType
        {
            StatusMessage,
            ErrorMessage
        };
        private void setTermsByAlphabet(string queryText)
        {
            IEnumerable<Item> suggestionList = (IEnumerable<Item>)storeData.Collection.Cast<Item>();
            List<Item> filteredList = suggestionList.ToList<Item>();
            if (!string.IsNullOrEmpty(queryText))
            {
                foreach (Item suggestedItem in suggestionList)
                {
                    String suggestion = suggestedItem.Title;
                    if (suggestion.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase))
                    {
                    }
                    else
                    {
                        filteredList.Remove(suggestedItem);
                    }
                }
                DetailsItemListView.ItemsSource = filteredList;
            }
            else
            {
                DetailsItemListView.ItemsSource = storeData.Collection;
            }
        }
    
        private  void DetailsItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
              if (DetailsItemListView.SelectedIndex < 0)
                DetailsItemListView.SelectedIndex = 0;
        }
    
        private async Task<bool> FileExistsAsync(StorageFolder folder, string fileName)
        {
            try
            {
                await folder.GetFileAsync(fileName);
                return true;
            }
            catch (FileNotFoundException)
            {
                return false;
            }
    
        }
        private async void StartDownload(BackgroundTransferPriority priority, bool requestUnconstrainedDownload)
        {
    
            StorageFolder dataFolder = await localFolder.CreateFolderAsync("VideoFolder",
            CreationCollisionOption.OpenIfExists);
            Uri source;
            if (!Uri.TryCreate(serveraddressField, UriKind.Absolute, out source))
            {
                return;
            }
    
            StorageFile destinationFile;
    
            try
            {
                destinationFile = await dataFolder.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);
            }
            catch (Exception)
            {
                return;
            }
    
            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download = downloader.CreateDownload(source, destinationFile);
    
            download.Priority = priority;
    
            if (!requestUnconstrainedDownload)
            {
                // Attach progress and completion handlers.
                await HandleDownloadAsync(download, true);
                return;
            }
    
            List<DownloadOperation> requestOperations = new List<DownloadOperation>();
            requestOperations.Add(download);
    
    
            UnconstrainedTransferRequestResult result;
            try
            {
                result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations);
            }
            catch (NotImplementedException)
            {
                return;
            }
    
             await HandleDownloadAsync(download, true);
        }
    
        private void StartDownload_Click(object sender, RoutedEventArgs e)
        {
            StartDownload(BackgroundTransferPriority.Default, false);
            outputField.Visibility = Visibility.Visible;
            PauseAllButton.Visibility = Visibility.Visible;
            ResumeAllButton.Visibility = Visibility.Visible;
            CancelAllButton.Visibility = Visibility.Visible;
            StartDownloadButton.Visibility = Visibility.Collapsed;
       }
    
        private void PauseAll_Click(object sender, RoutedEventArgs e)
        {
            foreach (DownloadOperation download in activeDownloads)
            {
                if (download.Progress.Status == BackgroundTransferStatus.Running)
                {
                    download.Pause();
                }
                else
                {
                }
            }
        }
    
        private void ResumeAll_Click(object sender, RoutedEventArgs e)
        {
            foreach (DownloadOperation download in activeDownloads)
            {
                if (download.Progress.Status == BackgroundTransferStatus.PausedByApplication)
                {
                    download.Resume();
                }
                else
                {
                }
            }
        }
    
        private void CancelAll_Click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
            cts.Dispose();
    
            // Re-create the CancellationTokenSource and activeDownloads for future downloads.
            cts = new CancellationTokenSource();
            activeDownloads = new List<DownloadOperation>();
        }
    
        private void DownloadProgress(DownloadOperation download)
        {
            double percent = 100;
            if (download.Progress.TotalBytesToReceive > 0)
            {
                percent = download.Progress.BytesReceived * 100 / download.Progress.TotalBytesToReceive;
            }
    
            outputField.Value = percent;
    
            if (outputField.Value == 100)
            {
                Progressbox.Visibility = Visibility.Collapsed;
                outputField.Visibility = Visibility.Collapsed;
                videoPlayer.Play();
            }
        }
    
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                // Store the download so we can pause/resume.
                activeDownloads.Add(download);
    
                Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }
    
                ResponseInformation response = download.GetResponseInformation();
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Execution error", ex, download))
                {
                    throw;
                }
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
    
    
    }

    Am not able to download multiple files using switch case ,i need to download more than two files in every switch case aboveis my code,

    I am new to Windows development. Any and all help will be appreciated.

    • Edited by fmidev Monday, January 19, 2015 7:17 AM
    Monday, January 19, 2015 7:15 AM

All replies

  • can you share a project we can run? easier to look in it.

    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    Monday, January 19, 2015 9:10 AM