Consume ASP.Net Web API Via Windows Phone Using RestSharp

Table of Contents

  • Consume ASP.NET WEB API via Windows Phone using RestSharp
  • Abstract
  • Introduction
  • Pre-requisite
  • What services we will consume
  • Let's Start Creation of a Sample Project
  • Optional:Add support of HTTP client and JSON.NET
  • Add Support of RestSharp for Windows Phone
  • Create Layout:
    •  Create Application Title
    •  Calling a Web API
  • Getting output
  • Did you notice anything?
  • Conclusion
Abstract

This article explains how to consume an ASP.NET WEB API using RestSharp for Windows Phone.

Introduction

This article explains how to consume an ASP.NET WEB API using RestSharp Windows Phone. We will create a simple demo application to use simple RestFul services, already developed.

We will not develop any services in this article although we will use the services already developed. We will not cover Windows Phone features in details, the only thing we will explain is the display and usage of JSON data/response from our APIs.

Prerequisites

We need the following to proceed with this article:
  • Visual Studio 2013 or later with Windows Phone support (8.0 or later)
  • Basic knowledge of Windows Phone
  • Basic knowledge of ReSTFUL services
  • Basic knowledge of ASP.NET WEB API; we will consume the Web API, although we are not developing the same but we should have basic knowledge about these.
  • Any Rest Client; here we will use RestSharp for Windows Phone; there are other alternatives for use with a Microsoft HTTP Client to consume an ASP.NET WEB API
  • Basic knowledge of JSON
What services we will consume

In this article we will use our earlier created ASP.NET WEB API hosted here: http://crudwithwebapi.azurewebsites.net/

We will try to discuss very simple resources in this article. The following are the resources of our Web API:



Let's Start Creation of a Sample Project


