Archive for the ‘Software Development’ Category

Java Live Messenger (MSN) Robot

Thursday, September 2nd, 2010

I recently had a project to setup an Instant Messenger Robot for Windows Live Messenger. A IM robot can have many purposes such as:

  • Keeping track of when contacts are online/offline and when they were last seen.
  • Broadcasting a message to all contacts.
  • Automatically answering common questions.
  • Notifying contacts about new events. A newer site http://notify.me has a nice IM Robot that notifies you when a RSS feed is updated. This works well in conjuction with sites like craigslist.
  • Keeping track of code snippets
  • Checking the weather
  • Checking server status

An IM robot can be setup to automate just about any task.

What IM Library to Use

Setting up a IM robot can be a bit of work especially if starting from scratch. There are a lot of libraries out there that can be used to help simplify the process. The trouble is a lot of libraries are not kept up to date and fail to work as IM protocols change.

I did some digging and found a library that would provide a good foundation to build a IM Robot that can do just about anything. I saw implementations in PHP, C, Java, Perl and Python. After some testing I concluded the Java MSN Library would be a very good fit.

How To Use It

Using this library with java is pretty straight forward. First, the library must be added to the classpath. The step to take to complete this will depend on how your developing your java code. The most basic method to add a library to your classpath is to do this at run time with a command such as:

java -classpath MyLibrary.jar MyPackage.MyClass

A better approach would be to setup the classpath in a manifest file. The manifest file is then placed inside the jar file and tells the executable jar where to look for the libraries. This manifest file should look something like the following (note the class-path on line 5):

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 14.3-b01 (Sun Microsystems Inc.)
Main-Class: imstatus.Main
Class-Path: lib/jml-1.0b4-full.jar lib/httpcore-4.0.1.jar lib/mysql-co
 nnector-java-5.1.6-bin.jar
X-COMMENT: Main-Class will be added automatically by build

This is setup so that the 3 required libraries are in the lib folder. These 3 libraries are needed for setting up an IM robot and can be downloaded from the following locations:

Now that the libraries are setup we can begin to use them.

Developing the IM Robot Code

There are a few examples of using the Java MSN Library on the main page. However, they are a tad confusing as it creates a new BasicMessenger class. This is confusing as the library already has a BasicMessenger class which is abstract. The library also has a SimpleMessenger class which is a subclass of BasicMessenger. This class appears to be the correct implementation that we would want to use to create a new IM Robot. However, the original authors made the constructor protected so that we cannot instantiate the class outside of the original package. Since we want a simple way to create an IM Robot I have modified the original source code to have a public constructor for the SimpleMessenger class. This new package can be downloaded from our server.

With this new package we can very easily create a new IM Robot with the following two lines of code (make sure to replace yourLogin and yourPassword):

SimpleMessenger messenger = new SimpleMessenger(Email.parseStr("yourLogin@msn.com"), "yourPassword");
messenger.login();

With that code in our main funtion we can run it and test that the Robot automatically logs into Windows Live Messenger.

Of course, that code just logs the Robot into Windows Live Messenger. The next step is to setup the robot to do something interesting. This is one feature that is very nice about the Java MSN Library as it has listeners for many different events. For example we can detect when the robot has finished logging in with the following:

messenger.addListener(new MsnAdapter() {
	// Setup the login completed event

	@Override
	public void loginCompleted(MsnMessenger messenger) {
		MsnOwner owner = messenger.getOwner();
		owner.setInitStatus(MsnUserStatus.ONLINE);
		owner.setStatus(MsnUserStatus.ONLINE);

		// Setup the contact list event
		messenger.addContactListListener(new ContactListAdapter());
	}
});

Then we can take this a step further and detect when a status changes for one of the robots contacts with something like the following:

messenger.addListener(new MsnAdapter() {
	// Setup the login completed event

	@Override
	public void loginCompleted(MsnMessenger messenger) {
		MsnOwner owner = messenger.getOwner();
		owner.setInitStatus(MsnUserStatus.ONLINE);
		owner.setStatus(MsnUserStatus.ONLINE);

		// Setup the contact list event
		messenger.addContactListListener(new ContactListAdapter());
	}
});

The above code will detect when the robot has finished logging in and then setup a new listener to detect when a contacts status has changed. The new listener invokes the ContactListAdapter class when a status has changed. This contactListAdapter class is setup as followes:

class ContactListAdapter extends MsnContactListAdapter {
	@Override
	public void contactStatusChanged(MsnMessenger messenger, MsnContact contact) {
		System.out.println(contact.getEmail()+" is currently "+contact.getStatus());
		// Can add code here to store the status in a database
	}
}

We can still take this a step further and setup the robot to handle automatically adding contacts when a contact requests it. This logic can be added to the ContactListAdapter class with something like the following:

class ContactListAdapter extends MsnContactListAdapter {
	@Override
	public void contactListSyncCompleted(MsnMessenger messenger) {
			MsnContact[] contacts = messenger.getContactList().getContactsInList(MsnList.AL);
			for (int i = 0; i < contacts.length; i++) {
				contactStatusChanged(messenger,contacts[i]);
			}
	}

	@Override
	public void contactAddedMe(MsnMessenger messenger, MsnContact contact) {
		messenger.addFriend(contact.getEmail(), contact.getDisplayName());
	}

	@Override
	public void contactAddedMe(MsnMessenger messenger, MsnContactPending[] pending){
		for(int i=0; i<pending.length; i++){
			messenger.addFriend(pending[i].getEmail(), pending[i].getDisplayName());
		}
	}

	@Override
	public void contactStatusChanged(MsnMessenger messenger, MsnContact contact) {
		System.out.println(contact.getEmail()+" is currently "+contact.getStatus());
		// Can add code here to store the status in a database
	}
}

There you have it! Put all of the above code together and you will have a robot that knows how to automatically add contacts and keep track of when a contact’s status changes.

This article was cross-posted from Software Projects

UltraMon Breaks After Remote Desktop Connection (RDP)

Tuesday, April 6th, 2010

I use the application UltraMon to help manage my multiple monitor setup. Overall this application is awesome as it makes moving applications between monitors a breeze and supports a separate task bar on each monitor, among other things.

However, I have had this issue for a while where UltraMon will not move applications between monitors after a Remote Desktop Connection has been established, instead UltraMon acts as if there is only one monitor.

In the past the only solution I had for this issue was to restart my computer. This is not an ideal solution for me as I’m often multi-tasking and running many applications at the same time.

In order to reboot I have to close down each application, save my work, reboot, and then start up every application again after the reboot. This is not a major amount of time but it does add up if I have to do it on a regular basis. Plus, I am one who likes to optimize everything to achieve as much efficiency as humanly possible in a given day.

So, I spent a few minutes and fiddled with UltraMon and found a way to fix this RDP flaw without requiring a reboot. The steps are as follows:

  1. Close UltraMonsshot-2010-04-05-[5]
  2. Right click on your desktop and select Screen Resolution
  3. Disable the monitor that the application cannot be moved to and click apply (screenshot on right). Repeat for all monitors that are suffering from this issue.
  4. Start UltraMon
  5. Enable all monitors that were disabled in step 3.

After completing the above steps UltraMon will be as good as new.

I have only tested this on Windows 7 so let me know if this works on other Windows versions as well.

Anyone up for automating the above steps? If I get a break I might try and tackle it.

Format Credit Card with X’s and Dashes using PHP (credit card masking)

Monday, March 22nd, 2010

I recently had a project where I needed to accomplish the following two tasks:

  1. Replace all but the last four digits of a credit card with X’s
  2. Format the credit card with dashes in the appropriate places

