Wednesday, July 9, 2008

Resolving Download Failure in WebClient

Today I was developing a Silverlight client program which reads cross-domain content when I started facing Download Failure exception. This is code I was using, which resulted in exception

private void btnSearch_Click(object sender, RoutedEventArgs e){
string strTopic=txtSearchTopic.Text;
string strUrl = "";
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler
(this.DownloadCompleted);
wc.DownloadStringAsync(new Uri(strUrl));
}
private void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
string strResult = e.Result;
}
}


So in this code, Line 10 was throwing Download failure exception probably because my domain in not registered in GroupPolicy.xml file on the server from which I was reading the content. Now the solution to this problem is to use System.Net.HttpWebRequest object which can easily read data across domains. So here are steps:

  • Add Reference to System.Net assembly


  • Add System.Net namespace and replace the previous code with this code





private void btnSearch_Click(object sender, RoutedEventArgs e)
{
string strTopic = txtSearchTopic.Text;
string strUrl = "";
HttpWebRequest objRq = (HttpWebRequest)WebRequest.Create(new Uri(strUrl));

objRq.BeginGetResponse(new AsyncCallback(responseHandler), objRq);

}
void responseHandler(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
Stream respStream = response.GetResponseStream();
if (respStream != null)
{
StreamReader sr = new StreamReader(respStream);
//Here you will get the content in strResp string
string strResp = sr.ReadToEnd();

}
}




And the above code worked.





No comments: