0

I'm trying to create a downloading app that runs on RSS Feeds. What I'm trying to accomplish is a get parse the xml with a title desc and a link is a listbox(which I have done) but when the user clicks on the link to then download a JPG to the phone, which I can't do any help would be greatly appreciated.

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    WebClient wc = new WebClient();
    wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
    wc.DownloadStringAsync(new Uri("Https://feed.xml"));
}

private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
        return;
    XElement xmlitems = XElement.Parse(e.Result);

   List<XElement> elements = xmlitems.Descendants("item").ToList();

   List<RSSItem> aux = new List<RSSItem>();
   foreach (XElement rssItem in elements)
   {
       RSSItem rss = new RSSItem();                
       rss.Description1 = rssItem.Element("description").Value;
       rss.Link1 = rssItem.Element("link").Value;
       rss.Title1 = rssItem.Element("title").Value;
       aux.Add(rss);
       TextBlock tbTitle = new TextBlock();
       tbTitle.Text = rss.Title1 + "\n";
       ListBoxRss.Items.Add(tbTitle);
       TextBlock tbDescription = new TextBlock();
       tbDescription.Text = rss.Description1 + "\n";
       ListBoxRss.Items.Add(tbDescription);
       TextBlock tbLink = new TextBlock();
       tbLink.Text = rss.Link1 + "\n";
       ListBoxRss.Items.Add(tbLink);

   }
}

The Info you gave me worked fine but im having one last issue, the app loads fine lists the xml fine, when the user clicks on the download link it only works once, once downloaded if the user clicks on another one it only remembers the title and link from the first click until i restart the app here is my current code

    public string fileurl;
    public string filetitle;
    public string filesave;

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        WebClient wc = new WebClient();
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
        wc.DownloadStringAsync(new Uri("https://feed.xml"));
    }

    private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error != null)
            return;
        XElement xmlitems = XElement.Parse(e.Result);
        List<XElement> elements = xmlitems.Descendants("item").ToList();   
        List<RSSItem> aux = new List<RSSItem>();
        foreach (XElement rssItem in elements)
        {
            RSSItem rss = new RSSItem();               
            rss.Description1 = rssItem.Element("description").Value;
            rss.Link1 = rssItem.Element("link").Value;
            rss.Title1 = rssItem.Element("title").Value;
            aux.Add(rss);
            TextBlock tbTitle = new TextBlock();
            tbTitle.Text = rss.Title1 + "\n";     
            ListBoxRss.Items.Add(tbTitle);
            TextBlock tbLink = new TextBlock();
            tbLink.Text = "Download: " + rss.Link1; 
            tbLink.MouseLeftButtonDown += new MouseButtonEventHandler(tbLink_MouseLeftButtonDown);
            ListBoxRss.Items.Add(tbLink);
            fileurl = rss.Link1;
            filetitle = rss.Description1;              
        }
    }

    private void tbLink_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {       
       WebClient client = new WebClient();
        client.OpenReadCompleted += client_OpenReadCompleted;
       client.OpenReadAsync(new Uri(fileurl));         
    }

    async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        filesave = (filetitle + ".zip");
        byte[] buffer = new byte[e.Result.Length];
        await e.Result.ReadAsync(buffer, 0, buffer.Length);
        using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream stream = storageFile.OpenFile(filesave, FileMode.Create))
            {
                await stream.WriteAsync(buffer, 0, buffer.Length);
            }
        }

        try
        {               
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile pdffile = await local.GetFileAsync(filesave);
            Windows.System.Launcher.LaunchFileAsync(pdffile);
        }
        catch (Exception)
        {
            MessageBox.Show("File Not Found");
        }
    }
  • because `fileurl` and `filetitleis` are assigned in the foreach loop, their values are from the last link you add to the listbox, and never change afterwards no matter which link you click. – kennyzx Oct 17 '14 at 01:17

1 Answers1

1

Register a 'Click' event on the tbLink before adding it to the ListBox.