There are many different approaches that can be taken to accomplish the above two tasks. The simplest approach would be to do something like the following:

<?php
echo 'XXXX-XXXX-XXXX-'.substr($cc,-4);
?>

I have often seen credit cards masked with the above approach. For the most case this solution will work fairly well. However, I am not a huge fan of this approach as it displays the credit card at a fixed length of 16 digits. This can be a bit confusing since credit cards can very in length from 13 to 16 digits.

To better address this issue I put together two functions. One function is to apply a mask to a credit card and the other is to format the credit card with dashes. These functions will keep the original length of each credit card.

<?php

/**
 * Replaces all but the last for digits with x's in the given credit card number
 * @param int|string $cc The credit card number to mask
 * @return string The masked credit card number
 */
function MaskCreditCard($cc){
	// Get the cc Length
	$cc_length = strlen($cc);

	// Replace all characters of credit card except the last four and dashes
	for($i=0; $i<$cc_length-4; $i++){
		if($cc[$i] == '-'){continue;}
		$cc[$i] = 'X';
	}

	// Return the masked Credit Card #
	return $cc;
}

/**
 * Add dashes to a credit card number.
 * @param int|string $cc The credit card number to format with dashes.
 * @return string The credit card with dashes.
 */
function FormatCreditCard($cc)
{
	// Clean out extra data that might be in the cc
	$cc = str_replace(array('-',' '),'',$cc);

	// Get the CC Length
	$cc_length = strlen($cc);

	// Initialize the new credit card to contian the last four digits
	$newCreditCard = substr($cc,-4);

	// Walk backwards through the credit card number and add a dash after every fourth digit
	for($i=$cc_length-5;$i>=0;$i--){
		// If on the fourth character add a dash
		if((($i+1)-$cc_length)%4 == 0){
			$newCreditCard = '-'.$newCreditCard;
		}
		// Add the current character to the new credit card
		$newCreditCard = $cc[$i].$newCreditCard;
	}

	// Return the formatted credit card number
	return $newCreditCard;
}

?>

Below are a couple examples of how to use these functions and the results they create.

<?php
echo maskCreditCard('5362267121053405').'<br>'; // Prints XXXXXXXXXXXX3405
echo formatCreditCard('5362267121053405').'<br>'; // Prints 5362-2671-2105-3405
echo formatCreditCard(maskCreditCard('5362267121053405')).'<br>'; // Prints XXXX-XXXX-XXXX-3405
?>
<?php
$creditCard[] = '5362267121053405'; // Mastercard
$creditCard[] = '4556189015881361'; // Visa 16
$creditCard[] = '4716904617062'; // Visa 13
$creditCard[] = '372348371455844'; // American Express
$creditCard[] = '6011757892594291'; // Discover
$creditCard[] = '30329445722959'; // Diners Club
$creditCard[] = '214927124363421'; // enRoute
$creditCard[] = '180012855304868'; // JCB 15
$creditCard[] = '3528066275370961'; // JCB 16
$creditCard[] = '8699775919'; // Voyager

for($i=0;$i<count($creditCard);$i++)
{
	echo FormatCreditCard(MaskCreditCard(($creditCard[$i])))."\n";
}
?>

Output:

XXXX-XXXX-XXXX-3405
XXXX-XXXX-XXXX-1361
X-XXXX-XXXX-7062
XXX-XXXX-XXXX-5844
XXXX-XXXX-XXXX-4291
XX-XXXX-XXXX-2959
XXX-XXXX-XXXX-3421
XXX-XXXX-XXXX-4868
XXXX-XXXX-XXXX-0961
XX-XXXX-5919

Let me know if you find these functions useful or have any suggestions on how to tweak them.

Update .htaccess with Dynamic DNS IP Address to Prevent Password Protection

Tuesday, March 9th, 2010

I was working on a password protected site that needed to allow one specific user access without requiring a login/password to access it. The site was already using .htaccess to password protect the entire site so the quickest solution was to use the following type of setup in the htaccess file:

Order deny,allow
Deny from all
AuthGroupFile /dev/null
AuthName "A Blog"
AuthType Basic
AuthUserFile /home/admin/domains/domain.com/.htpasswd/public_html/.htpasswd
require valid-user
Allow from person.getmyip.com
Satisfy Any

The main addition that I added to the password protection is line 8 “Allow from”. This line allows a specific IP address or host to have access without requiring password protection.

However, the host that needed to be used was a Dynamic DNS hostname. This creates a problem as Apache takes the following steps when the user requests access.

  1. Grab IP from user requesting access
  2. Do a reverse DNS lookup
  3. Compare the results to the host in the Allow from line (person.getmyip.com)

In this case when a reverse DNS lookup is completed on the users IP address it will not find the Dynamic DNS hostname. Instead, it will find the hostname that is associated with your ISP which might look something like this 8.sub-79-231-223.myvzw.com.

There are a number of ways to get around this issue. In my case I wanted to use a small script to dynamically populate the .htaccess file with the correct IP address.

Below is the following PHP script that handles updating .htaccess with the latest IP address. The main requirement is that there is a comment “# Allow from person.getmyip.com” somewhere in the .htaccess file. This line tells the script where to insert the IP address on the very next line.

<?php
// Rewrites the entire htaccess file. When a line starts with '# Allow from brett.getmyip.com' the
// very next line will be replaced with the actual ip associated with brett.getmyip.com
$htaccessFile = "/home/admin/domains/batie.com/public_html/.htaccess";
$handle = fopen($htaccessFile, "r");
if ($handle) {
	$previous_line = $content = '';
	while (!feof($handle)) {
		$current_line = fgets($handle);

		if(stripos($previous_line,'# Allow from person.getmyip.com') !== FALSE)
		{
			$output = shell_exec('host person.getmyip.com');
			if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
			{
				$content .= 'Allow from '.$matches[0]."\n";
			}
		}else{
			$content .= $current_line;
		}
		$previous_line = $current_line;
	}
	fclose($handle);

	$tempFile = tempnam('/tmp','allow_');
	$fp = fopen($tempFile, 'w');
	fwrite($fp, $content);
	fclose($fp);
	rename($tempFile,$htaccessFile);
	chown($htaccessFile,'admin');
	chmod($htaccessFile,'0644');
}
?>

I quickly wrote this script and realize that there is room for improvement. However, this meet the need and solved the problem.

After the script was completed adding a simple line to the crontab (crontab -e) file got it running on a regular basis to automatically update the file with the current IP.

# Script to update ip access for dynamic dns host - it allows person.getmyip.com
*/5 * * * * /usr/local/bin/php /home/admin/scripts/allow_person.php >/dev/null 2>&1

Paste Code – Live Writer Plugin To Paste HTML/Code

Saturday, March 6th, 2010

I recently started using Windows Live Writer and I believe it is currently the best application out there for quickly posting to a blog. However, I found one issue where I could not easily paste HTML and other code and decided to develop a plugin to address it.

If your in a hurry here is the download link:

DOWNLOAD: Paste Code For Windows Live Writer

The Issue

Below is an example of some code I would like to paste into Live Writer.

<html>
<head>
	<title>Hello World</title>
</head>
<body>
	Hello World
</body>
</html>

When I try to paste the above code in the "Edit" window. It appears correctly on the screen but in reality Live Writer added content to my code. When I view the source I receive the following:

&lt;html&gt;
  <br />&lt;head&gt;

  <br />&#160;&#160;&#160; &lt;title&gt;Hello World&lt;/title&gt;

  <br />&lt;/head&gt;

  <br />&lt;body&gt;

  <br />&#160;&#160;&#160; Hello World

  <br />&lt;/body&gt;

  <br />&lt;/html&gt;

