Telerik blogs

If you’ve been following along with the Conference Buddy series, you have seen that Jeff Fritz has developed a back-end WebAPI service to provide the Conference Buddy clients with conference data. This blog post will walk you through consuming this service to obtain Event data in JSON format for our Conference Buddy application.

Why JSON?

It is quite possible these days that some data will need to be consumed and provided by many different types of clients. These clients may consist of a mixture of mobile phones, web browsers, tablets and desktop computers. Conference Buddy falls into this category as it is being made available on the Windows Phone, Windows 8 Tablets as well as on the Windows desktop. An effective way to provide common data once, without resorting to duplication is to create a service layer over the data being provided. One type of service is called the RESTful service, it is meant to be lightweight and simple to use by issuing common HTTP verbs to interact with the data.

Verb Data Action
GET Select
POST Insert
PUT Update
DELETE Delete

 

ASP.NET WebAPI is a framework that provides a RESTful interface to your data. ASP.NET WebAPI gives clients the option of communicating data through XML or through JSON. In the case of Conference Buddy, the team of Evangelists have chosen to use JSON as it is more terse, and therefore more compact and issues smaller payloads across the wire. It also takes up less space when storing data locally to account for disconnected client scenarios. JSON data is also simple to work with as you will discover in this blog post.

Creating the Conference Buddy Data Access Layer

The first thing we will do is add a new C# class library project to our Conference Buddy solution, I’ve named the project “ConferenceBuddyLib”. Delete the Class1.cs class that is generated by default with the project template.

Getting some help from our friends

Now that we have the project setup, we will use the Library Package Manager (NuGet) to pull down a couple very useful libraries into the ConferenceBuddyLib project, these are:

  • Json.NET will assist us with the deserialization of the Json data obtained from the WebAPI service.
  • Microsoft .NET Framework 4 HTTP Client Libraries will simplify making the call to the WebAPI service.

Access NuGet by right-clicking on the ConferenceBuddyLib project and selecting “Manage NuGet Packages”, ensure the Online/NuGet official package source is selected and search for Json.NET, then click the Install button next to its entry.

JsonDotNet

Similarly, you will now search for HTTP Client, and click the Install button next to the Microsoft .NET Framework 4 HTTP Client Libraries.

HttpClient

Setting up our Model and Repository

The next thing that we will need is an Event model that coincides with the JSON being returned by the Conference Buddy WebAPI service. Add a new class to the ConferenceBuddyLib project called Event.cs and define it as follows:

using System;
using System.Linq;
 
namespace ConferenceBuddyLib
{
 public class Event
    {
 public int Id { get; set; }
 public string Name { get; set; }
 public string City { get; set; }
 public string State { get; set; }
 public string Country { get; set; }
 public DateTime StartDate { get; set; }
 public DateTime EndDate { get; set; }
 public int AttendeeCount { get; set; }
 public string TelerikEventCoordinator { get; set; }
 public string EventOrganizerName { get; set; }
 public string EventOrganizerEmail { get; set; }
 public string EventOrganizerPhone { get; set; }
 public bool IsTelerikSponsored { get; set; }
 public string SponsorshipLevel { get; set; }
 public bool HadBooth { get; set; }
 public string TelerikSpeakers { get; set; }
 public string Notes { get; set; }
 
    }
}

 

Now we will need a repository class that will be responsible for obtaining event data from the service, parsing and deserializing the JSON from the service and into our Event class. Add a new class to the ConferenceBuddyLib project called JsonEventsRepository.cs and define it as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Net.Http;
 
namespace ConferenceBuddyLib
{
 public class JsonEventsRepository
    {
 /// <summary>
 /// Parses a string of JSON into a List of Event objects
 /// </summary>
 /// <param name="json">JSON data to be parsed</param>
 /// <returns>List of Event objects</returns>
 public List<Event> LoadFromJson(string json)
        {
 return JsonConvert.DeserializeObject(json, typeof(List<Event>)) as List<Event>;
        }
 
 /// <summary>
 /// Reads a file located at specific path and parses the text into a List of Event
 /// </summary>
 /// <param name="path">Path to the file</param>
 /// <returns>List of Event objects</returns>
 public List<Event> LoadJsonFromFile(string path)
        {
 string json = System.IO.File.ReadAllText(path);
 return LoadFromJson(json);
        }
 
 /// <summary>
 /// Read JSON data from a WebAPI endpoint and parse it into a List of Event
 /// </summary>
 /// <param name="uri">Uri of the WebAPI service</param>
 /// <returns>List of Event objects</returns>
 public List<Event> LoadJsonFromWebApi(string uri)
        {
           HttpClient apiClient = new HttpClient();
           HttpResponseMessage response = apiClient.GetAsync(uri).Result;
           List<Event> events = LoadFromJson(response.Content.ReadAsStringAsync().Result);
 return events;
        }
    }
}

 

Using the Events Repository from the WinForms Conference Buddy Client

In order to use the Events repository in our Conference Buddy Client application, we will need to add a solution reference to the class library that we just created. For now, let’s be sure that our call out to the service works. Open the code view of CoreForm and in the load event, add the following code to initialize our Events repository and make the call out to the Conference Buddy WebAPI service and obtain a list of events. Finally we will display a message box to verify that data has indeed been retrieved from the service:

ConferenceBuddyLib.JsonEventsRepository repo = new ConferenceBuddyLib.JsonEventsRepository();
List<Event> events = repo.LoadJsonFromWebApi(@"http://<YOURURL>/api/Events");
MessageBox.Show(events[0].Name);

 

codemash

Summary

In this blog post we added a class library to the Conference Buddy solution to assist us in retrieving data from the ASP.NET WebAPI back-end web service. We saw how easy it was to call and consume this service using the Json.NET and .NET HTTP Client libraries obtained from NuGet, and we verified the retrieval of data by displaying a message box in our Conference Buddy client application.

In the next blog post, we will put the Event data to good use and display it in our application using Live Tiles and RadPanorama.

DOWNLOAD SOURCE

Please note the source code download contains a JSON file with Event information as you may or may not have the Conference Buddy WebAPI services running on your machine, the ability to read JSON from a file has also been provided in the JsonEventsRepository class.

Download RadControls for WinForms by Telerik


About the Author

Carey Payette

Carey Payette is a Senior Software Engineer with Trillium Innovations (a Solliance partner), an ASPInsider, a Progress Ninja, a Microsoft Certified Trainer and a Microsoft Azure MVP. Her primary focus is cloud integration and deployment for the web, mobile, big data, AI, machine learning and IoT spaces. Always eager to learn, she regularly tinkers with various sensors, microcontrollers, programming languages and frameworks. Carey is also a wife and mom to three fabulous boys.

Comments

Comments are disabled in preview mode.