Ryan Harrison My blog, portfolio and technology related ramblings

C# The Google Currency API Update

NOTE: The Google Finance API has now been deprecated so this code will no longer work

After testing out the code from the recent post on the Google Currency API, it became apparent that the code had one very significant bug that caused an exception to be thrown when the user enters a value that returns a result over the one million mark. For example -;

http://www.google.com/ig/calculator?hl=en&q=1000000gbp=?usd

which gives back this JSON object -;

{lhs: "1 000 000 British pounds",rhs: "1.6399 million U.S. dollars",error: "",icc: true}

As you can see, instead of returning just a decimal number, it gives a number followed by a String, which caused the previous program to crash.

In this case to fix the bug, the Regex needs to be modified so that it returns not only the number, but also the new String in the same match. With this information, the number can then be multiplied to give the final result as a single decimal.

The Regex now becomes -; rhs: \\\"((\\d|\\s|\\.)*)(\\s[^\\s]+)

(the cluster of backslashes are to escape the possible escape sequences of ‘/d’ and ‘/s’ for example)

The new Regular Expression makes use of ‘Groups’ to store the two pieces of data in the same match -; the first groups contains the number, and the third contains the String due to the way this pattern is designed (it’s probably possible to modify this, yet it doesn’t create too much of a problem and so isn’t worth the effort).

We can now produce a match from the response using the same code as before -;

WebClient client = new WebClient();

string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={0}{1}=?{2}", amount, from.ToUpper(), to.ToUpper());

string response = client.DownloadString(url);

Regex pattern = new Regex("rhs: \\\"((\\d|\\s|\\.)*)(\\s[^\\s]+)");  
Match match = pattern.Match(response);  

Once we have access to the match, we can extract the data into our own variables -;

string number = match.Groups[1].Value;  
number = number.Replace(((char)160).ToString(), "");

decimal num = System.Convert.ToDecimal(number);  
string units = match.Groups[3].Value.Replace(" ","");  

Here, the number is stored as a String from the first group and the ‘spaces’ are removed (for some reason in the returned String, ‘spaces’ have a Unicode value of 160, which is called the ‘Non-breaking space’). Next, the number is converted into a decimal and the units are extracted from the match and stored in the ‘units’ variable.

As the only possible values of the ‘units’ variable are ‘millions’, ‘billions’ and ‘trillions’, we can simply test the variable against each and multiply the number correspondingly to get the overall result. Finally, we just need to round the number to two decimal places to signify a currency, and return the value. Here is the full updated code which hopefully is bug free. The full source code can be found in GitHub.

using System;  
using System.Text.RegularExpressions;

public static class Currency  
{  
	public static decimal Convert(decimal amount, string from, string to)  
	{  
		WebClient client = new WebClient();

		string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={0}{1}=?{2}", amount, from.ToUpper(), to.ToUpper());

		string response = client.DownloadString(url);

		Regex pattern = new Regex("rhs: \\\"((\\d|\\s|\\.)*)(\\s[^\\s]+)");  
		Match match = pattern.Match(response);

		string number = match.Groups[1].Value;  
		number = number.Replace(((char)160).ToString(), "");

		decimal num = System.Convert.ToDecimal(number);  
		string units = match.Groups[3].Value.Replace(" ","");

		if(units.Equals("million"))  
		{  
			num *= 1000000;  
		}  
		else if (units.Equals("billion"))  
		{  
			num *= 1000000000;  
		}  
		else if (units.Equals("trillion"))  
		{  
			num *= 1000000000000;  
		}

		return Math.Round(num, 2);  
	}  
}  
Read More

C# - The Google Currency API

NOTE: The Google Finance API has now been deprecated so this code will no longer work

After I found myself using Google to translate currencies, I wondered whether it would be possible to utilise this functionality in a program. After a little research it turns out that Google offer a huge API that deals with currencies and finance. For the purpose of this post I will show you how to convert currencies, yet you can also use the API to find stock information and even market gains over a period.

Although here I will be using C#, it should be possible to use pretty much any language and get the same results.

This particular feature can be utilised through a simple URL containing the amount to convert from, the currency to convert from, and the currency to convert to. This translates into this URL -;

http://www.google.com/ig/calculator?hl=en&q={AMOUNT}{FROM}=?{TO}

For example -;

http://www.google.com/ig/calculator?hl=en&q=1GBP=?USD

(which converts 1 British Pound to US Dollars) returns the following -;