This is very close to how I desire to have the code formatted. However, the major problem is it inserted a bunch of <br /> characters. It does make sense that it inserted these <br />’s since in most cases we want line returns to have breaks but this is not the case when pasting source code.

Next, if I paste the code in the "Source" window the problem is the code is taken as actual source. This means that the code will not be seen on the screen but instead will be interpreted by the browser. If I then swap back and forth between the "Edit" and "Source" windows my code gets reformatted to be the following:

Hello World

Which is obviously not what I wanted.

Solution: A Plugin

To address the issues stated above I put together a plugin that will allow pasting code in either the "Edit" or "Source" windows. It will replace special characters so that the code will be viewable and will not insert extra HTML (like <br />’s).

Below is a screenshot of the plugin in action:

sshot-2010-03-06-[3]

This plugin will automatically take the code that exists on the clipboard and display it in the "Code Snippet" section and give the ability to edit the code before pasting it.

It also has the "Before Code Snippet" and "After Code Snippet" text areas. These two text areas allow defining code to wrap around your code snippet. By default the two box’s will have <pre> and </pre>. Using either a <pre> or a <textarea> is required in order to have the formatting display correctly. If the content of "Before Code Snippet" and "After Code Snippet" is changed it will be remembered the next time the plugin is used.

Once insert is clicked in the plugin the code will be added to your post in Windows Live Writer and will be formatted correctly.

DOWNLOAD: Paste Code For Windows Live Writer

Icing On Top

With this plugin in place we can easily paste code and not worry about the formatting. However, it is very beneficial to have the source code displayed on your blog with syntax highlighting. I do know that there are a few plugins for Windows Live Writer that will apply syntax highlighting to code. However, I do not love this for the following reasons:

  1. Will not work when writing an article from blog’s admin page.
  2. Will not easily allow changing the Syntax Highlighting to a different algorithm. There are a ton of different Syntax Highlighting plugins for blogs and every once in a while I like to upgrade to the the latest and greatest.
  3. Will not work if I decide I want to move away from Windows Live Writer (that will never happen, right?).

For my blog I am using the syntax highlighter developed by Alex Gorbachev. There is also a nice plugin that quickly installs this syntax highlighting in a wordpress blog. With the paste code plugin for Windows Live Writer in combination with syntax highlighting I can quickly paste code and achieve the following results:

sshot-2010-03-06-[4]

How to Modify a Program’s Icon

Monday, March 9th, 2009

It is possible to change just about any icon that comes with an application.  There are a few different applications that will help make this job easy and my favorite is resource hacker. The reason that I can think of that someone would want to change a programs icon are the following:

  • Two programs have icons that look too similar
  • The program comes with an icon that does not give a good representation of what the program does
  • To have the coolest icons on the block
Resource Hacker Replace Icon

Resource Hacker
Replace Icon

The steps to replace an icon for a program are fairly simple. Just follow the below steps to modify the icons for any of your applications.  

  1. Download Resource Hacker
  2. Unzip the file and run ResHacker.exe
  3. Open the program that contains an icon you would like to change (like C:\Program Files\Brett Batie\Excel on Multiple Monitors\runExcel.exe)
  4. Click Actions→Replace Icon in the Menu Bar
  5. Click the “Open file with new icon…” button
  6. Select the new icon (like C:\Program Files\Microsoft Office\Office12\EXCEL.exe)
  7. Click the “Replace” button
  8. Click File→Save in the Menu Bar
  9. Close Resource Hacker All Done

Verify a WordPress Blog with Google

Monday, July 21st, 2008

In order to verify your site with google you need to go to Google’s Webmaster Tools Dashboard and add your website and then click verify. After clicking verify it will ask you to put a file on your website with a name similar to google54fbcc37db740a4d.html. In most cases this is all that needs to be done and then google can verify that you are the owner.

