Question

I have to get the result from a web service. This is what I used:

EDIT:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        webService.WebServiceHuscSoapClient a = new webService.WebServiceHuscSoapClient();
        a.InsertNewUserCompleted += a_InsertNewUserCompleted;
        a.InsertNewUserAsync("name", "phonenumber", "address");
    }

    void a_InsertNewUserCompleted(object sender, webService.InsertNewUserCompletedEventArgs e)
    {
        MessageBox.Show(e.Result.ToString());
    }

Is there any way that I could put all this function and even handler to a class and when I want to get data from my webservice I would do something like this:

string json = MyWebService.GetData();
Was it helpful?

Solution 2

I figured it out from this article: How to use async-await with WCF in VS 2010 for WP7?

More: Async CTP - How can I use async/await to call a wcf service?

I wrote this on another class:

 public static Task<int> InsertNewUser(string name, string phonenumber,string address) //can make it an extension method if you want.
    {
        TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
        service.InsertNewUserCompleted += (object sender, WebService.InsertNewUserCompletedEventArgs e) => //change parameter list to fit the event's delegate
        {
            if (e.Error != null) tcs.SetResult(-1);
            else
                tcs.SetResult((int)e.Result);
        };
        service.InsertNewUserAsync(name, phonenumber,address);
        return tcs.Task;
    }

then I could call it from my class:

 int su = await WebServiceHelper.SignUp("blabla", "0123465","huehuehue");

OTHER TIPS

First, your call of DownloadStringAsync suggests passing in username and password, but it doesn't work like that. Check the documentation.

To (not really :-) ) answer your question: a far better approach these days is to use the new 'async/await' functionality available in C# 5. See this link for a comprehensive overview.

Your example then becomes trivial (no need to hook up a separate event handler anymore)

private async void Button_Click(object sender, RoutedEventArgs e)
{
    WebClient webclient = new WebClient();
    // TODO set up credentials
    string result = await webclient.DownloadStringTaskAsync("http://your-url-here");
    textBlock1.Text = str;
}

You could then still extract this in a separate, reusable (async) method:

private async Task<string> GetDataAsync()
{
    WebClient webClient = new WebClient();
    // TODO set up credentials
    string result = await webclient.DownloadStringTaskAsync("http://your-url-here"); 
    return result;
}

If you want to stick with the event-based approach, you could wrap the functionality in a separate class with it's own event, but that wouldn't bring you much gain IMO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top