3

I have this code for execute httpwebrequest and response in background method and i just want show dialog for information when download zip crashed and my code enter in this catch...

    private void DoSincroFit()
    {
        HttpWebRequest request = HttpWebRequest.CreateHttp(url);
        request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
    }

    public async void playResponseAsync(IAsyncResult asyncResult)
    {
        //Declaration of variables
        HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;

        try
        {
            string fileName = "sincrofit.rar";

            using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
            {
                byte[] buffer = new byte[1024];


                var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                var newZipFile = await KnownFolders.DocumentsLibrary.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new DataWriter(outputStream))
                        {
                            using (Stream input = webResponse.GetResponseStream())
                            {
                                var totalSize = 0;
                                for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                                {
                                    dataWriter.WriteBytes(buffer);
                                    totalSize += size;    //get the progress of download
                                }
                                await dataWriter.StoreAsync();
                                await outputStream.FlushAsync();
                                dataWriter.DetachStream();
                            }
                        }
                    }
                }

            }
        }
        catch
        {
           SMethods.Message_Dialog("Download has stopped!","Error");
        }
    }

But when my code execute this method, from this class:

class StandarMethods
{
public async void Message_Dialog(string text, string title)
    {
        //Declaration of variables
        MessageDialog MDialog = new MessageDialog(text, title);

        await MDialog.ShowAsync();
    }
}

Finally my app crash when try to execute:

await MDialog.ShowAsync();

This await in background task... Someone can helps me? It's possible time to use Event Handlers? Why? How? Thanks in advance!

3 Answers3

2

Merli your problem is you are trying to access the UI thread from a background tread to show dialog to user So use Dispatcher for this Basic example is : -

// This is for silverlight part
    Deployment.Current.Dispatcher.BeginInvoke(delegate
    {
      var mbr = MessageBox.Show("Are you sure you want to leave this page?", "Warning",      
      MessageBoxButton.OKCancel);

      if(mbr == MessageBoxResult.OK)
      {   OK pressed  } 
      else
      {   Cancel pressed  }

    });

For winrt part -

CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
    dispatcher.RunAsync(CoreDispatcherPriority.Normal, async()=>{
          // UI code goes here
          //Declaration of variables
        MessageDialog MDialog = new MessageDialog(text, title);
        await MDialog.ShowAsync();
    });
