Tuesday, September 18, 2012

Windows Store Apps – using a generic service layer

Another perhaps helpful tip when building Windows Store Apps that are connected in some way to the internet: You can easily create a reusable “service layer” for your web requests that make consuming async http urls more of a walk in the park.

With that said, say hello to the GenericServiceLayer for Windows Store Apps.

the idea is simple: extract away as much as possible from the (often) repetitive task of sending web requests in a windows store app.

Usage:

  1. Reference the dll/project
  2. In your viewmodel/datasource/whatever, create a GenericServiceLayer
  3. use it in your code

Setting up a GenericServiceLayer in your code shouldn’t take much more than this:

    public class GenericServiceLayerSample
    {
        private GenericServiceLayer service = null;

        public GenericServiceLayerSample()
        {
            CookieContainer cookieContainer = new CookieContainer();
            HttpMessageHandler handler = new HttpClientHandler() { CookieContainer = cookieContainer, UseCookies = true};
            handler = new InspectorHandler(handler);
            var client = new HttpClient(handler) { BaseAddress = new System.Uri("http://dev.virtualearth.net/REST/v1/Locations/") };

            service = new GenericServiceLayer(client);
        }
    }

Note that the code above also uses the InspectorHandler I wrote about in the previous post.

Now, to use it. It’s really as simple as:

        public async void Sample()
        {
            // get a string response
            var response = await service.GetAsync("Eiffel%20Tower?o=json&key=BingMapsKey");
            // get a Json.NET mapped model
            var responseModel = await service.GetAsync<MyEiffelTowerModel>("Eiffel%20Tower?o=json&key=BingMapsKey");
        }

Passing in parameters/content is done in a structured way using the normal syntax, for example:

            // pass in content via PUT and get a string response
            HttpContent content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("SomeInnerContent", "innercontent")
            });
            var response = service.PutAsync("Eiffel%20Tower?o=json&key=BingMapsKey", content);

The methods (GET, POST, PUT) exposed in the GenericServiceLayer all implement IAsyncOperationWithProgress<Tresult, int> which easily enables you to also report progress on the requests made:

            // get a string response and listen for progress
            var response = service.GetAsync("Eiffel%20Tower?o=json&key=BingMapsKey");
            int reportedProgress = 0;
            response.Progress = (info, progress) =>
            {
                reportedProgress = progress;
            };

The above “reportedProgress” would probably be a property in your viewmodel (or the approach you’re running with that makes use of NotifyPropertyChanged) so that it’d present a visual progress notification in your app when changed.

Perhaps you’ll find this useful, it has proven valuable in the adventures of Windows Store Apps I’m currently embarking on.

Full source code can be downloaded here.

No comments: