Blog Moved

My blog has moved!

https://kmack.azurewebsites.net

Friday, February 28, 2014

Web API, or Cutting out the middle man

Ok, so I’m back with another blog post.  Tonight I sit here, with the wife and the munchkin passed out and am taking this singular opportunity to catch up on the Blacklist and thinking about the latest blog post.  And then it hit me, Web API.

This past week I’ve been doing a lot of reading and research into Web API, and I have to say I’m impressed with how completely flexible it is, and the overall possibilities it opens up.

All of us as Web developers have been tasked whether we like it or not with working towards a common goal….RIA.  Or Rich Internet Applications.  The challenge is that despite the Web being a disconnected model, to make the user feel like its not. 

I have to admit that Web API, is a technology that quickly and simply allows us developers to work towards that by allowing a new way of sending data back and forth between the client and the server without needing a postback of the page, in any capacity.

In short, Web API functions a lot like Raymond Reddington, it transmit and utilizes information in a way that cuts through all the red tape.  In the show, thanks to underworld connections, Reddington is able to trade back and forth information without having to go through proper channels that the FBI has to. 

Reddington

My job is to deal in information…all kinds. 

But analogies aside, Web API utilizes a special type of controller to allow the ability to sending and receiving information. 

In MVC, the controller is used to route requests from the server to the client.  It traditionally is used to send requests to the server for specific views, and allowing the server to send back the appropriate view after performing any server side functions. 

In Web API, controllers function largely in the same way.  They allow calls too be made to the server, those requests are processed and responses are sent back.  The key difference is though that Web API does it without having to be weighed down by views and models and instead is primarily concerned with passing data.

Enough Theory though, let’s look at the code.

When you create a new project in Visual Studio 2013, thanks to Project Katana there is now only an “ASP.NET Web Application”.  When you do, you will receive the following prompt.

image

When your project is created, you are given the option, no matter what type of application you create to add “WebForms”, “MVC”, and / or “Web API”.  For this project We are going to select “MVC”, and “Web API”.

Now, if you look at your Solution Explorer, you will notice that several key folders and classes have been created for you.

image

First and foremost, I’m going to create a basic MVC Controller and view to display a page.  Below you will see our Home Controller.

   1:  public class HomeController : Controller
   2:      {
   3:          //
   4:          // GET: /Home/
   5:          public ActionResult Index()
   6:          {
   7:              return View();
   8:          }
   9:      }



Just a simple controller that is going to render a view, that’s it.  Nothing special, after all this blog post is about Web API not MVC.  I also will be creating a view for this “Index” action, called “Index.cshtml”.  Below is the view.


   1:  <!DOCTYPE html>
   2:   
   3:  <html>
   4:  <head>
   5:      <meta name="viewport" content="width=device-width" />
   6:      <title>Index</title>
   7:  </head>
   8:  <body>
   9:      <div> 
  10:      </div>
  11:  </body>
  12:  </html>



Ok, now for the fun part.  We are going to build an Web API controller that is going to add two numbers together.  I know ground breaking stuff, but for right now I’m just trying to show the basics, watch this space for more advanced later. 


To start, right click on “Controllers” and select “Add Controller”.  After doing so, you will be prompted with the following menu:


image


We are going to select a “Web API 2 Controller – Empty”.  Given that are creating a very basic Web API controller, this will suit our purposes.  But it’s worth noting that you do have the option to create Web API controllers that are already set up with Scaffolding for Entity Framework or Read / Write actions.


We are going to name our controller “MathController”, and set it up as follows:


   1:  public class MathController : ApiController
   2:      {
   3:          public int AddNumbers(int number1, int number2)
   4:          {
   5:              int answer = number1 + number2;
   6:              return answer;
   7:          }
   8:      }



We have a single action that is called “Get”, and allow for passing two numbers and returning an integer amount. 


Now, the next step is that one I find most people miss.  For Web API to work, we need to set up routing for this controller.  For MVC controllers we don’t need to do this because it is already done for us.  But because we have a lot more flexibility with Web API we need to tell the application how to handle it’s routing.