If you are using permalinks with WordPress it is not so easy to get Google to verify your site. There are two items that are causing validation to not work with WordPress. First, Google is trying to access more than just google54fbcc37db740a4d.html it is also trying to request a page that does not exist. When I tested it, Google was also asking for noexist_54fbcc37db740a4d.html. You might notice that Google just replaced the word “google” with “noexist_”. Second, WordPress is taking a request for any page (including ones that do not exist) and trying to find an appropriate page and is therefore not returning a 404 error. These two problems cause Google to respond with the following error when you try to validate your site.

We’ve detected that your 404 (file not found) error page returns a status of 200 (Success) in the header.

 The code that causes WordPress to not return a 404 for an invalid page is the following which is in an .htaccess file.

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

After creating your file google54fbcc37db740a4d.html and adding it to your server you just have to modify the above .htaccess file to have it not redirect the request for noexist_54fbcc37db740a4d.html to index.php. You also need to specify a specific page or message to display when a 404 error occurs. You can do that by replacing the above code with the following code.

RewriteEngine On
ErrorDocument 404 "This page does not exist"
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{request_uri} !^/noexist_54fbcc37db740a4d.html$ [nc]
RewriteRule . /index.php [L]

Make sure you replace the 54fbcc37db740a4d in the above code with the same characters of the file that google tells you to add to your website.

Password Protect All but One File (htaccess)

Sunday, July 20th, 2008

Once in a while need to allow someone access to one file but no other files in the same directory. I often solve this problem by moving the one file to a sub directory and then adding the following to an htaccess file in that same sub directory.

allow from all
satisfy any

This normally works well but is not a perfect solution since it is not always appropriate to move the file to a different directory. So, I took the time and figured out how to password protect everything but one file. Below is the basic password protection that I had in the htaccess file that blocked everything in the directory (and sub-directories).

AuthGroupFile /dev/null
AuthName "A Blog"
AuthType Basic
AuthUserFile /path/to/.htpasswd
require valid-user

Now in order to exclude a file I just had to add the following below the above six lines of code.

<Files "page.html">
  Allow from all
  Satisfy any
</Files>

Of course this can be taken one step further if you wanted to exclude multiple files from password protection.

<FilesMatch "(page1\.html)|(page2\.html)">
  Allow from all
  Satisfy any
</FilesMatch>

FilesMatch can take a regular expression so you don’t necessarily have to list out each file. The below code will also accomplish the same thing (as above).

<FilesMatch "page[1-2]\.html">
  Allow from all
  Satisfy any
</FilesMatch>

Count Lines of Code in C#

Tuesday, December 4th, 2007

When I am programming I often wonder how much code I have actually typed. Sometimes when I get in the zone, have a well thought out design and have auto-completion helping, I can generate code pretty quick. Although there are quite a few programs out there that will count the lines of code some are a bit more intelligent than others.

At the most basic level a simple command in DOS can count the lines of code in a file or directory. But, I often want to a little more than just the the number of lines in each file. I want to know things like the lines of code vs empty lines and the number of lines that contain comments. Fortunately, there is a plug-in for Visual Studio that will do just that. Since, I am normally using Visual Studio to write any program in C# this is a very logical place to have this tool.

C# count lines of code

My next mission will be to find a good line counter for Java. Anyone know of any?

Extra Update Center Module – Netbeans 6 beta 2

Thursday, October 25th, 2007

In the nightly build of netbeans there is a module that can be installed called “Extra Update Center Module”. This can be made available in Netbeans 6 beta 2 by going to Tools–>Plugins–>Settings and clicking the “add” button. Then use the following url:

http://deadlock.netbeans.org/hudson/job/javadoc-nbms/lastSuccessfulBuild/artifact/nbbuild/nbms/updates.xml.gz

Click “ok” and you should now have access to the “Extra Update Center Module”. Of course the plugins that are provided by this module could be unstable. That is why it is only included with the nightly builds.

Extra Update Center Module