Hopefully you have had a chance to take a look at Part 1 to see how to the use the App Orchestration API using webforms. In this next part of the series we will look at doing the same thing, but this time using MVC. MVC is the latest and greatest ASP technology from Microsoft, blending C#/VB language syntax with basic HTML elements. Things look much cleaner and are easier to manage in MVC then the old school webforms. It is about as good as you can get using server side scripting.(If you don’t leave the Microsoft umbrella. :))

The project I created was using Visual Studio 2012 using MVC 4. Visual Studio has a nice out of the box project that uses integrated Windows Authentication. This lets us demostrate another way to access the API – the ImplictAuthContext. I just added the ApiContext into my HomeController, but in a more complex example you would want to store this seperately and then access it from a base controller class so you don’t constantly setup and tear down the context with each controller initialization.

Let’s take a look at the code for this:

public virtual async Task<ActionResult> Index()
        {
            ApiContext = new ImplicitAuthContext(DefaultApiServiceAddress); 

            var global = ApiContext.GlobalSettings.Get();
            ViewBag.Message = string.Format("Are we licensed? {0}", global.IsLicensed);

Notice a couple of things here:

  1. The async keyword. The API allows you take advantage of this new .Net feature and make calls to asynchronously. (More on this in a moment.)
  2. You can store results in the viewbag and then display them on the view. Here I show a simple query to check the licensing state of App Orchestration. You never want to be unlicensed, right? 🙂
  3. That is all you need with the implicit method – a one line simple call. We store it in a property of the controller.

In the webforms example we got the offerings and data bound them to a repeater. In MVC, we query them and save them in a model for display.

Here is the query. You see it is using async. After waiting for the results, I then massage the data out of the query into my specific model using LINQ.

var offeringsTask = ApiContext.Offerings.GetAsync();
var offerings = (await offeringsTask).ToList();

var offeringModels = (from offering in offerings
                      select new OfferingModel
                      {
                           Id = offering.Id,
                           Name = offering.Name,
                           IconUrl = Url.LargeIconUrl(offering.Icon.Id),
                      }).OrderBy(ad => ad.Name);

var model = new HomeModel
            {
                 Offerings = offeringModels.ToList(),
            };

return View(model);

Here are the models for reference:
    public class OfferingModel
    {
        public string Id { get; set; }
        public string IconUrl { get; set; }
        public string Name { get; set; }
    }

    public class HomeModel
    {
        public List<OfferingModel> Offerings { get; set; }
    }


Here is all the code you need in the cshtml page to display the offerings:
<table width="100%" id="tblOfferings">
    <tbody>
        <tr>
            <th style="text-align: left; width: 5%">Offering</th>
            <th style="text-align: left; width: 95%"></th>
        </tr>
        @foreach (var offering in Model.Offerings)
        {
            <tr class="" id="trd">
                <td>
                    <img src="@offering.IconUrl"/>
                </td>
                <td id="@offering.Id">
                    <label style="vertical-align:middle; text-align: left;">@offering.Name</label>
                </td>        
            </tr>
        } 
    </tbody>
</table>

And it will look like this, just the same as the webforms example:

The MVC syntax makes doing the table much easier and it almost looks like good old HTML.

The way we do the icons is not that much different, but it is easier and simpler. First there is this nice helper class that builds up the urls to get the icon images.

    public static class UrlHelperExtensions
    {
        public static string LargeIconUrl(this UrlHelper urlHelper, Guid? id)
        {
            return urlHelper.Action("GetIcon", "Home", new {id, width = 32, height = 32});
        }

        public static string LargeIconUrl(this UrlHelper urlHelper, string id)
        {
            return urlHelper.Action("GetIcon", "Home", new { id, width = 32, height = 32 });
        }
    }

Then we have the typical method that returns the actual bits of the image. (This is pretty much the same as the webforms example but you can build it directly into your controller. However, you might want this to be a separate controller in a real world example to isolate concerns.)
        [OutputCache(Duration = Int32.MaxValue)] // Cache forever
        public virtual async Task<ActionResult> GetIcon(string id, int? width, int? height)
        {
            try
            {
                var icon = await ApiContext.Icons.GetByIdAsync(id, IconFormat.Png, width ?? 32, height ?? 32);
                return File(Convert.FromBase64String(icon.DataBase64), "image/png");
            }
            catch (Exception e)
            {
                Trace.TraceError("Error getting Icon message: {0}", e.Message);
                return new EmptyResult();
            }
        }

That is it. This project ended up with less code, was easier to read and followed some of the latest server side techniques. In Part 3 we will evolve this example to not use server side processing but instead use knockout and Ajax queries to get the data. Stay tuned!