Contents
Abstract
In this article, we will discuss all about how to consume ASP.NET WEB API using RestSharp
for Windows Phone.
Introduction
In this article, we will discuss all about how to consume ASP.NET WEB API using RestSharp Windows Phone. We will create a simple demo application to use a simple RESTFul
services, already developed.
We are not going to develop any services in this post although we will use the services already developed. We will not cover Windows Phone features in details, the only thing we are going to discuss is about the display and usage of JSON
data/response from our APIs.
Pre-requisite
We need the following to go with this article/post:
- 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 are going to consume 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 with the use of Microsoft HTTP Client to consume ASP.NET WEB API.
- Basic knowledge of JSON
What Services Are We Going to Consume?
In this article/post, we will use our earlier created ASP.NET WEB API hosted at http://crudwithwebapi.azurewebsites.net/.
We will try to discuss very simple resources in this post. Following are the resources of our Web API:
Action |
HTTP method |
Relative URI |
Get a list of serverdata |
GET |
/api/serverdata |
Get a serverdata by ID |
GET |
/api/serverdata/id |
Get serverdata by datatype |
GET |
/api/serverdata/type/datatype |
Get serverdata by machine IP |
GET |
/api/serverdata/ip/ip |
Create a fresh serverdata |
POST |
/api/serverdata |
Update an existing serverdata |
PUT |
/api/serverdata/id |
Delete an existing serverdata |
DELETE |
/api/serverdata/id |
Let's Start Creation of a Sample Project
Follow these steps 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)
- Give 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 I am going to make this a GitHub repository
- Now click on Ok
- We will get a blank Windows Phone APP
- Add the following XAML code to our xaml file
- Add the following code to our xaml.cs file
- Add new class ServerData.cs under Data Model folder and write the following code:
public class ServerData
{
public int Id { get; set; }
public string InitialDate { get; set; }
public string EndDate { get; set; }
public int OrderNumber { get; set; }
public bool IsDirty { get; set; }
public string IP { get; set; }
public int Type { get; set; }
public int RecordIdentifier { get; set; }
}
Optional: Add Support of HTTP Client and JSON.NET
This section is optional and we are not using HTTP client in our demo. If you are a fan of HTTP Client, this section is for you to just read and make changes in your application accordingly.
We are going to consume ASP.NET Web APIs with a JSON response, so, we need both HTTP client and JSON.NET (to serialize/deserialize our JSON data).
- Open Nuget Management console and type the following command:
Install-Package Microsoft.Net.Http
Install-Package Newtonsoft.Json
Alternatively, you can use Nuget Dialog Windows to add support for both things:
Add the following snippet in MainPage.xaml.cs:
private async void GetServerData_HTTPClient(object sender, RoutedEventArgs e)
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://crudwithwebapi.azurewebsites.net");
var url = "api/serverdata";
client.DefaultRequestHeaders.Accept.Add
(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsStringAsync();
var lstData = JsonConvert.DeserializeObject<List&
lt;ServerData>>(data.Result.ToString());
LstServerData.ItemsSource = lstData;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Add Support of RestSharp for Windows Phone
In this article, we are going to use RestSharp for Windows Phone a ReST client. Let's add the same from Nuget:
Alternatively, type the following command in Package Manager Console.
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 in MainPage.xaml file.
<Grid x:Name="ContentPanel"
Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="LstServerData">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="DarkOrange" Width="460"
Height="150" Margin="0,10,0,0">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Title}" Foreground="Black"
FontSize="30" Margin="10,10,0,0"/>
<TextBlock Text="{Binding Description}" FontSize="20"
Margin="10,10,20,0" TextWrapping="Wrap"/>
</StackPanel>
In the above code, we are just creating a ListBox
using ItemTemplate
of two TextBlock
s to display our data in vertical direction.
Create Application Title
Just add the following lines before the above snippet to make a decent Title for our application:
<StackPanel x:Name="TitlePanel"
Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Demo: Consume Web API"
Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="Server Data"
Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
Calling a Web API
To make ensure that 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 put some SOLID Programming Principles. To know more about SOLID Principles, read this article: SOLID Programing Principles.
To make a call, just add the following snippet into MainPage.xaml.cs file:
private void GetServerData()
{
const string url = "http://crudwithwebapi.azurewebsites.net";
var client = new RestClient(url);
var request = new RestRequest("api/serverdata",
Method.GET) { RequestFormat = DataFormat.Json };
client.ExecuteAsync<List<ServerData>>(request, response =>
{
LstServerData.ItemsSource = response.Data;
});
}
Here, we are just defining url and a resource type which is a GET
in our case and then we are making an Async call. I am not going to discuss in detail about this. If you want to know more, I recommend you read Parallel Programming.
We are done, now just invoke this method from our MainPage()
simply call our method as shown below:
public MainPage()
{
InitializeComponent();
GetServerData();
}
Ready to see some awesome results on 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 draw your attention towards the output shown above.
Did You Notice Anything?
At the 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 we received from our WEB API. These dates are of JSON and having UNIX format. Let's make them read-friendly.
We make DataType
to DateTime
from string
and define our own format:
public String Description
{
get
{
return string.Format("Start Date:{0}, End Date:{1},
Order Number:{2}, IP:{3}, Record Type:{4}",
InitialDate.ToString("F"),
EndDate.ToString("F"), OrderNumber, IP, Type);
}
}
And here, we have a very good date format as:
Conclusion
In this post, we discussed all about how to consume our ASP.NET WEB API using RestSharp for Windows Phone. We made async calls, did a bit of date formatting, reformatted our output.