Creating the HTTP web service class for the TrackMyWalks app

In the previous section, we successfully modified the WalkEntries database model that will be used by our TrackMyWalks application. This will allow us to have a live backend service that will enable our application to communicate over HTTP so that it can send requests to the API to retrieve, add, and delete trail walk entries. In this section, we will need a means for our app to communicate with our API over HTTP, and therefore it will require an HTTP library.

Since we are using .NET and C#, we can use a library within the .NET Framework, called System.Net.Http.HttpClient. This Framework provides a mechanism for allowing our app to send and receive data using standard HTTP methods such as GET and POST. We will begin by creating a base service class within our TrackMyWalks Portable Class Library that will be responsible for handling all the HTTP communications for us.

Let's now start to implement the code required for our WalkWebService base-class model, by performing the following steps:

  1. Create an empty class within the Services folder, by choosing Add | New File..., as you did in the section entitled, Creating the navigation service interface for the TrackMyWalks app within Chapter 3 , Navigating within the MVVM Model - The Xamarin.Forms Way.
  2. Then, enter in WalkWebService for the name of the new class that you want to create, and click on the New button to allow the wizard to proceed and create the new file.
  3. Next, ensure that the WalkWebService.cs file is displayed within the code editor, and enter in the following code snippet:
            // 
            //  WalkWebService.cs 
            //  TrackMyWalks Http Web Service Class 
            // 
            //  Created by Steven F. Daniel on 30/10/2016. 
            //  Copyright © 2016 GENIESOFT STUDIOS. All rights reserved. 
            // 
                using System; 
                using System.Collections.Generic; 
                using System.Net.Http; 
                using System.Text; 
                using System.Threading.Tasks; 
                using Newtonsoft.Json; 
     
                namespace TrackMyWalks.Services 
                { 
                    public abstract class WalkWebService 
                    { 
    
  4. Then, we need to create a protected async method called SendRequestAsync<T> that accepts a Uri named url as well a HttpMethod named httpMethod, and finally a Dictionary<string, string> object named headers, as well as an object named requestData, that will be used to construct the HTTP request. Proceed and enter in the following code snippet:
            protected async Task<T> SendRequestAsync<T>( 
              Uri url, HttpMethod httpMethod = null,
              IDictionary<string, string> headers = null,
              object requestData = null) 
            { 
    
  5. Next, we'll set up the result to the default(T) type that will return a default value to a parameterized type since we don't know what our result will contain at this point. We'll then declare our method variable to contain the GET HttpMethod. This will be used to return the content and then create a request variable that will set up an instance of our HttpRequestMessage class and then serialize our requested data to our request object and return the information back in Json format as defined by the application/json type. Proceed and enter in the following code snippet:
            var result = default(T); 
            var method = httpMethod ?? HttpMethod.Get; 
            var request = new HttpRequestMessage(method, url); 
     
            // Serialize our request data 
            var data = requestData == null ? null :  
              JsonConvert.SerializeObject(requestData); 
                
            if (data != null) 
            { 
               // Add the serialized request data to our request  
               // object. 
               request.Content = new StringContent(data, 
                 Encoding.UTF8, "application/json"); 
             } 
    
  6. Then, we'll begin iterating through our headers collection to add each of our specific headers to the request object that will be sent along with the HttpRequestMessage class. Proceed and enter in the following code snippet:
            // Add each of the specified headers to our request 
            if (headers != null) 
            { 
                foreach (var h in headers) 
                { 
                    request.Headers.Add(h.Key, h.Value); 
                } 
            } 
    
  7. Next, we'll set up and declare a handler variable that instantiates an instance of the HttpClientHandler class which is essentially a HttpMessageHandler that contains a common set of properties that work across the HttpWebRequest API. In the next step, we'll declare a client variable that instantiates our HttpClient class that accepts our handler variable to begin sending our request over HTTP.
  8. Next, we'll declare our response object that performs a SendAsync and accepts our request object, along with our HttpCompletionOption.ResponseContentRead that completes after reading the entire response content.
  9. Finally, we'll perform a comparison check to see if we have successfully read our content and have a response code of 200 (Success) returned, before deserializing our content into Json format, using the JsonConvert method. Proceed and enter in the following code snippet:
            // Get a response from our Web Service 
            var handler = new HttpClientHandler(); 
            var client = new HttpClient(handler;
            var response = await client.SendAsync(request,  
              HttpCompletionOption.ResponseContentRead); 
     
                if (response.IsSuccessStatusCode &&  
                response.Content != null) 
                { 
                    var content = await response.Content. 
                                  ReadAsStringAsync(); 
                    result = JsonConvert.DeserializeObject<T>(content); 
                } 
      
                return result; 
             } 
            } 
           } 
    

Now that we have successfully created our base HTTP service class, we can begin to use this within our ViewModels as well as our WalkEntries database model, by creating a base sub-class within our DataService API which we will be covering in the next section.

Note

If you are interested in finding out more information about the HttpClientHandler and HttpClient classes, please refer to the Microsoft developer documentation located at https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx .

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.197.136