Gigi Labs

Please follow Gigi Labs for the latest articles.

Saturday, August 23, 2014

C# WCF: Backslash Limitation in WCF Test Client

Welcome! :)

Last year, I wrote an introductory WCF article, "C# WCF: A Minimal Client and Server Using Visual Studio 2012". In this article, we explored how to create a simple WCF service, and how to communicate with it using either the WCF Test Client provided with Visual Studio, or via client code. Visual Studio conveniently takes care of much of the plumbing involved in getting client and server to communicate with each other.

In today's article, we will be creating another simple WCF service to learn about a limitation in the WCF Test Client that bit me just yesterday - an issue you'll no doubt come across when using the WCF Test Client to send a string parameter containing a backslash.

First, let us create a new WCF Service Library project:


Now, by default you will have a service called Service1 that exposes a simple method called GetData(). You can test this directly using the WCF Test Client. Press F5 to launch the WCF Test Client; then double-click on the GetData() method, enter a value for the value parameter, and press the Invoke button to see the result (just as we had done in "C# WCF: A Minimal Client and Server Using Visual Studio 2012":


Next, let's add a new method called Echo() to our IService1 interface, which is our Service Contract. This is what it should look like:

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        string Echo(string text);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }


With this done, let us now add an implementation for our Echo() method in the Service1 class:

        public string Echo(string text)
        {
            return text;

        }

Nothing special there - the server echoes the input back to the client, much like we had done in "C# Network Programming: Echo Client/Server". Now, let's fire up the WCF Test Client again (F5) and test our new method:


With an input of "Brazil nuts", it worked fine. Now let's try a fictional domain username:


This time, instead of getting back the data we sent, we're getting a null! Why is that? Let's put a breakpoint in our Echo method and investigate:


Well, as you can see, the input itself is arriving as null, so there's nothing wrong with our logic. To investigate further, switch to the XML tab in the WCF Test Client, where you can actually see the underlying data that is being sent and received:


And even here, you'll see that a null is being sent. It turns out that the problem is that the WCF Test Client does not escape backslashes, so it will convert the whole input to null if it encounters an escape sequence it doesn't recognise (in our case \d); but it does work normally when you send a recognised escape sequence, such as \n:


So whenever you use the WCF Test Client, always escape slashes you actually intend to send as such:


You don't have to do this if you communicate with your WCF service in code, of course.

Note: while this may or may not be seen as limitation in the WCF Test Client (since it's technically allowing you to enter a raw string), it's pretty evil that it silently converts the input string to null when it fails to parse it correctly.

Thanks for reading, and I hope someone finds this useful! :)

Friday, August 1, 2014

ASP .NET Web API: A Gentle Introduction

Hello! :)

Last year, we saw how to intercept HTTP requests in Wireshark, and also how to construct them. As you already know, HTTP is used mainly to retrieve content from the Web; however it is capable of much more than that. In this article, we will learn how HTTP can be used to expose an API that will allow clients to interact with back-end services.

Ideally, you should be using Visual Studio 2013 (VS2013) or later. If you're using something different, the steps may vary.

Right, so fire up VS2013, and create a new ASP .NET Web Application. In VS2013, Microsoft united various different kinds of web projects under a single banner, which is what people mean when they refer to something called "One ASP .NET". So there isn't that much choice in terms of project types:


You are given some sort of choice once you click "OK", however:


At this stage there are various web project types you can choose from, and in this case you need to select "Web API". You'll notice that the "MVC" and "Web API" checkboxes are selected and you can't change that. That's because Web API is somewhat based on the ASP .NET MVC technology. Web API is sort of MVC without the View part, so discussing MVC is beyond the scope of this article; however just keep that in mind in case you ever dive into MVC.

Once you click "OK" and create your project, you'll find a whole load of stuff in your Solution Explorer:


This may already seem a little confusing. After all, where should we start from? Let's ignore the code for a moment and press F5 to load up our web application in a browser. This is what we get:


You'll notice there is an "API" link at the top. Clicking it takes you to this awesome help page, where things start to clear up:


It turns out that the Web API project comes with some sample code that you can work with out of the box, and this help page is telling you how to interact with it. If you look at the first entry, which says "GET api/Values", that's something we can point the browser to and see the web application return something:


And similarly, we can use the second form ("GET api/Values/{id}") to retrieve a single item with the specified ID. So if you point your browser to /api/Values/1, you should get the first one:


That's all well and good, but where are these values coming from? Let's go back to the code, and open up the Controllers folder, and then the ValuesController in it:


You can see how there is a method corresponding to each of the items we saw in the help page. The ASP .NET Web API takes the URL you enter in the web browser and tries to route the request to a method on a controller. So if you're sending a GET request to /api/Values/, then it's going to look for a method called Get() in a controller called ValuesController.