...
    TextBlock tbLink = new TextBlock();
    tbLink.Text = rss.Link1 + "\n";

    //add the event handler
    tbLink.MouseLeftButtonDown += new MouseButtonEventHandler(tbLink_MouseLeftButtonDown);
    ListBoxRss.Items.Add(tbLink);
}

When user tap the TextBlock, you use WebClient.OpenReadAsync(Uri) to read the online image into a byte array (byte[]), and then save the byte array to IsolatedStorage.

private void tbLink_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    WebClient client = new WebClient();
    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
    client.OpenReadAsync(new Uri((sender as TextBlock).Text));
}

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    var resInfo = new StreamResourceInfo(e.Result, null);
    var reader = new StreamReader(resInfo.Stream);

    byte[] contents;
    using (BinaryReader bReader = new BinaryReader(reader.BaseStream))
    {
        contents = bReader.ReadBytes((int)reader.BaseStream.Length);
    }

    IsolatedStorageFileStream stream = file.CreateFile("file.jpg");
    stream.Write(contents, 0, contents.Length);
    stream.Close();
}

The code sample is taken from here.

Update based on your comment:

I attach the link information (the url and the description) to tbLink, which I can get when the TextBlock is clicked - you can see the difference, each tbLink has its unique url and description.

public string fileurl;
public string filetitle;
public string filesave;

private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    ...
    foreach (XElement rssItem in elements)
    {
        ...
        TextBlock tbLink = new TextBlock();
        tbLink.Text = "Download: " + rss.Link1; 

        //Add the link info to tbLink, you can get the info when tbLink is Clicked
        tbLink.Tag = new string[] {rss.Link1, rss.Description1};
        tbLink.MouseLeftButtonDown += new MouseButtonEventHandler(tbLink_MouseLeftButtonDown);
        ListBoxRss.Items.Add(tbLink);
    }
}

private void tbLink_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{       
   //get the link info from tbLink's Tag property
   string[] linkInfo = (sender as TextBlock).Tag as string[];
   fileurl = linkInfo[0];

   WebClient client = new WebClient();
   client.OpenReadCompleted += client_OpenReadCompleted;
   //pass the link info to the OpenReadCompleted callback
   client.OpenReadAsync(new Uri(fileurl), linkInfo);         
}

async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    //and you get the link info from the e.UserState property
    string[] linkInfo = e.UserState as string[];
    filetitle = linkInfo[1];
    filesave = (filetitle + ".zip");
    ...
}
kennyzx
  • 12,845
  • 6
  • 39
  • 83
  • Hi thanks for the tip, worked great i'm now having a very odd issue i've edited my post thanks – black1stallion2 Oct 16 '14 at 22:50
  • you are a genius!, is there any way to save to the download folder as for some reason if for example i download a zip file, it wont work with any zip app, so i want to test the newly downloaded file on the computer to make sure its valid – black1stallion2 Oct 17 '14 at 08:53
  • unfortunately you can't access the Downloads folder from your app by writing code- it is restricted for security reasons. And your file is not zipped at all, you just change its file extension from .png to .zip, of course it won't open in zip apps. – kennyzx Oct 17 '14 at 09:06
  • Try [this](http://stackoverflow.com/a/20006189/815938) for writing zip file on WP8. – kennyzx Oct 17 '14 at 09:10
  • i have done that, i used manual urls not from the feed and manual save names just to be sure, the files download fine but when i open them they are corrupt, they download and open fine on a pc, but dont work when i download them via the app – black1stallion2 Oct 17 '14 at 09:10
  • is there anyway to access the downloaded file so i can check they are being saved right – black1stallion2 Oct 17 '14 at 09:11
  • try the [ISETool](http://msdn.microsoft.com/en-us/library/windows/apps/hh286408(v=vs.105).aspx#BKMK_othertools) – kennyzx Oct 17 '14 at 09:25
  • i uses wptools all the files are invalid once downloaded through the app, any ideas? – black1stallion2 Oct 17 '14 at 11:04
  • I suggest ask a new question about that, otherwise our discussion becomes off-topic. – kennyzx Oct 17 '14 at 15:59