All posts filed under “Code

comment 0

Apache with PHP on a Windows Machine


The program can’t start because LIBPQ.dll is missing from your computer. Try reinstalling the program to fix this problem.

If you’re getting the above error when starting Apache after installing Apache and PHP on your Windows machine, go to your PHP install directory (e.g. c:Program Files (x86)PHP) and copy the file libpq.dll into the bin directory under the Apache install directory (e.g. C:Program Files (x86)Apache Software FoundationApache2.2bin).

comment 0

Using Better Naming to Clarify Code

I’m a big fan of good naming in code, here’s a recent example:

Suppose you have a unique index in a database table and you’re trusting that index to enforce no more than one record with the key.

So you’re using an insert ignore into…on duplicate key update statement.

So you end up calling something like DataAccess.InsertRecord(data) or DataAccess.AddRecord(data). Looking at such code it’s very unclear that what really happens is an insert/update and you’re only left with one record.

You can go the way of making your code explicit my moving the logic into your app and doing something like

var record=DataAccess.GetRecord(key);
if(record == null)
  DataAccess.InsertRecord(data);

But then you’ll be losing the power of using the database do that for you.

So what I’m suggesting is just making your naming better, for example: DataAccess.ReplaceRecord(data).

comment 0

Make the Ugly Scrollbars on your Facebook App Disappear

If you have annoying scrollbars around your Facebook app’s canvas, here’s what you need to do:

First, go to your app’s settings, click “Edit App” and then “Advanced” on the right.

Scroll all the way down to “Canvas Settings” and change “Canvas Height” to “Settable”.

Second, add a call to FB.Canvas.setSize() (http://developers.facebook.com/docs/reference/javascript/FB.Canvas.setSize/). Make this call inside window.fbAsyncInit, after calling FB.init.

That’s it! Gorgeous app, no scrollbars!

comment 0

Adaptive Payments Error This transaction has already been approved

If you’re using the PayPal Adaptive Payments API in sandbox mode, redirecting the user to https://www.sandbox.paypal.com/cgi-bin/webscr and getting the following error:

This transaction has already been approved

The problem may be that you’re using an incorrect sandbox user as the “sender” in the transaction.

You need to go to the sandbox (https://developer.paypal.com/) and then to “test accounts” on the left.

You need to create a test account. Click “preconfigured” next to “new test account” and then make sure you select “buyer” under “account type”.

Now use the email of this account that you’ve just created as the “senderEmail” in the call to the “Pay” API operation.

comment 0

Code Sample: Consuming the Twitter Streaming API

Here’s a c# example of consuming the Twitter Streaming API.
Suppose you want to take all Tweets mentioning a country and save it to a database.
I will be using the Twitterizer c# library. Let’s first look at the complete code and then walk through it:

private static bool streamEnded = false;
public static void HandleStream()
{
  DateTime end = DateTime.Now + TimeSpan.FromSeconds(60);

  OAuthTokens tokens = new OAuthTokens { ConsumerKey = “YOUR_KEY”, ConsumerSecret = “YOUR_SECRET”, AccessToken = “ACCESS_TOKEN”, AccessTokenSecret = “ACCESS_TOKEN_SECRET” };
  TwitterStream s = new TwitterStream(tokens);
  s.OnStatusReceived += new TwitterStatusReceivedHandler(s_OnStatusReceived);
  s.OnStreamEnded += new TwitterStreamEnded(s_OnStreamEnded);
  FilterStreamOptions ops = new FilterStreamOptions { Track = new List<string> { “italy”, “germany”, “spain”, “france”, “england” } };
  s.StartFilterStream(ops);

  while (DateTime.Now < end && !streamEnded)
     Thread.Sleep(1000);
 

  s.EndStream();
}
static void s_OnStreamEnded()
{
   streamEnded = true;
}
static void s_OnStatusReceived(Twitterizer.TwitterStatus status)
{
  SaveTweetToDatabase(status);
}

Now let’s look at the code in depth. First, as we’ll be processing tweets in a loop, let’s set an end to our loop. Let’s say we want to process tweets for 60 seconds:

DateTime end = DateTime.Now + TimeSpan.FromSeconds(60);

Next, we setup the Twitterizer class used to handle the Streaming API:

OAuthTokens tokens = new OAuthTokens { ConsumerKey = “YOUR_KEY”, ConsumerSecret = “YOUR_SECRET”, AccessToken = “ACCESS_TOKEN”, AccessTokenSecret = “ACCESS_TOKEN_SECRET” };
TwitterStream s = new TwitterStream(tokens);

The class TwitterStream is part of the “addons” to Twitterizer, so you will need to download the source of the 2.3.2 release of Twitterizer and make a small fix as I described here.
You will pass to TwitterStream the app keys of your Twitter application which you set up here and the OAuth tokens.
Next, we set up event handlers for the stream of tweets:

s.OnStatusReceived += new TwitterStatusReceivedHandler(s_OnStatusReceived);
s.OnStreamEnded += new TwitterStreamEnded(s_OnStreamEnded);

s_OnStatusReceived will be called by TwitterStream when a tweet is received from Streaming API and s_OnStreamEnded will be called when the connection to Twitter ends.
Next, we may add some options to the Streaming API. There are several methods to access the Streaming API: you can either get tweets for a list of keywords, a list of users or a random sample of all tweets. In our example, let’s ask Twitter for tweets mentioning a country and open the connection:

FilterStreamOptions ops = new FilterStreamOptions { Track = new List<string> { “italy”, “germany”, “spain”, “france”, “england” } };
s.StartFilterStream(ops);

The last thing to do is wait for the amount of time we decided on in the beginning and then close the stream:

while (DateTime.Now < end && !streamEnded)
     Thread.Sleep(1000);
 
s.EndStream();

comment 0

Twitter API .Net Libraries Roundup

Out of the few Twitter API libraries for .net out there, the ones that seem most complete are: Twitterizer and TweetSharp.
I’ve been developing with both in the past couple of weeks and both are generally stable, complete and provide a clean one-per-one wrapper for the Twitter API methods. Which is great news ™.
TweetSharp currently does not support the Streaming API, which is a major drawback and the reason why I am sticking with Twitterizer for now.

I recommend using the latest 2.3.1 source code of Twitterizer.

Small but important note: Twitterizer’s team is not currently officially supporting the Streaming API, so to use it (in assembly Twitterizer2.Streaming) – comment out the following line at the end of TwitterStream.StartStream:

request.Abort();

Otherwise – it will not work.

comment 0

Twitter API Rate Limiting

Reading http://dev.twitter.com/pages/rate-limiting, here are the major points:

REST API

  • Anonymous calls (things like users/show – get a user’s info) are limited to 150/hour, that’s 3,600/day. This limit is IP-based.
  • Authenticated calls (like a user’s home timeline) – 300/hour. Limit based on your app key.

Those rates are useful for a single-user app (something like TweetDeck), not useful for something like an app that crawls Twitter.
You can ask to be white-listed using this form: http://twitter.com/help/request_whitelisting.
If approved – you get 20,000 requests / hour. That’s more useful.

Search API

  • The rates are limited but to a higher rate than the REST API. The exact number is not disclosed.
  • Important to include a User Agent parameter, otherwise you will get a lower limit.

Streaming API

  • This is what you really need for high-volume Twitter polling. Gives you a sampling of all tweets based on optional filter you pass (e.g. user, keyword, location).
  • Have three access levels, based on what Twitter decides to give you: Spritzer (about 1% of everything), Gardenhose (10%) and Firehose (everything).