Use the following procedure to create a sample project:
  • Start Visual Studio and select "File" -> "New" -> "Project..." (or enter Ctrl + Shift + N).
  • From Installed templates Visual C# -> Store Apps -> Windows Phone Apps -> Blank App (Windows Phone)



  • Provide a name to your new project, I called it ConsumeWebAPIInWindowsPhone to make it a self-explanatory name 
  • Just a note, I checked Add to source control since I will make this a GitHub repository
  • Now click on Ok
  • We will get a blank Windows Phone APP
  • Add the following XAML code to our MainPage.xaml file
  • Add the following code to our MainPage.xaml.cs file
  • Add a new class, ServerData.cs, under the Data Model folder and provide the following code:
  1. public class ServerData  
  2. {  
  3.    public int Id { getset; }  
  4.    public string InitialDate { getset; }  
  5.    public string EndDate { getset; }  
  6.    public int OrderNumber { getset; }  
  7.    public bool IsDirty { getset; }  
  8.    public string IP { getset; }  
  9.    public int Type { getset; }  
  10.    public int RecordIdentifier { getset; }  

Optional:Add support of HTTP client and JSON.NET

This section is optional and we are not using a HTTP client in our demo. If you are a fan of HTTP Clients then this section is for you, just read and make changes in your application accordingly.

We will consume ASP.NET Web APIs with a JSON response, so, we need both a HTTP client and JSON.NET (to serialize/deserialize our JSON data).
  • Open Nuget Managerment console and type following command:
  1. Install-Package Microsoft.Net.Http  
  2.   
  3. Install-Package Newtonsoft.Json  
 
Alternatively, you can use Nuget Dialog Windows to add support for both of the following things:





Add the following snippet into MainPage.xaml.cs:

  1. private async void GetServerData_HTTPClient(object sender, RoutedEventArgs e)  
  2. {  
  3.    try  
  4.    {  
  5.       using (HttpClient client = new HttpClient())  
  6.       {  
  7.          client.BaseAddress = new Uri("http://crudwithwebapi.azurewebsites.net");  
  8.          var url = "api/serverdata";  
  9.          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  10.          HttpResponseMessage response = await client.GetAsync(url);  
  11.          if (response.IsSuccessStatusCode)  
  12.          {  
  13.             var data = response.Content.ReadAsStringAsync();  
  14.             var lstData = JsonConvert.DeserializeObject<List<ServerData>>(data.Result.ToString());  
  15.             LstServerData.ItemsSource = lstData;  
  16.          }  
  17.       }  
  18.    }  
  19.    catch (Exception ex)  
  20.    {  
  21.        MessageBox.Show(ex.Message);  
  22.    }  
  23. }  
Add Support of RestSharp for Windows Phone

In this article, we will use RestSharp for Windows Phone, a ReST client. Let's add the same from Nuget:



Alternatively, type following command in Package Manager Console

  1. Install-Package RestSharp  

Now, we are ready to write a simple code to call our Web API.

Create Layout

Let's make it very simple, so, add the following XAML code to the MainPage.xaml file:
  1. <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  2.    <ListBox x:Name="LstServerData">  
  3.      <ListBox.ItemTemplate>  
  4.        <DataTemplate>  
  5.           <Grid Background="DarkOrange" Width="460" Height="150" Margin="0,10,0,0">  
  6.              <StackPanel  Orientation="Vertical">  
  7.                 <TextBlock Text="{Binding Title}" Foreground="Black" FontSize="30" Margin="10,10,0,0"/>  
  8.                 <TextBlock Text="{Binding Description}" FontSize="20" Margin="10,10,20,0" TextWrapping="Wrap"/>  
  9.              </StackPanel>  
  10.            </Grid>  
  11.        </DataTemplate>  
  12.       </ListBox.ItemTemplate>  
  13.    </ListBox>  
  14. </Grid> 
In the preceding code, we are just creating a ListBox using ItemTample of two TextBlocks to display our data in a vertical direction.

Create Application Title

Just add the following lines before the preceding snippet to make a descent Title for our application:
  1. <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">  
  2.     <TextBlock Text="Demo: Consume Web API" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>  
  3.     <TextBlock Text="Server Data" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>  
  4. </StackPanel> 
Calling a Web API

To ensure we are calling our Web API, we need a method to make a call. We want to make this demo as simple as possible, so I am not considering any patterns and programming principles, if you want to extend please try to use some SOLID Programming Principles. To learn more about SOLID Principles read this article: SOLID Programing Principles.

To make a call, just add the following snippet into the MainPage.xaml.cs file:
 
  1. private void GetServerData()   
  2. {  
  3.     const string url = "http://crudwithwebapi.azurewebsites.net";  
  4.     var client = new RestClient(url);  
  5.     var request = new RestRequest("api/serverdata", Method.GET)   
  6.     {  
  7.         RequestFormat = DataFormat.Json  
  8.     };  
  9.     client.ExecuteAsync < List < ServerData >> (request, response = >   
  10.     {  
  11.         LstServerData.ItemsSource = response.Data;  
  12.     });  
  13. }  
Here we are just defining an URL and a resource type (that is a GET in our case) and then we are making an Async call. I will not discuss that in details. If you want to learn about this, I recommend you read: Parallel Programing
We are done, now just invoke this method from our MainPage() by simply calling our method as shown below:
  1. public MainPage()  
  2. {  
  3.    InitializeComponent();  
  4.    GetServerData();    

We are ready to see the some awesome results on the Mobile.

Getting output


Just run the demo and you will get a decent Mobile Page in your Windows Phone Emulator:



We received the output and consumed our ASP.NET WEBAPI, we are done with our main topic. But, here I would like to direct your attention towards the output shown above.

Did you notice any thing?


At very first instance we did not make it in our notice but just take an another look. Ah! Here, we need to make some changes, our dates are not well formatted actually , we are displaying the date as it was received from our WEB API. These dates are of JSON and having UNIX format. Let us make them read-friendly.

We make DataType to DateTime from string and define our own format:
 
  1. public DateTime InitialDate { getset; }    
  2. public DateTime EndDate { getset; }   

  1. public String Description  
  2. {  
  3.    get  
  4.    {  
  5.       return string.Format("Start Date:{0}, End Date:{1}, Order Number:{2}, IP:{3}, Record Type:{4}",  
  6.           InitialDate.ToString("F"), EndDate.ToString("F"), OrderNumber, IP, Type);  
  7.    }  

And here we have a very good date format as:



Conclusion

This article explained how ro consume our ASP.NET WEB API using RestSharp for Windows Phone. We make async calls, did a bit of date formatting and reformatted the output.


Similar Articles