loop
  • 9,002
  • 10
  • 40
  • 76
  • Perfect! But this code give me a little error... Error: "Object reference no set to and intance of an object" This is a sealed class and don't have constructor methods.Any idea? Thanks for all! – Merlí Escarpenter Pérez Sep 08 '14 at 07:38
  • This Code doesn't work, because visual say me: "The name "Deployment" doesn't exists in actual context" and when i use the visual studio help then export this library: Windows.Phone.Management.Deployment.Current.Dispatcher.BeginInvoke... But visual say me that current doesn't exist and is a error. Finally MessageBox control doesn't exist in Windows phone 8. Thaks for all! – Merlí Escarpenter Pérez Sep 08 '14 at 09:54
  • Are you developing for WP8.1 silverlight or WP8.1 winrt templates ? – loop Sep 08 '14 at 09:56
  • And the first code: CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { //Declaration of variables SMethods.Message_Dialog("Download has stopped!", "Error"); }); Fail in the first line when assign value on the dispatcher. Thanks for all – Merlí Escarpenter Pérez Sep 08 '14 at 09:59
  • I don't know exactly, sorry but i'm newbie developer of wp, silverlight it's a nuguet package's or library? If it's then I use winrt templates, how can i know this? Thanks for all! – Merlí Escarpenter Pérez Sep 08 '14 at 10:10
  • In Your solution explorer of VS you can see beside of your project. For silverlight project - it is like Windows Phone Silverlight 8.1. If Silverlight is not thr - try the Winrt code in the ans - it is working for me. any problem just comment. – loop Sep 08 '14 at 10:14
  • In the first code u try to execute in catch? Because when I use this: catch { CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { //Declaration of variables SMethods.Message_Dialog("Download has stopped!", "Error"); }); } My visual studio give me a error on here: CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; – Merlí Escarpenter Pérez Sep 08 '14 at 10:23
  • This is a error: "Object reference no set to and intance of an object" when I execute the program. Thanks for all! – Merlí Escarpenter Pérez Sep 08 '14 at 10:25
  • What you can do is declare your Dispatcher in some page or outside your method. May be dispatcher is not able to get the window to show messagebox. in my end it is working. – loop Sep 08 '14 at 10:30
  • loop u can see my final code and image in the las post, thanks for all! – Merlí Escarpenter Pérez Sep 08 '14 at 10:49
  • @MerlíPérezEscarpenter I am not sure about the issue. What I can say is put your "CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; //CRASH IN THIS LINE!" line outside your "playResponseAsync" callback method. – loop Sep 08 '14 at 11:00
  • Yes FINALLY! Thx for all @loop :D – Merlí Escarpenter Pérez Sep 09 '14 at 08:02
  • @MerlíPérezEscarpenter But I think my ans is same as what you needed. but leave it. feels good it works for you :) – loop Sep 09 '14 at 08:49
  • Hi another time loop! You Know if can I use silverlight with a universal apps? :O Thanks in advance! – Merlí Escarpenter Pérez Oct 07 '14 at 10:50
  • @MerlíPérezEscarpenter No. – loop Oct 07 '14 at 13:52
2

Solved, and my final code is here:

    private CoreDispatcher dispatcher;

    private void DoSincroFit()
    {
        HttpWebRequest request = HttpWebRequest.CreateHttp(url);

        //Add headers to request
        request.Headers["Type"] = "sincrofit";
        request.Headers["Device"] = "1";
        request.Headers["Version"] = "0.000";
        request.Headers["Os"] = "WindowsPhone";

        dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
        request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
    }

    public async void playResponseAsync(IAsyncResult asyncResult)
    {
        //Declaration of variables
        HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;

        try
        {
            //For download file  with stream
            //http://social.msdn.microsoft.com/Forums/windowsapps/en-US/de96a61c-e089-4595-8349-612be5d23ee6/download-file-with-httpwebrequest?forum=winappswithcsharp
            string fileName = "sincrofit.rar";

            using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
            {
                byte[] buffer = new byte[1024];

                //For acces Local folder of phone device
                //http://social.msdn.microsoft.com/Forums/windowsapps/en-US/ec99721c-6565-4ce9-b6cc-218f2265f9c7/what-is-the-uri-of-an-isolatedstorage-file?forum=wpdevelop
                var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new DataWriter(outputStream))
                        {
                            using (Stream input = webResponse.GetResponseStream())
                            {
                                var totalSize = 0;

                                for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                                {
                                    dataWriter.WriteBytes(buffer);
                                    totalSize += size;    //get the progress of download

                                    dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                    {
                                        //Declaration of variables
                                        pBar.Value = sizeFit / totalSize * 100;
                                    });
                                }
                                await dataWriter.StoreAsync();
                                await outputStream.FlushAsync();
                                dataWriter.DetachStream();
                            }
                        }
                    }
                }

            }
        }
        catch
        {
            dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                //Declaration of variables
                SMethods.Message_Dialog("Download has stopped!", "Error");
            });
        }
    }

Thanks for your time @loop!

0

My final code:

    private void DoSincroFit()
    {
        HttpWebRequest request = HttpWebRequest.CreateHttp(url);

        //Add headers to request
        request.Headers["Type"] = "sincrofit";
        request.Headers["Device"] = "1";
        request.Headers["Version"] = "0.000";
        request.Headers["Os"] = "WindowsPhone";

        request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
    }

    public async void playResponseAsync(IAsyncResult asyncResult)
    {
        //Declaration of variables
        HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;

        try
        {
            string fileName = "sincrofit.rar";

            using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
            {
                byte[] buffer = new byte[1024];
                var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new DataWriter(outputStream))
                        {
                            using (Stream input = webResponse.GetResponseStream())
                            {
                                var totalSize = 0;
                                for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                                {
                                    dataWriter.WriteBytes(buffer);
                                    totalSize += size;    //get the progress of download
                                }
                                await dataWriter.StoreAsync();
                                await outputStream.FlushAsync();
                                dataWriter.DetachStream();
                            }
                        }
                    }
                }

            }
        }
        catch
        {
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; //CRASH IN THIS LINE!
            dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                //Declaration of variables
                SMethods.Message_Dialog("Download has stopped!", "Error");
            });
        }
    }

This is my photo:

enter image description here Thanks for all!