You will need Azure SDK installed…

In an earlier blog post, I was bemused that the Create New Project wizard was skipping the Azure configuration screen.

It has now been confirmed that this is because the Azure SDK is required as an installation pre-requisite in order to create and configure the Azure role, and to correctly support the deployment to Azure.

Additionally, I can also confirm that there is no dependency on the Azure SDK on the Casablanca runtime libraries themselves.

Installing Azure SDK

You can download the installer from http://www.windowsazure.com/en-us/develop/downloads/. This actually fires up a Web Platform Installer which can download and install other components in addition to the Azure SDK.

figure-02

Clicking through will install the Azure SDK and any other components you have chosen to install/upgrade.

Hello World Revisited

Creating a new Casablanca Project raises the following wizard…

figure-03

… followed by …

figure-04

… which results in the following Solution Tree being created

figure-05

The Worker Role references the Deployment Project, and the Deployment project references the Casablanca Service.

…and One Last Thing

When you are building worker roles, ensure that you fire up Visual Studio with ‘Run As Administrator’.

Without Administrator privileges, you will get:

figure-06

You may also have to open up firewall ports and that kind of thing depending on how your development environment is set up…

Happy Coding!

Advertisements

The New Bits Are Here!!!

Hello all!

Just received word from the Microsoft Casablanca team that the November bits are available for general download.

[quote]

The November refresh of Casablanca bits is available for download!

As always, you’ll find the download links on the DevLabs page. There are four different MSIs, supporting Visual Studio 2010, Visual Studio 2012, Visual Studio 2012 Express for Windows Desktop and Visual Studio 2012 Express for Windows 8.

This release fixes multiples issues reported on this forum and adds the following improvements:

  • Cleanup of several HTTP APIs 
  • Full support for Azure tables
  • File and tcp stream buffer implementations for the WinRT version of Casablanca
  • Programmatic control of chunk sizes when sending HTTP entity body data
  • Improved Azure blob and queue support, including the latest REST APIs
  • Support for Azure SDK 1.8

As always, send you feedback through this forum!

Thanks for your support,

Casablanca Team

[/quote]

We’ll be re-compiling and pushing out some more of our demos with the new bits. Stay tuned.

Saying “Hello World”

So let’s dive in and start coding!

We’re assuming you’ve installed Visual Studio 2012 and the latest Casablanca SDK. We’re using the bits published on Sep 24.

The code for this project is available at http://microsoftcasablanca.codeplex.com/ in the ‘HelloWorld’ directory.

This code is quite different from the default we talked about in the video, and reflects the evolution and maturing of the Casablanca SDK itself. In fact, the next version of the Casablanca SDK may have a different default application, reflecting further improvements in the SDK. We’ll do our best to keep the blog up-to-date!

Fire up Visual Studio and create a new Casablanca project…

figure-01_thumb2

[The older bits gave us a second dialog allowing us to choose a Web or Worker role, and configure those appropriately, but the current drop seems to blitz past that dialog. I will post an explanation as soon as I find one! –John]

…which gives us the default project.

figure-02

We’ll walk through the code in a minute, but let’s run the project as is, and see what happens…

figure-03

Boom! The code compiles and runs, but obviously fails. It is time to dissect the code and understand what’s going on inside.

Let’s look at the project first, and figure out what is going on there:

First of all, the C++ compiler needs to get some header information about the Casablanca classes…

figure-04

…and the linker needs to include the Casablanca libraries…

figure-05

Pay close attention to the SDK folder, as this may change with future releases, and you will need to update your projects as and when this happens.

[I don’t know if there is a system like ‘nuget’ or ‘apm’ for Visual C++ projects, which can consume a library and keep it up-to-date in a streamlined way. It sure sounds like a good way to release Casablanca bits –John]

The actual Casablanca library is dependent on the version of Visual Studio. For VS 11 aka VS 2012, it is called ‘casablanca110.lib’. The Actors library, analogously, is contained in ‘actors110.lib’. This will be different if you’re using VS 2010.

figure-06

Similarly, the Project Configuration has a reference to a Platform Toolset, which is how the project is configured to build in a given version of Visual Studio.

figure-09

The project we are building does not create an .exe file. Rather, we are writing a library, as highlighted above. Our DLL is loaded by a host which is part of the Casablanca system. When we run the project in Visual Studio 2012, we are actually running CasablancaHost110.exe, and specifying the DLL to load in the actors_config.cfg file.

figure-07

figure-10

Therefore, there is a Post-Build step to copy it from the project directory to the deployment target directory.

figure-08

Now let’s go and get the application running:

The only material change that is required is that the endpoint needs to be specified. We could change

// Function to help find dynamically assigned port for our endpoint.
casablanca::string_t find_addr(const std::vector<casablanca::string_t> &configs)
{ 
    // The configuration data is a vector of [key1,value1,key2,value2,...,keyN,valueN] pairs.
    return U("http://*");
}