{lhs: "1 British pound",rhs: "1.6121 U.S. dollars",error: "",icc: true}

The URL responds with a JSON object where the actual result is mixed in with some other information from the request, which presents a minor problem when trying to convert currencies in our program. This will be dealt with a bit later on.

First of all in our program, we to get the output of the request. I used the WebClient class, which will download the response as a String for use in our program. In the following code, the URL is constructed with parameters passed in by the user, and the string is downloaded and stored in the ‘response’ variable.

using System;

public static class CurrencyConverter  
{  
	public static decimal Convert(decimal amount, string from, string to)  
	{  
		WebClient web = new WebClient();

		string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={0}{1}=?{2}", amount, from.ToUpper(), to.ToUpper());

		string response = web.DownloadString(url);  
	}  
}  

This takes care of getting the response with the answer we want, yet we still need to somehow extract the correct data from the string. In this example I will use Regular Expressions however if your prefer not to use them, or your language does not natively support them, it would be perfectly viable to loop through the response one character at a time, and parse out the result.

The Regex pattern will look like this -;

rhs: \\\"(\\d\*.\\d\*)

This pattern essentially searches for the ‘rhs’ which appears just before the result value, and extracts any numbers afterwards until any non-numeric character is reached.

Using the Regex to extract the result, we end up with the following, final code -;

using System;  
using System.Text.RegularExpressions;

public static class CurrencyConverter  
{  
	public static decimal Convert(decimal amount, string from, string to)  
	{  
		WebClient web = new WebClient();

		string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={0}{1}=?{2}", amount, from.ToUpper(), to.ToUpper());

		string response = web.DownloadString(url);

		Regex regex = new Regex("rhs: \\\"(\\d\*.\\d\*)");  
		Match match = regex.Match(response);

		return System.Convert.ToDecimal(match.Groups[1].Value);  
	}  
}  

The full source code can be found in GitHub.

Thats about it for the Google Currency API for now, however I may post snippets on how to use some other features of the extensive API’s Google offer soon.

More Information about the Google Finance API

Read More

Compile from the Command Line

It’s sometimes frustrating when you want to compile and test a short snippet of code, yet find yourself modifying an existing project or even creating a whole new one just to compile the code. Most developers write and compile their code straight from their IDE of choice and never bother compiling from the command prompt. For most situations this is sensible, however in some specific scenarios the command line can save you time when it’s not feasible to modify or create a new project. In this short tutorial I will show you how to compile your Java, C# and C++ code straight from the command line, including all the necessary tweaks of your Environment Variables.

Java

The first language is Java. I will assume that you have the JDK (Java Development Kit) installed, as this is the package that includes the Java compiler.

The first step is to navigate to the installation directory of your JDK installation and copy the path to the bin folder which resides inside. The path should look a bit like this (depending the version of the JDK you have installed) -

JDK Path

Once you have the path in the clipboard, you have to add it to your system’s Environment Variables, which will essentially allow you to run the Java compiler from anywhere on your computer.

In Windows 7, click the Start orb and right click on the Computer shortcut and click on Properties in the context menu. This should take you to a window that looks something like this -

System Properties

Then, click on Advanced System Settings on the right hand side. Under the Advanced tab of the new window, click on Environment Variables….

Next, you want to locate the variable named Path in your System Variables. If you don’t have one, click on the new button to create a new variable (make sure you name it Path). With it selected, click on edit. A new window pops up showing the value of the Path variable. Navigate to the end of the value string and add a semi-colon to signify a new entry.

Finally, simply paste in the path to the JDK’s bin directory and click on OK. The value field should look a little like this -

JDK Environment Variable

We have now configured your system to allow you to compile Java programs from any directory on you hard drive.

To use the compiler from the command line, open up a new command prompt window by typing cmd in the Run box (or search box in the Windows 7/Vista start menu).

Type in javac (stands for Java Compiler) and hit enter. You should see a lot writing being printed to the window. It should look a little like this -

Java Compiler

This signifies that you can actually use the compiler and that you have successfully followed the previous steps.

In this example I will compile and run a simple ‘Hello World!’ program from the desktop.

  
public class javacomp  
{  
  public static void main(String[] args)  
  {  
    System.out.println("Hello World!");
  }  
}  

Save this Java source file to any directory on your computer, (in this case my Desktop) and again open up a command prompt window.

Next, navigate to the directory of your source file using the cd command.

