Four years ago I wrote a blog post that shown how to build a web server using the http_listener from the C++ REST SDK library as well as a client application that consumed the exposed resources. Over the years there have been various changes to the API from the library and some readers complained the code no longer compiled. Eventually, I decided to revisit that post and update my code to the latest version of the library, which at this time is 2.10.

I will not reiterate all the details described in the former article. However, in summary, the server maintains a dictionary of values (both keys and values are strings). Through HTTP calls a client can retrieve the content of the dictionary, add new values, update or delete existing ones.

HTTP method Description Request Response
GET retrieves all the key-value pair from the dictionary {"one" : "100", "two" : "200"}
POST retrieves the values of the specified keys from the dictionary ["one", "two", "three"] {"one" : "100", "three" : "", "two" : "200"}
PUT inserts new pairs of key-values in the dictionary; if a key is already found its value is updated {"one" : "100", "two" : "200"} {"one" : "", "two" : ""}
DELETE deletes the specified keys from the dictionary ["one"] {"one" : ""}

Here is the server code:

And this is the client code:

Notice there are slight changes in the way output is formatted, both in the server and the client application. The rest is mostly unchanged, except for the handling of JSON, that has changed significatly since version 1.1. Again, please see the original post for an explanation of the code.

The output from running these client and server applications is shown below. On the left is the client output, and on the right the server output.

, , , Hits for this post: 205 .

In the previous post, I have shown how you could write a simple Twitter bot using JavaScript and Node.js very quickly. However, I ran the bot on my local machine, which is probably not something that you want to do for a real application. Instead, you’d probably want to host it on a cloud platform. In this article, I will show how you can do that also in no time using Heroku. Heroku is a cloud platform for building and running applications that takes away the complexity of setting up an entire infrastructure. This makes it well suited for simple things like the bot we previously created.

A word on Azure

Since I have an Azure account and MSDN subscription my first choice for hosting the bot was Azure. However, I learned something important.

After wasting too much time looking into both web apps and Azure Cloud Services, installing Azure Power Shell, learning to use it, setting up worker roles, deploying, etc. and still not getting the bot to work (unless accessed through a URL) I decided to move on and find something that even someone unfamiliar with can quickly grasp in minutes.

Starting with Heroku

Heroku is a platform that you can use for free for experimenting if you don’t require too many resources. Of course, there are paid plans, depending on your needs. However, for the simple bot I was building there would be no incurring costs.

Pricing is based on dyno hours. Dynos are lightweight Linux containers in which an application runs. A dyno can belong to one of the three possible configurations: web (that receive HTTP traffic from routers), worker (typically background jobs, queueing systems, and timed jobs), and one-off (temporary dynos that can run detached, or with their input/output attached to your local terminal, typically used for administrative tasks, such as database migrations and console sessions). You can get up to 1000 dyno hours per month for free, which is enough to run an application with no costs. Should you need to host more, then you’d have to pay for it.

After creating the account, you should download and install the Heroku CLI (previously known as Heroku Toolbelt). This allows you to create and manage Heroku apps from the command line on Window, MacOS and Debian/Ubuntu.

Creating a Heroku app

After creating an account and signing in you can create applications from the dashboard. You must specify a unique name and a data center where it should be hosted.

Heroku has its own git to store your project sources. You can find instructions under the Deploy page for how to create the project locally and commit it to Heroku’s git repository.

Defining a Procfile

Apart from the bot source files that we created in the previous article (package.json, bot.js, and others that might be necessary), we need to declare a Procfile in the root directory of the app. This is a text file that defines what command should be executed to start the application. The content of this file should be the following (assuming that the entry point of the bot is called bot.js).

This is necessary because the Twitter bot is not a web app, but a worker app that runs on the server and does something periodically in the background, not based on HTTP requests.

After uploading the source files including the Procfile to the heroku git repository, go to the application and under the Resources tab, stop the web dyno and start the worker dyno.

Note: a web dyno is created by default for every application.

And that’s it, the Node app now runs successfuly on the platform in the background.

