Sunday, October 16, 2016

Hydrate C# class with data from Azure Web API service

In this post I will give an example on how one can easily hydrate a C# class with data coming from an Azure Web API service. Hydration is used in the context of loading data from a data sources into C# objects. In this case the data source is a Web API service located at http://cartoonapi.azurewebsites.net/api/cartoon.

If you point your browser to this address you will see the following JSON response representing a list of cartoon characters and their respective pictures:

[{"name":"Aladdin","pictureUrl":"images/aladdin.png"},
{"name":"Bambam Rubble","pictureUrl":"images/bambam_rubble.png"},
{"name":"Bambi","pictureUrl":"images/bambi.png"},
{"name":"Barney Rubble","pictureUrl":"images/barney_rubble.png"},
{"name":"Betty Flintstone","pictureUrl":"images/betty_flintstone.png"},
{"name":"Dino","pictureUrl":"images/dino.png"},
{"name":"Donald Duck","pictureUrl":"images/donald_duck.png"},
{"name":"Flintstone Family","pictureUrl":"images/flintstone_family.png"},
{"name":"Flounder","pictureUrl":"images/Flounder.png"},
{"name":"Fred Flinrstone","pictureUrl":"images/fred_flinrstone.png"},
{"name":"Goofy","pictureUrl":"images/Goofy.png"},
{"name":"Jasmine","pictureUrl":"images/jasmine.png"},
{"name":"Jumbo","pictureUrl":"images/jumbo.png"},
{"name":"Mermaid","pictureUrl":"images/mermaid.png"},
{"name":"Micky Mouse","pictureUrl":"images/micky_mouse.png"},
{"name":"Minnie Mouse","pictureUrl":"images/minnie_mouse.png"},
{"name":"Pebbles Flintstone","pictureUrl":"images/pebbles_flintstone.png"},
{"name":"Peter Pan","pictureUrl":"images/peter_pan.png"},
{"name":"Pinocchio","pictureUrl":"images/pinocchio.png"},
{"name":"Pluto","pictureUrl":"images/pluto.png"},
{"name":"Simba","pictureUrl":"images/simba.png"},
{"name":"Snow White","pictureUrl":"images/snow_white.png"},
{"name":"Tigger","pictureUrl":"images/tigger.png"},
{"name":"Tinkerbell","pictureUrl":"images/tinkerbell.png"},
{"name":"Tweety","pictureUrl":"images/tweety.png"},
{"name":"Wilma Flintstone","pictureUrl":"images/wilma_flintstone.png"}]


Let’s build a simple console application. Fire up your Visual Studio 2015 and let’s get started.
  • File >> New >> Project
  • Templates >> Visual C# >> Console Application
  • Name the application WebApiConsoleClient
We need to create a class that closely matches the nature of the Web API JSON object. Therefore, add the following CartoonCharacter class to the console application project:

public class CartoonCharacter {
  public string Name { get; set; }
  public string PictureUrl { get; set; }
}


We need to install the We API Client libraries. To that end, execute the following command from within the Package Manager Console window in Visual Studio 2015:

Install-Package Microsoft.AspNet.WebApi.Client

We can use HttpClient to read CartoonCharacter instances from an HTTP response, without having to write a lot of deserialization code. Add the following global HttpClient declaration right above the Main() method in Program.cs.

static HttpClient client = new HttpClient();

Resolve the namespace for the HttpClient class.

It is necessary to access data from a Web API service asynchronously. Add the following method to Program.cs.

static async Task RunAsync() {
    client.BaseAddress = new Uri("
http://cartoonapi.azurewebsites.net");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    try {
        // Get all cartoon characters
        IEnumerable<CartoonCharacter> cartoonCharacters = null;
        HttpResponseMessage response = await client.GetAsync("/api/cartoon");
        if (response.IsSuccessStatusCode) {
            cartoonCharacters = response.Content.ReadAsAsync<IEnumerable<CartoonCharacter>>().Result;
        }

        foreach (var item in cartoonCharacters) {
            Console.WriteLine("Name: {0}\t Picture: {1}", item.Name, item.PictureUrl);
        }
    } catch (Exception e) {
        Console.WriteLine(e.Message);
    }

    Console.ReadLine();
}


In the above code, we first initialize the HttpClient instance with this code:

client.BaseAddress = new Uri("http://cartoonapi.azurewebsites.net");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


The above code sets the base URI for HTTP requests, and sets the Accept header to "application/json", which tells the server to send data in JSON format.

The following code sends a GET request for a  collection of CartoonCharacter instances:

IEnumerable<CartoonCharacter> cartoonCharacters = null;
HttpResponseMessage response = await client.GetAsync("/api/cartoon");
if (response.IsSuccessStatusCode) {
  cartoonCharacters = response.Content.ReadAsAsync<IEnumerable<CartoonCharacter>>().Result;
}


The GetAsync method sends the HTTP GET request. The method needs to be asynchronous, because it performs network I/O. When the method completes, it returns an HttpResponseMessage that contains the HTTP response. If the status code in the response is a success code, the response body contains the JSON representation of a collection of CartoonCharacter objects. Call ReadAsAsync to de-serialize the JSON payload to CartoonCharacter instances.

HttpClient does not throw an exception when the HTTP response contains an error code. Instead, the IsSuccessStatusCode property is false if the status is an error code.

Resolve all classes and do a quick compile to ensure that all is OK.

Add the following statement inside the Main() method to call our asynchronous RunAsync() method:

RunAsync().Wait();

Hit F5 to test your application. Your output should look like this:

image

You should be able to re-purpose the above code for reading from any other Web API service out there.

Reference:

https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

No comments:

Post a Comment