metro c# webapi client
Peter Daukintis
For my own purposes I wanted to create a test application which I can use as a test-bed to experiment with user interface aspects of Metro. I decided to create a simple REST web service and make create/read/update/delete type calls to it from a c# metro application. Pretty much the next step up from ‘Hello World’ for a web connected application.
First, to create the Web API choose ASP.NET MVC 4 Application from the New Project Dialog and in the ensuing dialog select WebApi. We are using the ASP.NET MVC 4 Beta which now includes the WebApi (http://www.asp.net/web-api); which was formerly known as WCF WebApi.
The template creates a ValuesController to expose the sample CRUD methods (GetCollection/Get/Post/Put/Delete). It uses a string as the payload so I’m going to change that to use a Person class.
{
static int idGen = 123456;
public Person()
{
Id = ++idGen;
}
public Person(Person other)
{
Id = other.Id;
Name = other.Name;
Occupation = other.Occupation;
}
public string Occupation { get; set; }
public string Name { get; set; }
public int Id { get; private set; }
}
Next, I renamed the ValuesController to PeopleController and modified the template code to query a list of Person objects:
{
private List<Person> _list = new List<Person>
{
new Person{ Name = "fred", Occupation = "plumber" },
new Person{ Name = "bob", Occupation = "lawyer" },
new Person{ Name = "flo", Occupation = "pilot" },
};
// GET /api/people
public IEnumerable<Person> Get()
{
return _list;
}
// GET /api/people/5
public Person Get(int id)
{
return _list.SingleOrDefault(p => p.Id == id);
}
// POST /api/people
public void Post(Person value)
{
_list.Add(value);
}
// PUT /api/people/5
public void Put(int id, Person value)
{
var item = _list.SingleOrDefault(p => p.Id == id);
if (item != null)
{
item.Name = value.Name;
item.Occupation = value.Occupation;
}
}
// DELETE /api/people/5
public void Delete(int id)
{
var item = _list.SingleOrDefault(p => p.Id == id);
if (item != null)
{
_list.Remove(item);
}
}
I’m not worried about the correctness or completeness of the http responses and behavior here as this post is about the client side of the code. Making the above code changes is enough to expose my RESTful api. For this example I an running the server on IISExpress on localhost – this enables me to test the GET calls using the browser by typing in http://localhost:60442/api/people to IE10 on the Desktop. (since web api returns JSON by default I made the modification to the registry described here http://stackoverflow.com/questions/2483771/how-can-i-convince-ie-to-simply-display-application-json-rather-than-offer-to-do to easily view the data coming back).
(I tested the other HTTP verbs using Fiddler by constructing requests by hand).
With that done it’s over to the Metro client.
I started with a blank c# Metro Style application and added a GridView to which I would bind my ViewModel (I tend to use the MVVM pattern). To support my MVVM architecture I rolled up a few helper classes; a DelegateCommand and a ViewModelBase class to provide INotifyPropertyChanged and an IsDesignMode property. The Expression Blend designer doesn’t work with network calls so the IsDesignMode property is used to facilitate design time data.
Next, I created some design-time data to enable me to design the ui in Blend
{
People = new ObservableCollection<Person>
{
new Person { Name = "design fred", Occupation = "Nurse" },
new Person { Name = "design bob", Occupation = "Artist" },
new Person { Name = "design flo", Occupation = "Teacher" },
new Person { Name = "design zak", Occupation = "Fireman" },
new Person { Name = "design rita", Occupation = "Nurse" },
};
}
Here’s how it looked in Blend:
With this out of the way I could get to the heart of the problem – making the client-side calls:
Starting with retrieving the initial list
var resp = await http.GetAsync(new Uri(apiRoot));
var stream = await resp.Content.ReadAsStreamAsync();
var djs = new DataContractJsonSerializer(typeof(List<Person>));
People = new ObservableCollection<Person>((IEnumerable<Person>)djs.ReadObject(stream));
stream.Dispose();
Then, Deleting a Person from the list
var resp = await http.DeleteAsync(new Uri(apiRoot + "/" + Selected.Id));
resp.EnsureSuccessStatusCode();
Then, editing and adding, which I implemented in the same function:
var djs = new DataContractJsonSerializer(typeof(Person));
var ms = new MemoryStream();
djs.WriteObject(ms, person);
ms.Position = 0;
var sc = new StreamContent(ms);
sc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var resp = original == null ?
await http.PostAsync(new Uri(apiRoot), sc) :
await http.PutAsync(new Uri(apiRoot + "/" + original.Id), sc);
ms.Dispose();
resp.EnsureSuccessStatusCode();
In order to invoke the CRUD commands I added an application bar and populated it with app bar command buttons which I data bound to ICommands exposed by the View Model.
One thing worth mentioning is that in order to edit the Person objects I needed some form of editor page. I wasn’t sure of the best Metro-Style way to implement it, but in the end I went for a modal dialog which looked similar to the built in message box.
I created this as a full screen UserControl.
The solution containing the web api project and the metro c# client is here https://skydrive.live.com/redir.aspx?cid=4f1b7368284539e5&resid=4F1B7368284539E5!442&parid=4F1B7368284539E5!123.
UPDATE: An update for the Release Preview is here http://sdrv.ms/N4kfZT
Comments