See more

Deploying Node.js Apps on Heroku
Getting Started on Heroku with Node.js
Dynos and the Dyno Manager

, , , , , , , Hits for this post: 1217 .

I had recently played with the idea of creating a twitter bot, not for any specific reason but to see how hard or easy that would be. And to do something that would put a bit of fun into the experience I decided to make a bot that would create nice tweets with emoji of bugs. Here is an example:

It turned out that creating such a bot is a no time consumer when done in JavaScript with Node. The result of my experiment is available here: https://twitter.com/emojibugs.

This article explains the necessary steps to build a simple Twitter bot that posts messages periodically, at some pre-defined interval.

Twitter account and app

The first thing to start with is a Twitter account. This could be either an existing account or a new one.

After setting up the account the bot should be tweeting on behalf of you need to go and create an application. That can be done from https://apps.twitter.com/. You need to create a new app, provide a name, description, website and other optional ones.

After the app is created you need to go to Keys and Access Tokens and generate them for the application. These will be used later on to sign it to Twitter from the bot, and specifically:

  • Consumer key (API key)
  • Consumer secret (API secret)
  • Access token
  • Access token secret

NOTE: should these keys and secrets be compromised new ones can be generated (which invalidates the previous ones).

Creating a bot in JavaScript

A very simple solution for a simple bot like this is creating a Node package in JavaScript. Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine that enables running JavaScript code outside the browser. Node comes with npm, which is a package manager for JavaScript.

Download and install Node.js: https://nodejs.org/en/
Learn more about npm: https://www.npmjs.com/

There is a Node package for the Twitter client API. It’s called twit and is very easy to use. The following is the only JavaSCript code you need to write to post a new tweet with the text “hello world!” on the registered account.

What you need to do here is fill in the API key and secret and the access token and secret with the ones generated for your app.

Creating a Node package

To create a new package go to an empty folder where you want to locate the package and run the npm init command in a console. This will prompt you to provide some information (some of which are already filled in for you).

There result is a file called package.json that describes the Node package and its dependencies.

To install the twit package for the Twitter client api run the following command in a console in the folder where the package is located:

The twit module and all its dependencies will be downloaded in this folder and the package.json file updated with the dependency:

Writing the bot

When we created the Node package we specified that the entry point should be a file called bot.js. We need to create this and fill it with the following code:

The function generateText creates the text to be posted in a tweet. It can do anything and for the sake of this post its content is irrelevant. Function tweetIt does a status update with a text generated by generateText. This function is executed both when the package is run the first time as well as every six hours (a timer is created with setInterval).

Running the bot locally

You can run the script locally in two ways:

  • By running the following command:
  • By adding a script to package.json and execuring that script.

    And then executing the following command:

It’s done

That is all that is necessary for a Twitter bot to run and post to a Twitter account. Of course, there are things that have been let aside, such as how to generate the content of the message, how to host the bot on a cloud platform, or how to write a bot that does more that posting text, such as posting images, replying, etc. But some of that in the next article.

, , , , , , Hits for this post: 1293 .

UPDATE: for an updated version of this demo, using C++ REST SDK 2.10 see this blog post.

In my previous post I shown how you can build a C++ application with the C++ REST SDK that fetches search results from a search engine. In this post, I will go a step further and develop a client-server application from scratch using version 1.1.0 of the SDK. This version features an HTTP listener implementation (still in an experimental phase). Notice that for the time being this 1.1.0 SDK release does not work with Visual Studio 2013 Preview. This samples are built with Visual Studio 2012.

Overview of the problem to solve

