Archive for the ‘Software Development’ Category

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);
}
?>

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

Regular Expression Search and Replace via Command Line (Editplus)

Thursday, December 14th, 2006

Editplus is definitely my favorite text editor but it does not entirely support Regular Expression. Below is an example of when Editplus has failed me:

Editplus-regex

So, I used the regular expression .*<table.*\n.*<tr>\n.*<td>. This unexpectedly returned everything from the beginning of the file down to the <td>. Basically it seems to have a little bit of trouble with multi-line regular expressions.

My solution to this problem was to develop a little regular expression command line program and add it as an Editplus user tool. An added benefit to creating this application is I can now do Regular Expression search and replace via the command line. At the time of creating this application I did not know about Powershell as that would have provided the same functionality. But this little application works so I will stick with it for now.

So, how does the search and replace program work? If you type SearchReplace.exe at the command line you will get the following:

Usage: searchReplace.exe “regular expression” “replacement string” file.txt

Pretty simple ehh?  Note: if you happen to have double quotes in your regular expression they will need to be escaped.

Now to set this up with Editplus just go to Tool —> Preferences —> User Tools and put in the following values:

Command: SearchReplace.exe
Argument: “$(Prompt)” “$(Prompt)” $(FileName)
Initial: $(FileDir)
Check: Run as text filter

When this user tool is run the first pop up box will be where you put the regular expression and the second will be the replacement string.

At this point I have to give a little warning that I have not thoroughly tested this program and I am not liable for any data loss caused by this program. If you happen to encounter any problems let me know. 

Determine File Encoding

Thursday, December 14th, 2006

I ran into a problem where I wasn’t sure if I could trust the encoding that my text editor was displaying. I also wanted to check the encoding on about 10,000 files and determine if it was not a specific encoding. So, I created a little program to tell me the encoding of a file. This in combination with powershell allowed me to loop recursively through all the files in a directory and create a list of the files that were not the correct encoding.

A Good portion of the code that I used for this application was available on the another site that describes how to determine the Encoding of a Unicode file.

The application can be downloaded below:

DOWNLOAD: Determine File Encoding

Formatting SQL

Thursday, December 7th, 2006

Today I found a nice little Java tool to help format long SQL queries. It has many options on how the string will be formatted. It will also take sql input types such as:

  • SQL
  • DB2/UDB
  • Oracle
  • MSAccess
  • SQL Server
  • Sybase
  • MYSQL
  • PostgreSQL
  • Informix

It then can take this input SQL and format it into a different type such as:

  • SQL
  • Java StringBuffer
  • Java String
  • C# StringBuilder
  • PHP String
  • ASP StringBuilder
  • VB String
  • VB StringBuilder
  • Concatenated SQL
  • HTML Code

This tool really has a lot of options and is very handy when trying to read/edit a long SQL query.

format sql screenshot