In the “App_Start” folder, you will see a file called “WebApiConfig.cs”.  By default, Visual Studio created the most basic routing I’ve ever seen.  We are going to add an additional route to this file so it looks like the following:


   1:  public static void Register(HttpConfiguration config)
   2:          {
   3:              // Web API configuration and services
   4:   
   5:              // Web API routes
   6:              config.MapHttpAttributeRoutes();
   7:   
   8:              config.Routes.MapHttpRoute(
   9:                  name: "DefaultApi",
  10:                  routeTemplate: "api/{controller}/{id}",
  11:                  defaults: new { id = RouteParameter.Optional }
  12:              );
  13:   
  14:              config.Routes.MapHttpRoute(
  15:   
  16:                  name: "MathApi",
  17:                  routeTemplate: "api/{controller}/{number1}/{number2}"
  18:                  );
  19:          }



Notice the placeholders we defined, denoting the controller and numbers needed.  The next step now is building the client side script to call it.  That script is shown below:


   1:  <script type="text/javascript">
   2:          function AddNumbers()
   3:          {
   4:              var num1 = $("#number1").val();
   5:              
   6:              var num2 = $("#number2").val();
   7:              
   8:              $.ajax({
   9:                  url: 'http://localhost:50008/api/math/' + num1 + '/' + num2,
  10:                  type: 'Get',
  11:                  dataType: 'json',
  12:                  success: function (data) {
  13:                      $("#divAnswer").html("The answer is " + data);
  14:                  }
  15:              });
  16:          }
  17:      </script>



Now, when you run this, you get the followiing:


image


Ok, so that’s well and great.  And Holy-No-Postback-Batman.


Batman66


Great Scott!


So, I know some of you are saying that you could just have easily built that into your MVC controller using a JSON response, and you’d be right.  The benefits of Web API controllers are really as follows in my experience:



  • Separation of Concerns:  We as programmers strive to separate our classes to have a singular concern, so that they are easier to manage, easier to follow, and easier to test and maintain.  Arguably by using the MVC controller for these types of requests you are mixing navigation concerns with Business / Data Concerns.  By separating your concerns you are making more testable code, and eliminating the possibility that changes to the navigation of your site affects how data is passed to the client.
  • More versatile:  Because we are using a custom controller we are not bound by the rules of how an MVC controller functions and can set this up to work differently.
  • Easy integration with other platforms:  Web API controllers are using HttpRequests to pass data, and all major platforms and languages can use those requests.  So by separating your logic to Web API, I can have my views, iPhone, iPad, and other platforms use the same services with minimal effort for installation. 

Well that’s it for me, like I said this was an intro blog post looking at web api, watch this space for more posts on thsis topic. 

Friday, February 21, 2014

Where’s my service…Service Locator Pattern

Design patterns are one thing that none of us can escape.  If you work in the software development industry and as a part of a team, then odds are that you have run into design patterns. 

When you boil it down, a design pattern is a approach to coding that solves a specific problem.  These patterns are great because they make it possible for other developers to immediately see our code and have some idea of the underlying architecture to it.

Today I'm going to be talking about a newer design pattern, one that I have been using a lot recently and offers several advantages to help decouple your code and build it in a way that separates layers and uses interfaces to remove dependencies...the service locator pattern.

 

What is a Service Locator Pattern Anyway?

A Service Locator pattern essentially when you boil it down is like a pharmacist.  Think about this, when you go to the pharmacist you take a prescription from the doctor of what you need, and you give it to the pharmacist, and based on that script they will give you back the drug on the script, or something that fits the same bill. 

A service locator utilizes an interface in the same way.  You tell it an interface that your interested in, and it returns a concrete class that implements that interface.

Below is an example of a service locator class, this class is usually implemented as a singleton, and serves as the only way that a concrete class can be called.

   1: public interface IServiceLocator
   2:     {
   3:         T GetService<T>();
   4:     }
   5:  
   6:     public class ServiceLocator : IServiceLocator
   7:     {
   8:         private IDictionary<object, object> services;
   9:  
  10:         public ServiceLocator()
  11:         {
  12:             services = new Dictionary<object, object>();
  13:  
  14:             //Add Interface to class references here for repositories
  15:             
  16:         }
  17:  
  18:         public T GetService<T>()
  19:         {
  20:             try
  21:             {
  22:                 return (T)services[typeof(T)];
  23:             }
  24:             catch (KeyNotFoundException)
  25:             {
  26:                 throw new ApplicationException("The requested service is not registered");
  27:             }
  28:         }
  29:     }