Notice how the "Controller" part is omitted from the URL. This is one of many things in Web API that you're expected to sort of take as obvious - Web API uses something called "convention over configuration", which is a cool way of saying "it just works that way, and by some kind of magic you should already know that, and good luck trying to change it". If you've read my article about Mystery Meat Navigation, part of which addresses the Windows 8 "content over chrome" design, you'll notice it's not very different.

And since, at this point, we have digressed into discussing big buzzphrases designed to impress developers, let's learn about yet another buzzword: REST. When we use HTTP to browse the web, we mainly use just the GET and POST request methods. But HTTP supports several other request methods. If we take four of them - POST, GET, PUT and DELETE, these map quite smoothly to the CRUD (Create, Read, Update and Delete) operations we know so well from just about any business application. And using these four request methods, we can build APIs that allow us to work with just about any object. That's what is meant by REST, and is the idea on which the ASP .NET Web API is built. "How I Explained REST to My Wife" is a really good informal explanation of REST, if you want to learn more about it. The irritating thing is that the concept is so simple, yet it's really hard to find a practical explanation on the web on what REST actually means.

To see this in action, let's rename our ValuesController to BooksController so that it's less vague. We'll also need a sort of simple database to store our records, so let's declare a static list in our BooksController class:

        private static List<string> books = new List<string>()
        {
            "How to Win Friends and Influence People",
            "The Prince"

        };

Now we can change our Get() methods to return items from our collection. I'm going to leave out error checking altogether to keep this really simple:

        // GET api/Books
        public IEnumerable<string> Get()
        {
            return books;
        }

        // GET api/Books/1
        public string Get(int id)
        {
            return books[id];

        }

We can test this in the browser to see that it works fine:


Great! We can now take care of our Create (POST), Update (PUT) and Delete (DELETE) operations by updating the methods accordingly:

        // POST api/Books
        public void Post([FromBody]string value)
        {
            books.Add(value);
        }

        // PUT api/Books/1
        public void Put(int id, [FromBody]string value)
        {
            books[id] = value;
        }

        // DELETE api/Books/1
        public void Delete(int id)
        {
            books.RemoveAt(id);

        }

Good enough, but how are we going to test these? A browser uses a GET request when you browse to a webpage, so we need something to send POST, PUT and DELETE requests. A really good tool for this is Telerik's FiddlerPostman, a Chrome extension, is also a pretty good REST client.

First, make sure that the Web API is running (F5). Then, start Fiddler. We can easily send requests by entering the request method, the URL, any HTTP headers, in some cases a body, and hitting the Execute button. Let's see what happens when we try to POST a new book title to our controller:


So here we tried to send a POST request to http://localhost:1817/api/Books, with "The Art of War" in the body. The headers were automatically added by Fiddler. Upon sending this request, an HTTP 415 response appeared in the left pane. What does this mean? To find out, double-click on it:


You can see that HTTP 415 means "Unsupported Media Type". That's because we're sending a string in the body, but we're not specifying how the Web API should interpret that data. To fix this, add the following header to your request in Fiddler:

Content-Type: application/json

When you send the POST request with this header, you should get an HTTP 204, which means "No Content" - that's because our Post() method returns void, and thus nothing needs to be returned. We can check that our new book title was added by sending a GET request to http://localhost:1817/api/Books, which now gives us the following in response:


We can similarly test PUT and DELETE:

  • Sending a PUT request to http://localhost:1817/api/Books/1 with "The Prince by Niccolo' Machiavelli" in the body updates that entry.
  • Sending a DELETE request to http://localhost:1817/api/Books/0 deletes "How to Win Friends and Influence People", the first book in our list.
  • Sending a GET request to http://localhost:1817/api/Books again shows the modified list:

Fantastic! In this unusually long article, we have learned the basics of working with the ASP .NET Web API. Lessons learned include:
  • The ASP .NET Web API is based on the REST concept.
  • The REST concept simply means that you use HTTP POST, GET, PUT and DELETE to represent Create, Read, Update and Delete operations respectively.
  • For each object you want to work with, you create a Controller class.
  • Appropriately named methods in this Controller class give you access to the CRUD operations mentioned above.
  • Use Fiddler or Postman to construct and send HTTP requests to your Web API in order to test it.
  • Add a content type header whenever you need to send something in the body (POST and PUT requests).
Thanks for reading, and please share this with your friends! Below is the full code of the BookController class for ease of reference.


    public class BooksController : ApiController
    {
        private static List<string> books = new List<string>()
        {
            "How to Win Friends and Influence People",
            "The Prince"
        };

        // GET api/Books
        public IEnumerable<string> Get()
        {
            return books;
        }

        // GET api/Books/1
        public string Get(int id)
        {
            return books[id];
        }

        // POST api/Books
        public void Post([FromBody]string value)
        {
            books.Add(value);
        }

        // PUT api/Books/1
        public void Put(int id, [FromBody]string value)
        {
            books[id] = value;
        }

        // DELETE api/Books/1
        public void Delete(int id)
        {
            books.RemoveAt(id);
        }

    }