The server manages a dictionary of key-value pairs (both strings) and supports several HTTP request methods:

  • GET: retrieves all the key-value pair from the dictionary.
    The response is a JSON object representing key-value pairs (eg. {"one" : "100", "two" : "200"}).
  • POST: retrieves the values of the specified keys from the dictionary.
    The request is a JSON array of strings (eg. ["one", "two", "three"]).
    The response is similar to the GET method, except that only requested keys are returned.
  • PUT: inserts new pairs of key-values in the dictionary. If a key is already found its value is updated.
    The request is a JSON object representing pairs of keys and values (eg. {"one" : "100", "two" : "200"})
    The response is a JSON object representing they key and the result for the action, such as addition or update (eg. {"one" : "<put>", "two" : "<updated>"}).
  • DEL: deletes the specified keys from the dictionary.
    The request is a JSON array of strings (eg. ["one", "two", "three"]).
    The response is a JSON object representing they key and the result for the action, such as success or failure (eg. {"one" : "<deleted>", "two" : "<failed>"}).

Notice that the server implements both GET and POST. The GET method is supposed to request a representation of the specified URI. Though it is theoretically possible that a GET request carries a body, in practice that should be ignored. The C++ REST library actually triggers an exception if you make a GET request with a body. Therefore, GET is used to return the entire content of the dictionary and the POST method, that supports a body, returns only the requested key-value pairs.

The client can make HTTP requests to the server, adding or updating key-values, fetch or delete existing pairs.

All communication, both for the request and the answer, is done using JSON values.

The server implementation

On the server side we have to do the following:

  • instantiate an http_listener object, specifying the URI where it should listen for requests.
  • provide handlers for the HTTP request methods for the listener.
  • open the listener and loop to wait for messages.

The core of the server application is shown below (except for the request handlers).

In this simple implementation the dictionary is a std::map. Its content is not persisted to disk, it is reloaded each time the server starts.

Let’s now look at the handlers. As mentioned earlier the GET method is a bit different than the others. A GET request should return all the key-value pairs in the server’s dictionary. Its implementation looks like this:

What it does is iterating through the dictionary and putting its key-value pairs into a json::value::field_map. That object is then sent back the the client.

The POST, PUT and DEL methods are a bit more complicated, because they all receive a JSON value specifying either keys to fetch or delete or pairs of key-value to add or update in the dictionary. Since some code would get duplicated several times I have created a generic method for handling requests that takes a function that evaluates the JSON request value and builds the response JSON value.

The handlers for POST, PUT and DEL will then call this generic method providing a lambda with the actual core implementation of each request handling.

And that is all with the server.

The client implementation

On the client side we need a http_client object to make HTTP requests to the server. It has an overloaded method request() that allows specifying the request method, a path and a JSON value for instance. A JSON value is not sent if the method is GET (or HEAD). Since for each request the answer is a JSON value, I have created a method called make_request() that dispatches the request and when the response arrives it fetches the JSON value and displays it in the console.

The core of the client code looks like this:

In the main() function I then just make a series of requests to the server, putting, fetching and deleting key-values from the server’s dictionary.

The client and server in action

You need to start the server first and then run the client. The output from running the client is:

On the server console the output is:

, , , , , , Hits for this post: 51159 .

The C++ REST project provides a modern asynchronous C++ API for cloud-based client-server communication. It is available on codeplex and works with Visual Studio 2010 and 2012, but it is now distributed with Visual Studio 2013. The preview version of VS2013 deploys version 1.0 of the SDK. Since its release a new version of the SDK (v1.1.0) has been made available.

The following example shows how to retrieve and display some JSON content. I’m querying google using its REST API. Here is how a query (for a single result) may look:

https://ajax.googleapis.com/ajax/services/search/web?q=marius%20bancila&v=1.0&rsz=1

The result that we get is a JSON value. From this value I will only display the URL and the (un-formatted) title.

There are several things that we must do:

  • create a http_client that maintains the connection to a HTTP service
  • send a HTTP GET request asynchronous and wait for the response
  • when the response is available check its status code and if all is right extract the JSON value from the body of the response message (the content type must be application/json)
  • when the json value is available display its content

The code looks like this:

The following program retrieves 5 search results for “marius bancila”.

The output looks like this:

You can find documentation for the API and the SDK here.

, , , Hits for this post: 54147 .