Specifically, a service locator operates on the principle of Inversion of Control.  Which is a development technique that over the past few years has gained a lot of traction.  You could do a whole article series on inversion of control, but can find a great article here.

For our purposes, Inversion of Control refers to the concept that instead of the class making the call deciding what it needs, it instead relies on a different construct to provide the concrete implementations of interfaces.

The key to the ServiceLocator class is that it maintains a dictionary listing of the interfaces and the matching classes that implement that interface.  This dictionary is loaded at line 14 above. 

 

Here’s an example:


Now, all of this is well and good but let’s look at some examples.  Let’s say we have an application that handles grading for a school.  And in that application we have the following code.



   1: public interface IGrade
   2:     {
   3:         int PointsPossible { get; set; }
   4:         int PointsEarned { get; set; }
   5:         decimal Percentage { get; set; }
   6:         string LetterGrade { get; set; }
   7:         void CalculateGrade();
   8:         string GradeType { get; set; }
   9:     }
  10:  
  11:     public class Assignment : IGrade
  12:     {
  13:         public int PointsPossible { get; set; }
  14:         public int PointsEarned { get; set; }
  15:         public decimal Percentage { get; set; }
  16:         public string LetterGrade { get; set; }
  17:         public string GradeType { get; set; }
  18:  
  19:         public Assignment()
  20:         {
  21:             GradeType = "Assignment";
  22:         }
  23:  
  24:         public void CalculateGrade()
  25:         {
  26:             Percentage = PointsEarned / PointsPossible;
  27:             if (Percentage >= 90)
  28:             {
  29:                 LetterGrade = "A";
  30:             }
  31:             else if (Percentage >= 80)
  32:             {
  33:                 LetterGrade = "B";
  34:             }
  35:             else if (Percentage >= 70)
  36:             {
  37:                 LetterGrade = "C";
  38:             }
  39:             else if (Percentage >= 60)
  40:             {
  41:                 LetterGrade = "D";
  42:             }
  43:             else
  44:             {
  45:                 LetterGrade = "F";
  46:             }
  47:         }
  48:     }

The IGrade interface, provides an generic version of what ever grade is made up of.  The Assignment class, implements those methods, in addition to providing functionality specific to an exam. 

In our service locator, the class would look as follows:



   1: public interface IServiceLocator
   2:     {
   3:         T GetService<T>();
   4:     }
   5:  
   6:     public class ServiceLocator : IServiceLocator
   7:     {
   8:         private IDictionary<object, object> services;
   9:  
  10:         public ServiceLocator()
  11:         {
  12:             services = new Dictionary<object, object>();
  13:  
  14:             //Add Interface to class references here for repositories
  15:             services.Add(typeof(IGrade), new Assignment());
  16:         }
  17:  
  18:         public T GetService<T>()
  19:         {
  20:             try
  21:             {
  22:                 return (T)services[typeof(T)];
  23:             }
  24:             catch (KeyNotFoundException)
  25:             {
  26:                 throw new ApplicationException("The requested service is not registered");
  27:             }
  28:         }
  29:     }

Notice that we added a single line showing the interface, adding to the dictionary an instance of the Interface, with the value being a new instance of the class. 

Now, let’s  say we have a page that allows us to add assignments, that save method would look like this.



   1: public void AddGrade(int pointsPossible, int pointsEarned)
   2:         {
   3:             IServiceLocator locator = new ServiceLocator();
   4:             IGrade grade = locator.GetService<IGrade>();
   5:  
   6:             grade.PointsEarned = pointsEarned;
   7:             grade.PointsPossible = pointsPossible;
   8:             grade.CalculateGrade();
   9:         }

Notice that our method makes no reference to the assignment class, or anything outside of the interface that it needs.  This allows us flexibility in that if I want to replace assignment, with Exam, I can do so within the service locator, and have it carry through the entire application. 

Why Do We Care?


The benefit of using this approach is that it makes your code more flexible and allows you to swap out old classes for new as requirements change.  This allows you to update your application in a way that minimizes the impact to the rest of the application.


Additionally, this can help with testability, because now using a Fakes Assembly, or just a different Service Locator, I can swap out my application classes for testing classes in my test project.


Service Locator is a valuable tool when applied appropriately and should be consider as a way to reduce dependencies and coupling in your applications.