views:

186

answers:

1

Hello everybody,

I started developing an application in Silverlight that was dealing with downloading the HTML of a website and then parsing it. With Silverlight 4 this can be achieved easily by simply requesting elevated permissions. With Silverlight 3, however, the only way to get the HTML of a website is via a WebService call. My initial idea was to do the following:

public class Service1
{
    [OperationContract]
    public void GetHtml()
    {
        Uri targetUri = new Uri("http://www.google.com", UriKind.RelativeOrAbsolute);

        WebClient webClient = new WebClient();
        webClient.DownloadStringCompleted += this.WebClient_DownloadStringCompleted;
        webClient.DownloadStringAsync(targetUri);
    }

    private void WebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {

    }
}

However, I realized that as soon as I make the call, which is async as well, from my Silverlight application, there is no way for me to retrieve the HTML of the website. That is why I changed to the following:

public class Service1
{
    [OperationContract]
    public string GetHtml()
    {
        Uri targetUri = new Uri("http://www.google.com", UriKind.RelativeOrAbsolute);

        WebClient webClient = new WebClient();
        return webClient.DownloadString(targetUri);
    }
}

I believe the last approach is not that fine since it will freeze the thread. So, my question, is there a way to achieve the first approach a.k.a. make async call from an async call :). Any help would be greatly appreciated.

Best Regards, Kiril

+1  A: 

You can achieve your goal by implementig a Duplex Service. There is some useful information about it on the msdn site and a wonderful podcast entry by Mike Taulty. In general, you would have to modify your operation contract by splitting it into two parts. First part would initiate your WebClient download on the server. Then, on the server, after the html has been downloaded, the server would call back a contract that is implemented on the client side with the payload consisting of the required html content.

Przemek
+1 for a good answer. But: While this solution is definitely the way to go if you absolutely must, I am still wondering why you would need it. Any decent web server is perfectly capable of handling multiple requests. It will not be "frozen" just because it is downloading some HTML.
Henrik Söderlund
@Henrik. I agree with you 100%. This is just 'if you absolutely must'. Thanks for +1 :)
Przemek
So you are guys saying that it is perfectly normal to use the DownloadString method for this scenario.
Kiril
That is my opinion, yes.
Henrik Söderlund