Wednesday, January 22, 2014

HTTP Error 405 When Making a PUT or DELETE Call to Web API Service

If you build ASP.NET Web API services and are testing against IIS, you might encounter the following error when trying to execute a HTTP PUT or DELETE:
Error Summary:

HTTP Error 405.0 - Method Not Allowed

The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.

Searching the web actually yielded a ton of results but as usual they were wide and plentiful making it difficult to discern the correct solution. I'm using VS.NET 2012 and VS.NET 2013 on Windows 7 and Windows 8 (variations of these), so this solution is current.

Here it is: a combination of updating the values for a few of the HTTP Handlers and modules in the web.config will solve this issue. 1st the solution, which resides within the <system.webServer> section within the web.config file for the Web API project:

  <validation validateIntegratedModeConfiguration="false" />
  <remove name="WebDAVModule" />
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

The explanation:

  1. The default ExtensionlessUrlHandler-* handlers displayed above are set within the %userprofile%\documents\iisexpress\config\applicationhost.config file and do not by default allow HTTP PUT and DELETE verbs. By removing and re-adding the handlers with all of the HTTP verbs we will allow, processing will continue as expected.
  2. Unfortunately updating the handlers is not enough. The WebDAV HTTP Publishing feature will block HTTP PUT and DELETE calls regardless of our previous modifications. WebDAV is a feature allowing access to files and folders via the internet as an alternative to FTP. If you are not using it in the Web API project, then removing the module will free up the restriction on these HTTP verbs. If you want to read more about what WebDAV is, please read this.
After these modifications have been made try using Fiddler or Postman and make a HTTP PUT or DELETE call and it should now work as expected. If you are reading this and are using a HTTP POST for all operations and bypassing a good RESTful design by having multiple POST actions on a controller (only distinguished by the action name in the URL as opposed to the verb defining the route), reconsider and try these modifications if in their absence had previously prevented you from creating that rich RESTful service you initially set out to make.

Tuesday, January 7, 2014

Creating a Unit Test Using Moq to Stub Out Dependencies

One of the main powers behind a mocking framework like 'Moq' for use with unit testing is the ability to write true unit tests as opposed to integration tests. Remember unit tests should run quickly and provide quick validation of the code being tested. They should be free of using external dependencies and rather focus on testing the code at hand. Examples of these dependencies could be a database, web service, 3rd party component, network share, file, etc..

If all of your unit tests were actually integration tests, it could potentially be lengthy to call and test, and even more challenging to configure. What if you are developing offline and that web service is not available? Should you then not be able to test your code? The answer of course is 'no' you should still be able to test your code.

Use of a mocking framework like Moq allows us to stub out these dependencies with expected behavior, thus allowing the code to be tested independent of the actual integration with that dependency. The primary example of this would be to stub out data access calls that would normally at runtime actually call the database.

The following example relies on the Repository pattern and an Interface provided with the calls that would be implemented to reach out to the database. This abstraction allows Moq to substitute the implementation and behavior to a predetermined expectation for our unit test. If you happen to already be using the Repository pattern but not unit testing, you should be able to fit the code below after understanding it into your solution to being building up some unit tests.

Here is the Repository Interface we are working with for the example:
public interface IRepository<T> where T : class 
  IList<T> GetAll();

Here is the implemented Repository class. There is a lot more abstraction we could do to the Repository in addition to using the UnitOfWork pattern, but the focus here is on the unit test so this is a basic implementation:

public class PersonRepository : IRepository<Person>
  private AdventureWorksEntities db = new AdventureWorksEntities();

  public IList<Person> GetAll()
     var people = from p in db.People
                  select p;

     return people.ToList();

In this test project I used Entity Framework and connected it to the 'AdventureWorks' database. I expanded on the Person POCO and added an arbitrary method that would find an employee by 1st and last name. In reality a method like this would probably be on a generic repository that takes an expression as the parameter, but again the focus here is to show how we can unit test this method that uses the Repository without actually calling the database. Here is the Partial Class I added with the 'GetPersonByName' method:

public partial class Person
  private readonly IRepository<Person> personRepository;

  public Person(IRepository<Person> personRepository)
    this.personRepository = personRepository;

  public Person GetPersonByName(string firstName, string LastName)

    var allPeople = this.personRepository.GetAll();

    return allPeople.Where(x => x.FirstName.ToLower() 
                                     == firstName.ToLower() && 
                                     == LastName.ToLower())

The last coding step is to write the unit test. I 1st need to build up a Person collection that will be used by the framework. This can be done in a Setup method with the [TestInitialize] attribute assigned. I will create a simple test that will ensure a valid instance of Person is returned. The idea here is to test the code within the method to make sure that logic is sound and working as opposed to the actual database call itself. I will leverage Moq to inject the Mock Interface into the Person class. If you have not used Dependency Injection, here is another 'plus' for doing it and it's benefits for testing. Here is the complete PersonTest class with the simple unit test:

