Last month the new Windows Azure features were released, and one of them which I found quite interesting was the “Web Sites”. Currently I have an account at GoDaddy.com where I host my “pet projects”, and now that Windows Azure has a similar feature at a similar pricing plan (for the preview we can have up to 10 sites at no cost, with some limited resource utilization), I felt compelled to “eat my own dogfood” and try it out. And I really loved it – especially the integration with the Git source control, where uploading new bits to the site feels like a breeze. Before I start to look too much like a homer, I liked the Git integration better than the GoDaddy interface because I prefer working with command-line interfaces. If you’re into GUI, you can use something like a FTP client to talk to GoDaddy, or one of the many Git shells (which I haven’t tried), so which one is better would depend on your opinion of the tools.
So I decided to convert one of my old projects which I have hosted in the GoDaddy account to work in an Azure Web Site. The project, a tool which converts a JSON document into a class (or series of classes) and an operation contract that can be used in WCF, was written using some classes from a Codeplex project which isn’t supported anymore (WCF Web APIs). So when migrating to Azure, I decided to also try the integration between that and the replacement for that project, ASP.NET Web APIs. Here’s a step-by-step account of what I did, hopefully you’ll find it useful when trying to do something similar.
So here’s a very detailed step-by-step of what I did – and similarly, what you’d do – to create my API and host it in Azure. I hope you like huge blog posts…
If you’re only interested in the tool to convert JSON to data contracts: see it at http://jsontodatacontract.azurewebsites.net, or you can get the source code in the MSDN Code Gallery.
The first thing to do is to create the new Web Site which will host the API. I tried the name jsontodatacontract, and it was available:
After creating the web site, there are a few options for deploying the site. We could use the Publish option in any web project (or web site) in Visual Studio, or we can also use the integrated source control system in the web sites. Since I want to have source control, and I like Git’s simplicity, I’ll choose that option.
Now the repository is created (one click!), and it’s ready to be used. The next page shows the next steps we can take to upload data to the site.
So far we don’t have any data to push to the web site, so let’s take a back off the Azure portal for a while, and let’s create a new project which we’ll use. Since all I want (for now) is to build a service, I’ll create an empty project, so I’ll use an Empty ASP.NET Web Application instead of the full MVC4 application This will make our code as small as possible, but we’ll need to deal with things such as routing ourselves – which are not too hard, as we’ll see shortly. Another advantage of this method (empty project) is that we don’t need to install anything, and to get the ASP.NET MVC 4 templates you need to, well, install the ASP.NET MVC 4 templates (which currently are in the RC version, and many people – myself included – don’t like to install pre-release software in their machines). The RC is at a good quality already, but since in this case I don’t need it, I like to keep things simple whenever possible.
So let’s open the New Project dialog, and create an empty ASP.NET Web Application. I’ll save it in the c:\git directory, but that’s just my preference (the root of my Git repositories), it could be created in any folder in your machine. One setting which we should use is the “Create directory for solution” checkbox, as it will allow us to use the NuGet Package Restore feature, which I’ll cover later on.
Once the project is created, let’s add a reference to the binaries for Web API. Right-clicking the project, select “Manage NuGet Packages…”, and that will bring NuGet’s dialog, where we can search for “webapi”, and select the “Microsoft ASP.NET Web API (RC)” package (while the final version isn’t available). Clicking “Install” will download that package (and all of its dependencies). It will also add them as references to the project, so they can be used right away.
One parenthesis here – I started using NuGet about a year ago, and I really like it. It’s a feature which comes installed by default on Visual Studio 2012. For Visual Studio 2010, you can install it, from a link in the main NuGet page: http://www.nuget.org/. My only gripe is that it doesn’t work on the express editions of VS 2010 (C# or VB) – it does work on Visual Web Developer, though. I think it will work on the express editions for VS 2012 as well, though.
Ok, back to the project. We need to create a controller class which implements our service. In Web APIs, controller classes can be defined anywhere in the project, but to keep with the convention, I’ll add it in a folder called “Controllers”, which I’ll add to the project.
And we can now add our controller class in that folder, by right-clicking on the folder and selecting “Add” –> “New Item”, then selecting a new Web API Controller Class.
For now, let’s remove the implementation of the class, and add a pair of Post / Get methods to see if the deployment to Azure will work.
One more thing with the project: since we used an empty template, we need to add the routing code ourselves. So let’s add a new Global Application Class
And add the routing in the code:
At this point we can “F5” our application to see if it works. By default the project will browse to the root “/”, but our controller is at the “api/” URL (based on the route template), so we need to browse to that location.
And since also added a Post operation, we should be able to call it as well, which I can do with Fiddler:
Ok, we now have a Web API which is functional, so we can start the deployment process. The last page in the portal showed what to do, so let’s go to the root of the application (c:\git\JsonToDataContract) and initialize our git repository.
Now we can see which files Git wants to track by using the git status command
There are two things which Git wants to track but we don’t really need to deploy. One is the .suo (Solution User Options) file for the solution, which doesn’t need to be shared. The other are the NuGet packages which are stores in the packages/ directory. Git, like other DVCS, don’t work too well with binary files, since updating them can cause the repository to grow a lot over time. Thankfully, NuGet has a feature called NuGet Package Restore, which allows us to bypass checking the packages in, and during the build it will download any missing packages locally. To do that, let’s right-click the solution in the VS Solution Explorer, and choose the “Enable NuGet Package Restore” option.
What the feature did was to add a new solution folder (.nuget), and on it add a new targets file and a small NuGet executable which can be used, during build, to download missing packages.
Now we can exclude the packages directory (along with the .suo file) from Git, and to do that we’ll need a .gitignore file on the Git root (in my case, c:\git\JsonToDataContract\.gitignore).
Now we can add the project, and see what is to be committed.
And finally let’s commit our changes:
So we committed the changes to our local repository, but nothing has been pushed to Azure yet. Let’s do that, again following the instructions on the Azure Web Site page:
A lot happened when we pushed to the web site. First, the we pushed our repository to the server. There, when the transfer finished, the site started the automatic deployment, by building the project. Notice that since we excluded the NuGet packages (but enabled package restore), the packages were downloaded during the build as well. And when the build was done, the site was deployed, so we can go to http://jsontodatacontract.azurewebsites.net/api and see the same page that we saw locally:
And our Web API is running on Azure!
Ok, what do we have so far? We created a web site on Azure, set up Git publishing, created a project using Web API via NuGet, and deployed the project to Azure. As far as “how to create and deploy a Web API in Azure”, that’s it. I’ll continue on, though, to finish the project which I set out to do.
Ok, let’s make the controller do what it’s supposed to do. Since I already had a project which did something similar, I’ll reuse some of the code from that project in this one and let me start saying that this is definitely not the most beautiful code you’ll see, but since it works, I decided not to fiddle too much with it.
The task of converting arbitrary JSON to classes which represent it can be broken down in two steps. First, we need to look at the JSON and see if it has a structure which actually can be represented in classes – there are some which don’t, such as an array containing both objects and primitives. By doing that we can load the JSON into a memory structure, similar to a DOM, with information about the types. Second, we need to traverse that DOM and convert it into the classes which we’ll use to consume and produce that JSON.
For the first part, I’ll define a class called JsonRoot, which can represent either a primitive type (string, boolean, numbers) or a complex type which contains members. The members (or the root itself) can be part of an array, so we also store the rank (or number of dimensions) of the array in the JsonRoot type (“rank” is an overloaded term which if more often used with rectangular array, but in this scenario it actually means jagged arrays which are supported by the serializers). Notice that this class could (maybe should?) be better engineered, split in two so that each type has its own behavior, but I won’t go there, at least not in this iteration.
Parsing primitive types is trivial, as shown above. Parsing objects is also not hard – recursively parse the members and create a user-defined type with those members. When we get to arrays is where the problem starts happening. JSON arrays can contain arbitrary objects, so we need some merging logic so that two similar items can be represented by the same data type.
Here are some examples to illustrate the issue:
So here’s how we can parse an array as a JsonRoot. After we try to merge all the elements of the array into one JsonRoot type, we’ll create a new JsonRoot object incrementing the ArrayRank property.
The code for merging two types can be found in the sample in the code gallery (link on the bottom of this post).
Now, we have a data structure which says which types we need to generate. Let’s move on to the code generation part. In this example (and in the original post), I’m using the types in the System.CodeDom namespace, since it gives me for free the generation in different languages. I’ll add a new class, JsonRootCompiler, which has one method which will write all the types corresponding to the given JsonRoot object (and the root of any members of that object as well) to a text writer.
Again, the bulk of the implementation can be found in the MSDN Code Gallery sample.
And we have the two pieces that we need, we can update the code for the controller to use them. The Post method has 4 parameters, 3 of type string (which, by default, are expected to come via the request URI, as query string parameters), and of of type JToken, which can be read by the JSON formatter in the Web API framework (it will be read from to the request body).
Let’s test it now. Since we only have a POST method, we’ll need to either create a custom client, or use something like Fiddler to do that.
At this point our API is done, and can be deployed to Azure via Git. But to make the web site more usable, let’s create a simple front-end where users don’t need to use a tool such as Fiddler to generate JSON. My design skills are quite rudimentary at best, so I won’t even try to make anything fancy and will just use a few HTML controls instead. Let’s first add a new HTML page. Based on the configuration of my Azure Web Site, the first file it will look for when browsing to it is called Default.htm (you can see that in the bottom of the “Configure” page in the portal), so let’s create one in our project.
And add some code to it:
Now we need to hook up the button to call our API. We could do that using the native XmlHttpRequest object, but I found that using jQuery is a lot simpler, and we can use NuGet to add a reference to jQuery to our project, so why not?
We need to add a reference to the jQuery.js on the default.htm file; the easiest way is to simply drag the file jQuery.1.7.2.js from the scripts folder (where it NuGet package created it), and drop it within the <head> section in the HTML file.
When we click the button, it will then send a request to the Web API, and we can test it out.
Ok, we’re getting close to the end, I promise. Let’s go back to our command prompt and see what Git is tracking now, using git status:
We have many items which we need to add to the staging area, so let’s do that. Depending on the configuration of your Git client, you may see some warnings about CR/LF mismatches in the jQuery files, but they can be safely ignored.
Now let’s commit the changes locally.
And we’re now finally ready to push to Azure:
The deployment succeeded again! That means that we should be ready to go. Let’s try browsing to http://jsontodatacontract.azurewebsites.net, and try out the service…
And it’s working! On the cloud!
This was probably the longest post I’ve written, but I don’t think this scenario is complex. I wanted to give a full step-by-step description on how to develop ASP.NET Web APIs and deploy them to Azure Web Sites, and the huge number of images is what made this post longer than most. If you like this format, please let me know and I’ll write some more like this, otherwise I’ll go back to shorter posts since they’re just easier to write :-)
[Code on this post]