to

// Function to help find dynamically assigned port for our endpoint.
casablanca::string_t find_addr(const std::vector<casablanca::string_t> &configs)
{
    // The configuration data is a vector of [key1,value1,key2,value2,...,keyN,valueN] pairs.
    return U("http://localhost:8181");
}

and run successfully.

figure-11

The functionality we’re demonstrating above is provided by the handler for the HTTP GET verb. We’re specifying that here.

    g_listener.support(methods::GET, [](http_request message)
    {
        message.reply(http::status_codes::OK, U("Hello World!"));
        actors::log::post(actors::LOG_INFO, U("Serviced a GET request for ") + message.request_uri().to_string());
    });

What we are actually doing is providing the listener a call-back lambda which writes “Hello World” into the response of the current request.

Two key points for the future:

1) This lambda does not close over any local or instance variables, so it’s effectively a free-standing static method. We can use this information to build more complex mechanisms to respond to HTTP methods in the future

2) There are several overloads to message.reply(), and we’ll encounter a few more as we build other projects.

That’s it for now. I hope this post has provided a detailed explanation of the basic infrastructure of a Casablanca project, which helps you to understand what is going on better!

Happy Coding!

TechEd Australia 2012: AZR331

This is a reprise of the blog post following our talk at TechEd Australia 2012, where we summarise what we talked about.

We gave a talk at Tech Ed Australia this year titled Casablanca: C++ on Azure. The talk itself was slotted in at 8:15 am on the last day of Tech.Ed after a long party the night before. The crowd was small, and although we were initially disappointed by the turn out, we took heart in the fact that this was the most viewed online video at Tech.Ed this year – lots of five star ratings, Facebook likes and tweets.  This post gives you an introduction to Casablanca and highlights the things we talked about in the Tech.Ed presentation.

So, what is Casablanca? Casablanca is an incubation effort from Microsoft with the aim of providing an option for people to run C++ on Windows Azure. Until now, if you were a C++ programmer, the easiest option for you to use C++ would be to create a library and then P/Invoke it from C# or VB.NET code. Casablanca gives you an option to do away with things like that.

If you are a C++ developer and want to move your code to Azure right away, all we can say is “Hold your horses!” It is, like we said, an incubation effort and  not production ready, yet. But you can download it from the Devlabs site, play with it and provide valuable feedback to the product team.

You are also probably thinking, “Why use C++?” The answer to that question is really “Why not?” Microsoft has been providing developers the option to use various other languages/platforms such as java and Node.js to write for Azure, and now they are giving the same option to C++ programmers – use the language of their choice to write applications in Azure. Although there has been a bit of resurgence in C++ in the last couple of years, we are not really trying to sell C++ to you. If we are writing a Web App that talks to a database, then our first choice would probably still be ASP.NET MVC using C#, and maybe Entity Frameworks to talk to the DB. What we are trying to say is that you still need to use the right language and framework that works best for you, and if C# is the language you are comfortable with, then why change.

On the other hand if you are using C++, then you probably already know why you want to continue using it. You may be using it for cross-platform compatibility or better performance or maybe you have lots of existing legacy code that you can’t be bothered porting across. Whatever the reason, Casablanca gives you an option to bring your C++ code to Azure without having to use another language to talk to its libraries.

The Node influence

When you first start to look at Casablanca code, you will notice how some of the code has some resemblance to Node.js. A simple Hello World example in node will look like this –

var http = require('http');

http.createServer(function (request, response) {

  response.writeHead(200, 
                  {'Content-Type': 'text/plain'});
  respose.end('Hello World!');

}).listen(8080, '127.0.0.1');

The equivalent Hello World in C++ would look something like this –

using namespace http;

http_listener::create("http://127.0.0.1:8080/",
    [](http_request request)    
    {        
        return request.reply(status_codes::OK, 
                      "text/plain", "Hello World!");
    }).listen();

Notice the similarity? This isn’t by accident. The Casablanca team has been influenced a fair bit by Node and the simplicity by which you can code in node.

Other inclusions

