Author Archives: stuart - Page 2

Getting paid to do something you love doing is awesome!

A lot of people who work, don’t like their job. It’s a fact. If you were at a party and you asked people if they like the job they get paid to do, the response would be largely negative. That you are reading this, on this blog, indicates that you are probably a programmer. Then, on the assumption that you are in some capacity employed as a programmer, I can say to you that you are a lucky person.

Why?

It is simple, really: A large percentage of the programmers I have met,  have worked with or follow on Twitter absolutely love to write code, whether it is for a website, a desktop application of some kind or they are just monkeying around with something. They love it! I love doing it. A number of my friends love doing it. And the best thing?

We get paid to do it!

Don’t get me wrong here, I know plenty of people who turn up at 9am and go home at 5pm and wouldn’t even consider writing anything for themselves or doing any open source work. For them, it’s like a factory job, albeit a (generally) much better paid one. Jeff Atwood (love him or loathe him) has a great post about these sorts of programmers titled “There are Two Types of Programmers”. Even though these programmers might not code in their spare time, I’d still say that 99% still like their job.

I’ll place myself firmly in that 20% block of programmers though. I wouldn’t say I was a rock star programmer, I’m certainly not bad, but I do always want to constantly improve myself and my ability. As the old saying, “Practice makes perfect”. I definitely love my job. Maybe I could do without some of the meetings and the office politics which comes from working in a large company, but still, I love what I do.

I get paid to do what I love doing; I consider myself lucky.

Damn you empty catch block

In the code I help maintain in my day job, I see a lot of the following code:

try
{
/* code */
}
catch(Exception)
{
}

I see it in several different languages almost daily. It really frustrates me that my colleagues and predecessors did this. I stamp it out ruthlessly.

Here is a great post on why empty catch blocks are bad. Here is a great question and series of answers on StackOverflow about best practices for exception handling.

Github C# API: Handling the response with RestSharp

Once we make a request to Github.com with RestSharp, we get a response, and RestSharp gives us a RestResponse object, with which we can do something with the content. The content will be in the format that we specified when we made the request, either JSON, XML or YAML.

Oh crap, complicated string parsing…

RestSharp to the rescue! We don’t have to worry about parsing the response content, because RestSharp can do it for us.

What we need to do, is model the response content into a POCO (Plain Old Clr Object):

public class User
{
	public virtual int Id { get; set; }
	public virtual string Login { get; set; }
	public virtual string Name { get; set;}

	...
}

Note that in this User class, I’ve made the properties virtual, this is not necessary for RestSharp to function correctly, it’s more habit on my part from working with NHibernate; however it does mean you can reuse the same models with NHibernate (if you wanted to do something like store the response in a database, for example).

Then we need to modify our client such that when we execute the request, we instruct RestSharp to construct an instance of the User object. Create the client in the usual way and also create the request in the usual way. The magic is in how the client executes the request:

var request = new RestRequest
				  {
					  Resource = string.Format("/user/show/{0}", username),
					  RootElement = "user"
				  };

var response = client.Execute<User>(request);

var user = response.Data;

As you can see, the Execute method has a generic overload. Internally, RestSharp detects that because we have used this overload, we want to deserialise the response content into an object of the given type, and it performs the deserialisation and constructs an instance of the object. The way that it does this is by looking at the Content-Type header in the response, and it uses the correct deserialiser depending upon the Content-Type. You can see more detail about this on RestSharp’s Github project pages.

It is really easy to work with the response from your REST request with RestSharp, you can access the raw string content of the response, or deserialise it into a POCO – it’s up to you.

Let’s write an API library for Github

Let’s write a C# API library for github.com.

Github has a REST base API, the details of which are available at develop.github.com. Before continuing, I should point out that there is an existing C# library already available, if you want to use that.

We’ll leverage John Sheehan’s excellent RestSharp library to do most of the heavy lifting.

Before we can really do anything, the first task at hand is to learn how to work with RestSharp, and how we can make a request and receive a response. Fortunately, RestSharp makes it really easy, and there are excellent resources on the project’s wiki page which explain how to do things. Let’s see a quick example:

[Test]
public void MakeBasicRequestToTwitterWithRestSharp()
{
	var client = new RestClient("http://api.twitter.com");
	client.UserAgent = "TemporalCohesion.TwitterApi";

	var request = new RestRequest();
	request.Resource = "statuses/public_timeline.json";

	var response = client.Execute(request);

	if (response.StatusCode == HttpStatusCode.OK)
	{
		String content = response.Content;

		Assert.That(content, Is.Not.Null);
	}
	else
	{
		Assert.Fail(response.StatusDescription);
	}
}

Here we are making an authenticated request to Twitter, asking for the public timeline in JSON format, but, the same code can easily be applied to github.com. We’ll see more of that later. First we create the client object, and then create the request object – telling it what resource to actually request, and then we execute the request using the client, and then do something with the response. Pretty straightforward, huh?

There is quite a lot that we can do with the Github API at this point, although you’ll quickly see that to do anything really interesting (i.e. modifying your github account, or creating/forking repo’s) requires you to be authenticated. Fortunately for us, Github uses HTTP Basic Authentication, and, RestSharp has a HttpBasicAuthenticator class, and if you put the two together, you can make an authenticated request to Github like this:

var client = new RestClient
				 {
					 BaseUrl = "https://github.com/api/v2/json",
					 Authenticator = new HttpBasicAuthenticator("test", "test")
				 };

After we set the authenticator, RestSharp takes care of making sure that the headers of the requests we make to Github’s API contain the necessary authentication which identifies us to Github. You’ll note that the BaseUrl here is set to https://github.com/…, so that we can take advantage of SSL. You can can access public data via normal http://, but if we are going to do anything that requires authentication, it will be best if we choose to use https://

Github also provide us with an API key. This is a unique key which identifies us to Github, and give our requests a little bit more security. We can’t set this key with RestSharp, as we need to modify the way the authorization header is generated when we make a request. What we can do though, is to implement our own IAuthenticator to do handle it for us. You can see my implementation up on Github. It’s fairly straightforward – I still wanted to allow basic username:password authentication, as well as username/token: authentication for Github.com. Let’s create a unit test to check everything is working OK.

How do we know if we have made an authenticated request successfully? If you make a request to Github for a user, and you are authenticated as that user, then as well as the standard user response, there is some additional information included in the responses that only you, as the authenticated user, can see. And we can check for this information in the response:

[Test]
public void MakeAuthenticatedRequest()
{
	var restRequest = new RestRequest
            {
                Resource = "/user/show/sgrassie"
            };

	var client = new RestClient
					 {
						 BaseUrl = "http://github.com/api/v2/json",
						 Authenticator = new GitHubAuthenticator(_secretsHandler.Username, _secretsHandler.Password, true)
					 };

	var response = client.Execute(restRequest);

	Assert.That(response.Content, Is.StringContaining("total_private_repo_count"));
}

The unit test is pretty straightforward, I make a request object which will get my user account, I authenticate the request and then execute it. Then I can simply check that the response content contains “total_private_repo_count” – this would only be returned if the request was an authenticated request.

One thing you might notice in the test is that in the GitHubAuthenticator constructor, I get my username and password/api token from the _secretsHandler object, an instance of a class I’ve written which will load my username, password and api key from an XML file. This is so that I don’t have to put my Github.com password and API key into the project’s Github repo, because that would be bad.

Unit Testing Events

Recently I have had to unit test some events in an application I work on. I came up with a workable solution, but I didn’t really like the way it was working, and it just looked ugly. So I did a little digging on Google, and found this helpful question on StackOverflow.

Here is my take it. I’m putting it here so I can find easily find it again. Basically it’s the same, but I’m using a lambda to create my anonymous delegate:

[Test]
public void UnitTestNodeChanged()
{
 var receivedEvents = new List<XmlNodeChangedEventArgs>();
 var document = new XmlDocument();

 document.NodeChanged += ((sender, e) => receivedEvents.Add(e));
 document.Load("C:\file.xml");

 Assert.That(receivedEvents.Count, Is.EqualTo(1));
}

Nice and short, and to the point. We can test the fact that the event was raised (or not); how many times the event was raised; and, we can test the event arguments.

I like it. Some people may not, but it suits my purposes.