e.g - cd C:\Users\YourUserName\Desktop

When this is done, type javac again, yet this time followed by the name of the source file you just created, (make sure you add the .java extension) and hit enter. If there are no syntax errors you should see a new .class file in the same directory. This is where the compiled bytecode is stored. Finally, to run the program type java and the name of the .class file (this time no need to add the extension). The program will now run the window and you should see something like this -

Compiling and Running the Java Program

More information about the Java compiler, including the many command line arguments.

C#

Next for C#. This is pretty much the same as for Java apart from a different path to the compiler.

In this case you need to copy the path to the .NET Framework folder in the root Windows folder. The path should be a bit like this depending on the version of the .NET framework you have installed -

The Path to the .Net Framework installation

Read More

C# - Auto Clicker

I recently got a link to a Facebook app which challenges you to how many times you can click a button in 30 seconds. After a couple of tries I got to around 180, yet I thought that I must be able to do better by making the computer click for me.

After a bit of research I came across two functions from MSDN named SendInput and mouse_event, both of which are provided in the Win32 API, and allow you to programatically simulate both mouse clicks and keyboard input. Thus I thought it was a great opportunity to try out C#’s p/invoke feature which allows the programmer to ‘import’ unmanaged functions from DLL libraries and use them in a C# application.

In this example I will only be using the mouse_event function, however an implementation of SendInput is included in the sources files, which are available for download at the bottom of this post.

The MSDN page of the mouse_event function gives us some good information on how to implement the function, including a function header and a rundown on each of the parameters. They give the mouse_event function the following header -

  
VOID WINAPI mouse_event(  
  __in DWORD dwFlags,  
  __in DWORD dx,  
  __in DWORD dy,  
  __in DWORD dwData,  
  __in ULONG_PTR dwExtraInfo  
);  

Which can then be imported for use in our C# application using using the DLLImport attribute and the extern keyword (which simply indicates that the method is implemented externally) -

  
[DllImport("user32.dll")]  
public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);  

We can now call this unmanaged function as we would any other method already in our project. However to make good use of them, we need to find out a bit more information on each of the parameters.

They can be summed up as follows -

  • dwFlags - In our case this parameter specifies which mouse button we would like to press depending on the integer value we pass
  • dx - The relative mouse position along the x-axis
  • dy - The relative mouse position along the y-axis
  • dwData - Contains how much we would like to move the mouse wheel and in which direction
  • dwExtraInfo - Contains extra information on the function call (not needed in our case)

In the case of this example we only have a need for the dwFlags parameter as we can easily set the cursor position using C# -

  
Cursor.Position.X = ...
Cursor.Position.Y = ...

Before we finally call this method, it is a good idea to declare some constants, each describing which mouse button we would like to press. Details can again be found on the relevant MSDN page -

  
public const int MOUSEEVENTF_LEFTDOWN = 0x0002;  
public const int MOUSEEVENTF_LEFTUP = 0x0004;  
public const int MOUSEEVENTF_RIGHTDOWN = 0x0008;  
public const int MOUSEEVENTF_RIGHTUP = 0x0010;  
public const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;  
public const int MOUSEEVENTF_MIDDLEUP = 0x0040;  

Finally we can now call the function, which will be wrapped into two methods -

private void ClickLeftMouseButtonMouseEvent()  
{  
  //Send a left click down followed by a left click up to simulate a  
  //full left click  
  mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);  
  mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);  
}

private void ClickRightMouseButtonMouseEvent()  
{  
  //Send a left click down followed by a right click up to simulate a  
  //full right click  
  mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);  
  mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);  
}  

As you can see we actually need to call the function twice, once for the mouse down action, and again for the mouse up action, to simulate a full mouse click. In this example we only use the dwFlags parameter and pass zero for the rest as we have no need for them.

So we now have two methods that we can use to simulate a mouse click, yet no way of letting the user determine where to click, how many times to click, and what mouse button to click - the perfect chance to create a C# Windows Forms Application (a.ka. GUI) to make our program a little more presentable.

In my program, I have created a simple User Interface containing a list view, a few buttons, and a couple of textboxes, which will allow the user to specify a queue of points to click in sequence, as well as the ability to insert additional information for each click (button to press, time in between, etc).

Screenshot of the final Auto Clicker program

Read More

Hello world!

Welcome to my blog! Stay tuned for posts on software development, animation and current technology…

Read More