public class PersonTest

  private IList<Person> people;

  public void Setup()

    people = new List<Person>()
      new Person()
             Title = "Mr.",
             FirstName = "Allen",
             LastName = "Conway",
             PersonType = "EM"     
      new Person()
             Title = "Mr.",
             FirstName = "John",
             LastName = "Smith",
             PersonType = "SC"


  public void PersonSearch_ShouldFind_ValidInstance()

    var repositoryMock = new Mock<IRepository<Person>>();
    //Setup mock that will return People list when called:
    repositoryMock.Setup(x => x.GetAll()).Returns(people);
    var person = new Person(repositoryMock.Object);

    //Act (mocked up IRepository will supply the data when calls are made to the repository)
    var singlePerson = person.GetPersonByName("Allen", "Conway");

    Assert.IsNotNull(singlePerson); // Test if null
    Assert.IsInstanceOfType(singlePerson, typeof(Person)); // Test type



If you run the unit test above you will see it passes and passes quite quickly (in about 100ms on my machine). Now if I had to actually call out to the database it would have returned the 20,000 rows in the Person table and that is not what I'm testing here. To prove the mock object (in this instance it's actually a stub returning a known state but that's for another post) behaved and returned the collection we expected, right click on the test name and select to debug (I'm using the MSTest runner in VS.NET 2013). If you walk through the code, guess what is returned when the call to .GetAll() on the repository is made within the 'GetPersonByName' method? Our collection created within the test class:

This is only the basics of unit testing and using a mocking framework like Moq, but I put it out there because I see such a disparity between creating unit tests and not creating / using them in our field. It seems like people are 'all in Gung-Ho' or do absolutely none of it. Hopefully this post showed a straight forward and simple example for those wanting to get into unit testing or begin using a mocking framework that are not already doing so today.

Thursday, January 2, 2014

Using Pencil to Create Wireframes for GUI Prototyping

image courtesy of link 
If you have ever lifted weights for strength or toning, you probably know there are some muscle groups in your body that are stronger and easier to work out than others. For me the muscles in the middle of my upper back seem to always be the weaker ones.

I offer this analogy as a segue into the 'software engineering' muscles of all the disciplines and hats we must wear. One discipline that I'm not particularly an expert at is UI design. Sure I've used the splash of rich web content on sites over the years, but nothing that's getting awards for style. Listen, I don't spend day in and day out doing it so I don't consider myself a seasoned expert. Like DBAs are to database development, UI/UX Designers make entire careers out of the trade.

However most of us 'all around' software engineers do not have the luxury of working with a true designer, and at some time or another must design a UI from scratch. We probably result to white board drawings, paper and pen, or just going straight to the VS.NET IDE designer to lay down some HTML, XAML, or raw form controls.

One main prototyping tool that comes to mind immediately is Sketchflow. Sketchflow is a great tool which was integrated with Microsoft Blend, and now Blend is a part of the VS.NET IDE install (since VS.NET 2012 - check versioning for support). About a year ago I was also introduced to a free tool named Pencil for creating wireframes for GUI prototyping in applications. The later tool 'Pencil' I will speak about today.

image courtesy of link
I've had mixed opinions about 'prototyping' over the years for various reasons I could write in another post. Most of my angst came from corporate environments where accounting, HR, or some other internal company party was requesting a custom application, and was a bit too overreaching in wanting to design the application which was a slippery slope. In many of these situations it was best to have the end party define the business problem and let the engineers do what they know best: solve that problem via a custom application. 

image courtesy of link
However this is not always the situation and in many environments (especially where the client is paying for an application), a sketch or mock-up of the final product is required. Could you imagine ordering and paying 25k for a car at the dealer that you had no idea what it would look like, but rather would get you from point 'A' to point 'B' because that was your problem? No, you must know what the car looks like as it is a big part of the purchasing decision. "Hey I wanted a 4 wheel mini car not a moon bus!"

Regardless of the scenario, you control how widely exposed the wireframes you create are distributed. You may only use them for yourself to have a visual of what to do when you dig into the HTML, XAML, etc.. You may choose to keep them internal to your development team that you might be delegating the task to for creation. Lastly, you might be required to show a physical design to a client before they will approve of it and allow you to proceed. Regardless of the audience this is a great tool in the toolbox for UI mock-up / sketch / prototyping design.

Begin by downloading Pencil from the 'Pencil Project' website located below:

Pencil Project

Once installed you will see a blank canvas where you can drag shapes, controls, etc. on to the screen. I'm going to pull a few shapes onto the screen that contains a few tabs as seen below:

I just threw that sketch together in a few minutes and is quite rudimentary. However, if needing to really design an application's GUI this tool has a nice set of shapes and controls for your needs. In fact in the newer versions, shapes have peen added for iPhone and Android tablets to mock up screens for these applications as well.

The one gripe I have about the tool is getting used to how to manipulate the shapes. When I 1st dragged an iPad tablet on it was too large for my screen and the 'size' values were grayed out in the toolbar. I'm accustomed to a right-click -> properties -> change values methodology from most application but this does not hold true for Pencil. It takes a little getting used to, but for being 'free' I can not complain. Some controls like a table are defined by pipe delimited values like displayed below:

Lastly the individual mock-ups can be exported a .png files for use in documentation, and the entire Pencil Project file (*.ep files) can be exported for storing in your source or document control systems.

If you have not done any prototyping before, or used some rudimentary tools to attempt the process, give Pencil a try. It might take that design or requirements document to the next level on your upcoming project. Tools such as these will certainly help elaborate and articulate the end product in a visual as opposed to a verbal manner.