Today I decided to give a try to Internet Explorer 9, currently in the Release Candidate phase, and available to download at http://www.beautyoftheweb.com. These are the impressions after the first day. I used it for my usual browsing activity, such as email, search, facebook, etc. No benchmarking or things like that. Unfortunatelly, I can’t say I’m impressed. I stumbled upon some issues and features that can’t help convincing me to drop Firefox and Chrome and use IE. Hopefully, at least some of them can be fixed until the RTM, though I have doubts. Here are some of them. Maybe in some case is the site’s fault, not the browser’s fault, but bottom line is that I want a nice browsing experience. If the browser is not able the display a page correctly, even if it’s the site’s fault, I’ll have to use another browser that is able to do so.

First, after the installation finished it asked to restart Windows! Why does a browser need a system restart? Even when you install a new driver you can use the device that needs it without restarting the system. But no, Internet Explorer need a restart.

Second, not that important, but does not score well in the aesthetic category, the big, round, Back button is cut at the bottom. If the button had to be made so big, why a circle? Why not something else that didn’t leave the impression it was too big to fit the bar?

The next thing that strikes is the blurriness of the text. On the most sites that I browsed today (the only exceptions being Amazon and some Google sites such as Reader, Documents, Picasa, but not Gmail) the text appears blurred. Here is a comparison between IE9 and Firefox 3.6.x for facebook.

When using Gmail, it is not possible to select any text in any email. Here is a comparative screenshot. Don’t know what IE9 has disabled by default, and I don’t care. This is an important feature that should always work, by default.

And speaking of Gmail, the text font used in the email editor is so small. Below is a screenshot from a reply to the previous shown email, but the same font size is used when composing a new email too.

Another problem I have experienced while writing this post. This might be the fault of WordPress, but does not happen with the other browsers. The Add an Image command is supposed to insert an image at the location of the caret in the text. However, in IE9 this is always added at the very beginning of the text.

I hope things will improve with the final release. And perhaps I will get better experience with media content (as IE brags). But so far I didn’t see something to make me set IE9 as my default browser.

, , Hits for this post: 18469 .

Facebook in Pirate English

Well, if you didn’t know there was a Pirate English you can find it on facebook. Scroll to the bottom of the facebook page, click on the language link and select English (Pirate).

A new world will unveil. For instance “What’s on your mind” becomes “What be troublin’ ye”, “Edit my Profile” becomes “Fix up Ye’ olde Vessel” and “Create a group” becomes “Fashion Yerself a Crew”. And many others.

Facebook gets my thumb-up for that! 🙂

, , Hits for this post: 16354 .

Google has unveil the next product they will launch later this year. It’s called Wave and it’s a communication protocol. It’s like the email of the 21st century, but much more than that. Wave is a collaborative product. The waves are communication objects, both conversation and documents, allowing people to almost instantly communicate on the web.

Waves allow people to send emails, but do it in an instant messaging style, sharing media like pictures and movies and being able to see live what the others are typing or sharing, and playback the entire conversation.

Wave is also an open source platform for building blogging sites or discussion groups. It provides APIs for collaboratively editing documents, building games (and playing back the moves), integrating with other communication systems (like twitter) and others.

To see what wave actually is, see this preview.

You can learn more about the waves here and here.

, Hits for this post: 19940 .

Microsoft Bing

There is a new search engine in town. It’s called Bing, and was created by Microsoft. Looks like they are going to invest massively in advertising it; according to AdAge, it will be between 80 and 100 million dollars.

You can find a short video here, with Stefan Weitz, the director of Windows Live, talking about what this new search engine bring new.

In addition you can find an article about comparison searches with Bing and Google, here.

Go Bing!

, , , Hits for this post: 30001 .

I am please to announce the launch of Sharparena.com, a developer community focused on the .NET framework and the # languages, C#, F# and J#.

This is an English site where you can ask questions about C#, F#, J# and the .NET framework in general, publish articles and stay up to date with news about the development on the .NET framework.

Here are some links:

On the main site you’ll find a series of FAQs about using the site. Consider reading the following for registering and publishing:

See you there!

, , , Hits for this post: 23975 .