1

I'd like to make a request to a server, parse the response, and carry on with my app. It never seems to get to the callback method, and I'm pretty sure that when I call send(a_url) this thing doesn't even execute the HTTP request at all.

public class item
{
    public status status { get; set; }
    public response response { get; set; }
}
public class status
{
    public int code { get; set; }
    public string message { get; set; }
}
public class response
{
    public string token { get; set; }
    public int distance { get; set; }
    public int angle { get; set; }
}

...

    public item deserializedJSON;

...

    /* sends the url string to the server */
    public void send(string url)
    {
        WebClient c = new WebClient();

// EDIT: Swapped the next two lines\
        c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted);
        c.DownloadStringAsync(new Uri(url));


    }

    /* parses the JSON response from the server */
    public void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
            deserializedJSON = JsonConvert.DeserializeObject<item>(e.Result);
            isReady = true;
    }
0

3 Answers 3

2

You should wire-up the event before you call the method!

public void send(string url)
{
    WebClient c = new WebClient();
    c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted);
    c.DownloadStringAsync(new Uri(url));
}
2
  • Ha, yeah, should have. Good call. I've rearranged it but it's still never setting my deserializedJSON var.
    – Brian D
    Mar 10, 2011 at 1:52
  • 1
    Do you get any exception at all (like a timeout)?
    – Josh M.
    Mar 10, 2011 at 2:34
0

You might try attaching the event handler before you order the download.

0

The event can be wired after the download call - it will work correctly. Did you set breakpoints inside the event handler to make sure that it really never hits it? Where and how are you calling the send method?

A similar issue was tied to HttpWebRequest (details here) - for some reason it can be tied to the data you are downloading. Care to share the URL?

2
  • It is conceivable that the DownloadStringAsync call could have completed before the DownloadStringCompleted delegate was attached. (Although very unlikely for a web request, I agree.)
    – Josh M.
    Mar 10, 2011 at 3:07
  • Given the case, I highly doubt the delay in wiring the event is the cause - there seems to be a data problem from what I see.
    – Den
    Mar 10, 2011 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.