views:

587

answers:

1

Hi guys,

I'm playing with Silverlight 4, and I when my page loads, I call

beginGet("my/people/", new OpenReadCompletedEventHandler(continueLoadStamData));

that I have defined as

private void beginGet(string endpoint, OpenReadCompletedEventHandler callback)
{
  WebClient wc = new WebClient();
  wc.Credentials = new NetworkCredential(username, password);
  wc.OpenReadCompleted += callback;
  wc.OpenReadAsync(new Uri(baseURL + endpoint));
}

and continueLoadStamData()

void continueLoadStamData(object sender, OpenReadCompletedEventArgs e)
{
  JsonObject root = (JsonObject)JsonObject.Load(e.Result);
}

My problem is that when I get to e.Result, it throws an exception. It is the same exception I get as when I tried to use WebRequest req = ...; req.Credentials = new NetworkCredential(username, password):

{System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid.  Check InnerException for exception details. ---> System.Net.WebException: An exception occurred during a WebClient request. ---> System.NotImplementedException: This property is not implemented by this class.
   at System.Net.WebRequest.set_Credentials(ICredentials value)
   at System.Net.WebClient.GetWebRequest(Uri address)
   at System.Net.WebClient.OpenReadAsync(Uri address, Object userToken)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   at System.Net.OpenReadCompletedEventArgs.get_Result()
   at JSONSample.MainPage.continueLoadStamData(Object sender, OpenReadCompletedEventArgs e)
   at System.Net.WebClient.OnOpenReadCompleted(OpenReadCompletedEventArgs e)
   at System.Net.WebClient.OpenReadOperationCompleted(Object arg)}

Do you have any idea of what's going on, how I can make sure basic authentication is implemented and get my request going?

Cheers

Nik

+1  A: 

Based on Mark Monster's post here you're missing some lines of code in your beginGet method. It should be something like:

private void beginGet(string endpoint, OpenReadCompletedEventHandler callback)
{
  WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);  
  WebClient wc = new WebClient();  
  wc.Credentials = new NetworkCredential(username, password);
  wc.UseDefaultCredentials = false; 
  wc.OpenReadCompleted += callback;  
  wc.OpenReadAsync(new Uri(baseURL + endpoint));
}

Also, if you're just trying to get JSON from the server, you should be able to use DownloadStringAsync instead of OpenReadAsync which might simplify things.

Bryant
Thanks a bunch, I'll give that a try :-)
niklassaers
That was a great blogpost by Mark. I've sent him a comment, because I don't get his example to work, but when I get it to work, this looks great. :-)
niklassaers