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 detail. The only thing we are going to discuss about the display and usage of JSON data/response from our APIs.

Prerequisite

We need 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 we are going to consume?

In this article/post 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 post. Following is the resources of our Web API:

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 (We used ConsumeWebAPIInWindowsPhone to make it self-explanatory name)
  • Just a note, check Add to source control as we are going to make this a GitHub repository
  • Now click on OK
  • We will get a blank Windows Phone App
  • Add following XAML code to our MainPage.xaml file
  • Add following code to our MainPage.xaml.cs file
  • Add new class ServerData.cs under Data Model folder and write following code:
01.public class ServerData
02.    {
03.        public int Id { get; set; }
04.        public string InitialDate { get; set; }
05.        public string EndDate { get; set; }
06.        public int OrderNumber { get; set; }
07.        public bool IsDirty { get; set; }
08.        public string IP { get; set; }
09.        public int Type { get; set; }
10.        public int RecordIdentifier { get; set; }
11.    }

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 then this section is for you. 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 Managerment Console and type following command:
1.Install-Package Microsoft.Net.Http
2. 
3.Install-Package Newtonsoft.Json

Alternatively, you can use NuGet Dialog Window to add support for both things:

Add the following snippet in MainPage.xaml.cs:

01.private async void GetServerData_HTTPClient(object sender, RoutedEventArgs e)
02. 
03.        {
04. 
05.            try
06. 
07.            {
08. 
09.                using (HttpClient client = new HttpClient())
10. 
11.                {
12. 
13.                    client.BaseAddress = new Uri("http://crudwithwebapi.azurewebsites.net");
14. 
15.                    var url = "api/serverdata";
16. 
17.                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
18. 
19.                    HttpResponseMessage response = await client.GetAsync(url);
20. 
21.                    if (response.IsSuccessStatusCode)
22. 
23.                    {
24. 
25.                        var data = response.Content.ReadAsStringAsync();
26. 
27.                        var lstData = JsonConvert.DeserializeObject<List<ServerData>>(data.Result.ToString());
28. 
29.                        LstServerData.ItemsSource = lstData;
30. 
31.                    }
32. 
33.                    }
34. 
35.            }
36. 
37.            catch (Exception ex)
38. 
39.            {
40. 
41.                MessageBox.Show(ex.Message);
42. 
43.            }
44. 
45.        }

Add Support of RestSharp for Windows Phone

In this post/article, we are going to use RestSharp for Windows Phone a ReST client. Lets add the same from NuGet:

Alternatively, type 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. Add following XAML code in MainPage.xaml file:

01.<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
02. 
03.            <ListBox x:Name="LstServerData">
04. 
05.                <ListBox.ItemTemplate>
06. 
07.                    <DataTemplate>
08. 
09.                        <Grid Background="DarkOrange" Width="460" Height="150" Margin="0,10,0,0">
10. 
11.                            <StackPanel  Orientation="Vertical">
12. 
13.                                <TextBlock Text="{Binding Title}" Foreground="Black" FontSize="30" Margin="10,10,0,0"/>
14. 
15.                                <TextBlock Text="{Binding Description}" FontSize="20" Margin="10,10,20,0" TextWrapping="Wrap"/>
16. 
17.                            </StackPanel>
18. 
19.                        </Grid>
20. 
21.                    </DataTemplate>
22. 
23.                </ListBox.ItemTemplate>
24. 
25.            </ListBox>
26. 
27.        </Grid>
  

In above, code we are just creating a ListBox using ItemTample of two TextBlocks to display our data in vertical direction.

Create Application Title

Just add following lines before above snippet to make a decent title for our application:

1.<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
2. 
3.            <TextBlock Text="Demo: Consume Web API" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
4. 
5.            <TextBlock Text="Server Data" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
6. 
7.</StackPanel>

Calling a Web API

To make sure 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 we will not consider 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:

01.private void GetServerData()
02. 
03.        {
04. 
05.            const string url = "http://crudwithwebapi.azurewebsites.net";
06. 
07.            var client = new RestClient(url);
08. 
09.            var request = new RestRequest("api/serverdata", Method.GET) { RequestFormat = DataFormat.Json };
10. 
11.            client.ExecuteAsync<List<ServerData>>(request, response =>
12. 
13.            {
14. 
15.                LstServerData.ItemsSource = response.Data;
16. 
17.            });
18. 
19.        }

Here we are just defining a URL and a resource type which is a GET in our case and then we are making an Async call. We are not going to discuss in detail about this. If you want to know about this, I recommend read this: Parallel Programming

We are done. Now just invoke this method from our MainPage() to simply call our method as shown below:

01.public MainPage()
02. 
03.        {
04. 
05.            InitializeComponent();
06. 
07.            GetServerData();
08. 
09.        }

Ready to see the 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 WEB API. We are done with our main topic. But, here we would like to take your attention towards output shown above.

Observations

At very first instance we did not 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 JSON and having UNIX format. Let's make them read-friendly.

We make DataType to DateTime from string and define our own format:

01.public DateTime InitialDate { get; set; }
02. 
03.public DateTime EndDate { get; set; }
04. 
05.public String Description
06. 
07.        {
08. 
09.            get
10. 
11.            {
12. 
13.                return string.Format("Start Date:{0}, End Date:{1}, Order Number:{2}, IP:{3}, Record Type:{4}",
14. 
15.                    InitialDate.ToString("F"), EndDate.ToString("F"), OrderNumber, IP, Type);
16. 
17.            }
18. 
19.        }

And here we have a very good date format:

Other languages

This wiki article is also available in following langauges: