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);
        }

    }

Thursday, July 24, 2014

C#: Metronome with Timers and Beeps

Hey people! :)

When you're learning to play an instrument, one thing you need to make sure of is that you're playing in sync with a regular beat. A device that helps you by producing such a regular beat is a metronome. In this article, we're going to write a simple metronome application. In doing so, we'll learn how to use the Console's beeping functionality, and we'll learn to use timers to fire events at regular intervals.

So let's begin by creating a new Console Application, and adding the following using statement near the top, which will give us access to some of the classes we need:

using System.Threading;

Now, making a quick and dirty metronome is very easy. This is all it takes:

            while (true)
            {
                Console.Beep(4000, 100);
                Thread.Sleep(1000);
            }

That Console.Beep() takes the frequency of the sound as the first parameter (in this case 4000Hz), and the duration of the beep as the second parameter (in this case 100 milliseconds). You can omit the arguments entirely to use default settings.

Thread.Sleep() is used to suspend the program for a specified duration (specified in milliseconds in the parameter). In this case we're using it to cause a delay between beeps of 1000 milliseconds (i.e. 1 second).

Now, suspending the program like this is not a very good thing. In fact, we can't give the user an option to quit, and if we were using a GUI (e.g. WPF), then this kind of blocking would be even more problematic.

A better approach for our metronome application is to use Timers. Now there are many different Timer classes we can use, but the one we need in this case is this one. So before we see how we can use these mystical creatures to create a more awesome metronome, let us first add another using statement:

using System.Timers;

Now let's create an instance of our Timer class:

            Timer timer = new Timer();

Now you're going to see Visual Studio complain about this line:


As Visual Studio is telling you, there is also a Timer class in System.Threading, so C# doesn't know which one to use. You can resolve the ambiguity by using the fully qualified names instead (or in this particular case, just remove System.Threading since we don't need it any more):

            System.Timers.Timer timer = new System.Timers.Timer();

Next, assign a new event handler to the Elapsed event:

            timer.Elapsed += timer_Elapsed;

Visual Studio offers to create the event handler for you as you type:


Take it up on the offer, and have the following code generated for you:

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            throw new NotImplementedException();
        }

Replace the contents of this event handler with our beeping functionality:

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.Beep(4000, 100);
        }

Back in the Main() method, set an Interval for the timer:

        timer.Interval += 1000;

You should begin to understand what we're doing here. Every time the interval passes (i.e. every second in this case), the Elapsed event will fire, and do whatever we specify in the event handler.

Now all we need to do is start the timer. In the code below, I am also waiting for the user to press ENTER, and once this is done, I am stopping the timer and exiting the application:

            timer.Start();
            Console.ReadLine();
            timer.Stop();

Since the timer runs on a separate thread, it does not interfere with user input. So we can have the timer running in the background while the program waits for user input - similar to what we did last year in "C# Threading: Bouncing Ball" (except that all the threading stuff is handled for you).

So there's your metronome! Full code below. :)

        static void Main(string[] args)
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += timer_Elapsed;
            timer.Interval += 1000;

            timer.Start();
            Console.ReadLine();
            timer.Stop();
        }

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.Beep(4000, 100);
        }

In this article, we created a very simple metronome application. We first used a sleep-based delay, and learned about the dangers of having it block the program, limiting its interactivity. We then used a Timer from the System.Timers namespace in order to trigger beeps at regular intervals.

There are many ways in which this can be improved (e.g. distinct beep every four beats, configurable beats per minute, etc), but this is a fully functional metronome and a pretty simple demonstration of how to use timers.

The beeping functionality can also come in handy in a wide range of scenarios. One example is to supplement last year's article "C# Basics: Morse Code Converter Using Dictionaries" with actual sounds to represent the dots and dashes in Morse Code.

I hope you found this useful. Thanks for reading! :)

Sunday, July 20, 2014

C# WPF: StackPanels and WrapPanels

So in yesterday's article, "C# WPF: CheckBoxes", we learned about CheckBoxes, content controls, and also used a StackPanel to position controls underneath each other. We'll learn a bit more about the StackPanel in this article, and we'll also compare it to another layout control - the WrapPanel.

So let's create a new WPF application, and replace the default <Grid> with a <StackPanel> of CheckBoxes. Your MainWindow's XAML code should look something like this:

<Window x:Class="CsWpfStackPanelWrapPanel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock>Choose the pizzas you want to order:</TextBlock>
        <CheckBox>Margherita</CheckBox>
        <CheckBox>Funghi</CheckBox>
        <CheckBox>Pepperoni</CheckBox>
        <CheckBox>Quattro Stagioni</CheckBox>
        <CheckBox>BBQ Chicken</CheckBox>
        <CheckBox>Ranch Special</CheckBox>
        <CheckBox>Vegeterian</CheckBox>
        <CheckBox>Ham and Mushroom</CheckBox>
        <CheckBox>Meat Lovers</CheckBox>
    </StackPanel>
</Window>

As we saw in yesterday's article, a <StackPanel> will lay out any controls inside it as a vertical list by default. You should be able to see this in Visual Studio's preview:


That's because the <StackPanel> has an Orientation property, which by default is set to Vertical. See what happens when we change this to Horizontal:


So as you can see, the <StackPanel> is also useful to position controls horizontally next to each other.

However, as you can see from the preview, we have so many checkboxes that they didn't all fit in the 525-pixel-wide window, so that the ones further right can't be seen because they fall outside the window's boundaries.

Let us now see what happens if we change the <StackPanel> to a <WrapPanel>:


So the <WrapPanel> is actually quite similar to the <StackPanel>, but there are two main differences. The first, as you've probably noticed, is that a <WrapPanel> will wrap controls that don't fit on one line onto subsequent lines.

The second is that a <WrapPanel>'s Orientation is Horizontal by default. You can change it to Vertical to have controls listed and wrapping vertically instead. Let's add a bunch of other checkboxes just to see how this works:


Great! In this article we've seen how to use the <StackPanel> and <WrapPanel> layout controls. Both of these can be used to list items in either vertical or horizontal lists. They are two key differences between them:
  • The <StackPanel> will always use keep controls in one row or column, even if they don't fit; the <WrapPanel> will instead wrap controls onto subsequent rows/columns when they don't fit.
  • The default Orientation of the <StackPanel> is Vertical, while that of the <WrapPanel> is Horizontal.
Stay tuned for more WPF goodness! :)