The proliferation of HTML, Web servers, web pages and the various languages to write web applications based on HTML happened in the 90s. C++ may have been around a lot longer than that, but surprisingly, it didn’t ride the HTML wave. Web servers were probably written in C++, but the applications themselves were written using much simpler languages like PHP. Of course, we did have CGI, which you could write using C++, and there were scores of web applications written in C++ but somehow, it really wasn’t the language of choice for writing them. (It didn’t help that scores of C++ developers moved on to things like Java, C#, and Ruby). What C++ needed was a good library or SDK to work with HTTP requests, and process them.

In addition to this, RESTful applications are becoming common place, and is increasingly becoming the preferred way to write services. So, the ability to easily process GET, PUT, POST and DELETE requests in C++ was also needed.

When we talk about RESTful apps, we also need to talk about the format in which the data is sent to/from the server. JSON seems to be the format of choice these days due to the ease with which it works with Javascript.

The Casablanca team took these things into consideration and added classes into Casablanca to work with the HTTP protocol, easily create RESTful apps and work with JSON.

To process the different HTTP actions and write a simple REST application to do CRUD operations, the code will look something like this:

auto listener = http_listener::create(L"http://localhost:8082/books/");

listener.support(http::methods::GET, [=](http_request request)
{
    //Read records from DB and send data back
});

listener.support(http::methods::POST, [=](http_request request)
{
    //Create record from data sent in Request body
});

listener.support(http::methods::PUT, [=](http_request request)
{
    //Update record based on data sent in Request body
});

listener.support(http::methods::DEL, [=](http_request request)
{
    //Delete
});

/* Prevent Listen() from returning until user hits 'Enter' */ 
listener.listen([]() { fgetc(stdin); }).wait();

Notice how easy it is to process the individual HTTP actions? So, how does conversion from and to Json objects work? To convert a C++ object to a Json object and send it back as a response, the code will look something like this:

using namespace http::json;
...

value jsonObj = value::object();
jsonObj[L"Isbn"] = value::string(isbn);
jsonObj[L"Title"] = value::string(title);
...

request.reply(http::status_codes::OK, jsonObj);

To read json data from the request, the code will look something like this:

using namespace http::json;

...

value jsonValue = request.extract_json().get();

isbn = jsonValue[L"Isbn"].as_string();

You have a collection? no problem, the following code snippet shows how you can create a Json array

...
auto elements = http::json::value::element_vector();
for (auto i = mymap.begin(); i != mymap.end(); ++i) 
{
    T t = *i;

    auto jsonOfT = ...; // Convert t to http::json::value
    elements.insert(elements.end(), jsonOfT);
}
return http::json::value::array(elements);

 

Azure Storage

If you are running your application in Windows Azure, then chances are you may also want to use Azure storage. Casablanca provides you with the libraries to be able to do this. The usage, again is quite simple, to create the various clients for blobs, queues and tables the usage is as follow:

storage_credentials creds(storageName, storageKey);

cloud_table_client table_client(tableUrl, creds);
cloud_blob_client blob_client(blobUrl, creds);
cloud_queue_client queue_client(queueUrl, creds);

Notice the consistent way of creating the various client objects. Once you have initialized them, then their usage is quite simple too. The following code snippet shows you how to read data from Table storage:

cloud_table table(table_client, tableName);
query_params params;
	...
auto results = table.query_entities(params)
                      .get().results();

for (auto i =  results.begin(); 
          i != result_vector.end(); ++i) 
{
    cloud_table_entity entity = *i;
    entity.match_property(L"ISBN", isbn);
    ...
}

Writing to Table storage is not difficult either, as seen in this code snippet:

cloud_table table(table_client, table_name);
cloud_table_entity entity(partitionKey, rowKey);

entity.set(L"ISBN", isbn, cloud_table_entity::String);
	...

cloud_table.insert_or_replace_entity(entity);

Writing to blobs, and queues follow a similar pattern of usage.

Async…

Another one of the main inclusions in Casablanca is the ability to do things in an asynchronous fashion. If you’ve looked at the way things are done on Windows Store applications or used Parallel Patterns Library (PPL), then you would already be familiar with the “promise” syntax. In the previous code snippets, we resisted the urge to use it, as we hadn’t introduced it yet. 

… and Client-Side Libraries

Also, we have been talking mainly about the server side use of Casablanca, but another thing to highlight is the fact that it can also be used to do client side programming. The following code shows the client side use of Casablanca and how promises can be used:

http::client::http_client client(L"http://someurl/");
client.request(methods::GET, L"/foo.html")
.then(
      [=](pplx::task task)
      {
         http_response response = task.get();
         //Do something with response
         ...
      });

If you need to find out more about ppl and promises, then you should read the article Asynchronous Programming in C++ written by Artur Laksberg in the MSDN magazine.

Wait, there is more…but first lets get started

Casablanca has also been influenced by Erlang, and the concept of Actors, but let’s talk about it another post. To get started with Casablanca, download it from the DevLabs site. It is available for both VS 2010 and 2012.

 

image012

Basic Resources

You’ll need these links to be able to make the best of the Casablanca Preview

The TechEd Australia 2012 Talk

First things first – let’s share the video of the presentation and talk itself. Here is the link to the video on the Channel 9 website.

It’s about an hour long, and you get to share the experience of the 25 faithful people who braved the 8:15 am time slot on the day after the party!

Do send us (John) or (Mahesh) comments or requests if you want us to explain something we didn’t!