Monday, October 1, 2012

Decoupling asynchronous web requests in another layer than the UI

Decoupling asynchronous web requests in another layer than the UI

I think this is a common and typical question from novices but I still don't fully understand the given solutions. I am writing a Windows Phone 7 application and I want to perform several HttpWebRequest where I submit POST data and set some headers. The response should be deserialized and then processed by the logic and/or UI layer.

Yes, Web communication is done in a asynchronous way for Silverlight apps. I got that. It works fine.

BUT: I want to decouple the communication handling from the UI resp. xaml.cs code. I need to do the communication with HttpWebRequest because I need to modify headers etc.

What I want to do is the following:

  1. A button is clicked. Login/Username is provided to let's say my communication layer. For example: LoginRequest(string username, string pwd)
  2. The comm. layer will execute the request and obtain the answer asynchronously, i.e. calling the callback LoginResponseCallback(IAsyncResult res)
  3. Okay, now I can handle the response, deserialize my retrieved JSON string into an object
  4. The object should be handed back to the UI to update the data. I know that I should use the Dispatcher.BeginInvoke method because the callback is not running on the UI thread.

But I still don't know how I can pass the object from my communication layer to the UI. I think the solution is very straightforward, like passing a delegate from the btnLogin_onClick(object sender, RoutedEventArgs e) to the LoginRequestmethod. Or maybe I need to work with lambdas?

I have a SendBasicRequest method in my communication layer, which sets the appropriate headers (e.g. ClientOS, LoginKey, VersionBuild etc.) I want to call this method from several pages, so I want it to be decoupled in the communication layer.

Thanks in advance

Answers & Comments...

Answer: 1

Use the MVVM light toolkit. It is the easiest way to decouple the UI from the backend code.

You can find MVVM Light on the CodePlex site.

by : AndrewJEhttp://stackoverflow.com/users/1061787




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog