Archive for the ‘Logaan's Toolkit’ Category.

Using 7-zip and batch files to perform backups automatically

UPDATE: I have recently overhauled this and created a simpler script in this post: http://www.logaans-site.co.uk/2009/10/17/simpler-version-of-the-7-zip-backup/

First, a little history:

Since the days when I started using XP I had gotten used to the control that NT Backup provided to allow me to backup my files.

About a year ago I moved to Vista and was unhappy with the “All or nothing” approach that the bundled backup software provided. I was also using OneCare at the time and it followed a similar policy.

Since moving to BitDefender I was much happier with the backup software it provided yet the fact that I was not using a well known backup format rubbed me.

So, using this article: http://www.wilshireone.com/article/115/easy-backups-with-7-zip as a guide, I engineered my own backup mechnism using 7-zip.

Now heres the fun. My backup schedule consists of a weekly incremental backup and one monthly full backup. My files are not so important that I need frequent backups, this schedule suits me down to the ground.

My solution consists of 7 parts:

  • Backup.cmd, this is the main script that executes the command
  • Backupset.txt, a list of files and folders that I wish to backup
  • CurrentSet.txt, a path to the current backup file. Used by incremental backups to update
  • FullBackup.cmd, the script to run a full backup
  • FullBackupSettings.ini, the settings used by a full backup
  • IncrementalBackup.cmd, the script to run an incremental backup
  • IncrementalBackupSettings.ini, the settings used by the incremental backup

Now you could remove the separate scripts for the full and incremental backup, the reason I created separate scripts was that I don’t have to change the arguments in the task scheduler. Instead it is all controlled through those scripts.

Backup.cmd

@echo off

echo TRACE: Start

IF EXIST %1 GOTO Begin

echo Settings file does not exist
GOTO End

:Begin

echo TRACE: Read settings
for /f "eol=# tokens=1,2 delims==" %%i in (%1) do SET %%i=%%j

IF "%varBackupType%"=="full" GOTO CreateNewSet

echo TRACE: Load existing set
for /F %%i in (CurrentSet.txt) do set varTargetBackupSet=%%i

IF EXIST "%varTargetBackupSet%" GOTO Execute

echo Backup set does not exist!
GOTO End

:CreateNewSet
echo TRACE: Create new set

set varTargetBackupSet=%varBackupLocation%\%DATE:~-4%-%DATE:~3,2%-%DATE:~0,2%-%TIME:~0,2%-%TIME:~3,2%-backup.%varFormat%
echo %varTargetBackupSet% > CurrentSet.txt

:Execute
echo TRACE: Execute backup
"%var7zipPath%\7z" %varMode% -t%varFormat% "%varTargetBackupSet%" @"%varFileList%"

:End
echo TRACE: Finished
pause

The backup script loads the settings passed as argument 1, does some checking, then calls 7-zip to begin backing up. The settings files define how the files are added and where to etc.

BackupSet.txt

D:\Guild Wars\Screens
D:\Logaan\Documents
D:\Logaan\Favorites
C:\Users\Logaan\Desktop
D:\Logaan\Saved Games
C:\Users\Logaan\AppData\Local\2DBoy
C:\Users\Logaan\AppData\Local\Ascaron Entertainment
C:\Users\Logaan\AppData\Local\id Software
C:\Users\Logaan\AppData\Local\Ironclad Games
C:\Users\Logaan\AppData\Local\Rockstar Games
C:\Users\Logaan\AppData\Roaming\EditPlus 3
C:\Users\Logaan\AppData\Roaming\FileZilla
C:\Users\Logaan\AppData\Roaming\Free Download Manager
C:\Users\Logaan\AppData\Roaming\Xfire

This is the list file passed to 7-zip. The only downside is that you cannot list the same folder or file name twice in this file. The work around would be to invoke multiple backup scripts and then add the duplicate folders and nested zips.

CurrentSet.txt

D:\2009-04-05-17-16-backup.zip

This contains the backup file created in the last full backup. Incremental backups then read it in and use it to update files.

FullBackup.cmd

@echo off
Backup D:\Logaan\Documents\Tools\7ZipBackup\FullBackupSettings.ini

Simples, it just calls the main backup script with the correct settings.

FullBackupSettings.ini

# File path to the 7-zip executables
var7zipPath=C:\Program Files\7-Zip

# Backup format
varFormat=zip

# Target location for the backup
varBackupLocation=D:

# List file
varFileList=D:\Logaan\Documents\Tools\7ZipBackup\BackupSet.txt

# Mode
varMode=a

# Type
varBackupType=full

The settings file is read in and used in the main backup script. Note the mode and backup type, this is what separates the two types of backup.

IncrementalBackup.cmd

@echo off
Backup D:\Logaan\Documents\Tools\7ZipBackup\IncrementalBackupSettings.ini

Similar to the full version, except its providing the increment backup settings

IncrementalBackupSettings.ini

# File path to the 7-zip executables
var7zipPath=C:\Program Files\7-Zip

# Backup format
varFormat=zip

# Target location for the backup
varBackupLocation=D:

# List file
varFileList=D:\Logaan\Documents\Tools\7ZipBackup\BackupSet.txt

# Mode
varMode=u

# Type
varBackupType=incremental

Similar to the full settings, but with the zip mode set to update and its backup type defined as incremental.

Once that has all been put in place, all I do is create two tasks in the windows task scheduler.

You could go one step further and have the script copy the backups to another disk, I just do this myself when I feel like.

Update

After a little testing I found a flaw in the technique that I was using. Essentially what is happening is that new files are being added to the old archive and any deleted files were being left. I want to keep any files that I deleted but I do not want them muddying up the actual latest image.

Instead, what I did was use the -u switch to stop updates to the base archive being made and adding new files to a new archive, which makes it incremental in its true sense.

Backup.cmd

@echo off

echo TRACE: Start

IF EXIST %1 GOTO Begin

echo Settings file does not exist
GOTO End

:Begin

echo TRACE: Read settings
for /f "eol=# tokens=1,2 delims==" %%i in (%1) do SET %%i=%%j

set varNewBackupSet=%varBackupLocation%\%DATE:~-4%-%DATE:~3,2%-%DATE:~0,2%-%TIME:~0,2%-%TIME:~3,2%-backup.%varFormat%

IF "%varBackupType%"=="full" GOTO CreateNewSet

echo TRACE: Load existing set
for /F %%i in (CurrentSet.txt) do set varOldBackupSet=%%i

IF EXIST "%varOldBackupSet%" GOTO ExecuteIncremental

echo Backup set does not exist!
GOTO End

:CreateNewSet
echo TRACE: Create new set
echo %varNewBackupSet% > CurrentSet.txt

:ExecuteFull
echo TRACE: Execute Full backup
"%var7zipPath%\7z" a -t%varFormat% "%varNewBackupSet%" @"%varFileList%"
GOTO End

:ExecuteIncremental
echo TRACE: Execute Incremental backup
"%var7zipPath%\7z" u -u- -u!"%varNewBackupSet%" -t%varFormat% "%varOldBackupSet%" @"%varFileList%"

:End
echo TRACE: Finished
pause

In fact, I have gone one step further and I have built a command line tool that wraps 7-zip and provides a nicer mechanism for configuring the backups. It then executes 7-zip. Once I have tested it a little I will post the source code.

NetBeans IDE

The other day I had hit a brick wall, I was really struggling with part of my FormManager project and really needed to debug it.

I started looking into XDebug and discovered what it could really do, and diving into the website I found they listed a set of compatible IDEs that could use the extension to debug php. Since I had spurned eclipse I thought there was nothing else short of the Zend IDE that could help. Thats when I noticed NetBeans. The last time I had used NetBeans was back in college for some Java projects. I was really surprised when I found out that they offered a PHP IDE.

Within a couple of seconds of getting the project setup in the IDE it found the problem already for me. It does a much better job of context sensitive variables than Eclipse ever did, and it can pick up all kinds of problems much better than Eclipse, within a few minutes I had fixed the problem and even found a couple of problems that I did not yet know about.

It even includes some basic refactoring tools!

NetBeans does support Unit Testing however there is currently no support for phpUnit at this time. It is planned as a feature some point in the future.

Modelling OO

NClass is a free open source class diagram modelling editor. It currently supports C# and Java. However recently I have used it to help model some of my php applications. Its quick and easy to use, simple installs, all round good app.

The Perpetual ToDo List

Like pretty much everyone else, I have a todo list with things on it that I never get round to doing. 

For a long time I used a text file sat on my desktop to keep track of all the bits I had to do, but that really didn’t cut it. Which items were high priority, when were they due by?

That why I have started to use this funky little free program from Abstract Spoon (which you can also get from CodeProject) called ToDoList.

Its a neat little app where you can enter all your tasks, create sub tasks and categorise them. Set due dates, priorities, effort and more.

Documenting your code in PHP

Whilst working on this model, I found myself forgetting various parameters or names of methods I had created. I can’t believe how much I rely on an IDE to provide me with all my prompts.

I did try setting up Eclipse again with PDT (had tried to use phpEclipse in the past with dissapointing results) yet I was getting UI errors all over, no matter what I tried (updating the JRE, grabbing various packages) I could not get the thing to work.

So I resorted to the next best thing, I went and found something called phpDoc. It reads DocBlocks from your code and creates a set of html pages containing all the information about your code.

Again, I installed it from pear on the command line, there are lots of site out there to help with installing it on Windows. Once installed, you can use the phpdoc -h to get all the command line parameters.

Similar to my last post, I use an msbuild script to run the documentation tasks


<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">

    <PropertyGroup>
        <BuildDir>$(MSBuildProjectDirectory)</BuildDir>
        <DocumentationTitle>Dynamic Data Model</DocumentationTitle>
        <HelpOutput>HTML:Smarty:HandS</HelpOutput>
        <DocumentationFolder>$(BuildDir)Documentation</DocumentationFolder>
    </PropertyGroup>

    <ItemGroup>
        <CodeFiles Include="$(BuildDir)***.php" Exclude="$(BuildDir)**.svn***.*;
                                 $(BuildDir)**tests***.*" />
    </ItemGroup>

    <Target Name="Clean">
        <RemoveDir Directories="$(DocumentationFolder)" Condition="Exists('$(DocumentationFolder)')" />
    </Target>

    <Target Name="Setup" DependsOnTargets="Clean">
        <MakeDir Directories="$(DocumentationFolder)" Condition="!Exists('$(DocumentationFolder)')" />
    </Target>

    <Target Name="Build" DependsOnTargets="Setup">
        <CallTarget Targets="BuildDocumentation" />
    </Target>

    <Target Name="BuildDocumentation" DependsOnTargets="Setup">
        <CreateProperty Value="@(CodeFiles, ',')">
            <Output TaskParameter="Value" PropertyName="FilesToDocument" />
        </CreateProperty>

        <Exec Command='phpdoc --sourcecode --target "$(DocumentationFolder)" --output $(HelpOutput) --title "$(DocumentationTitle)" --filename $(FilesToDocument)' />
    </Target>
</Project>

Unit testing in PHP with PHPUnit

With this dynamic data model that I am currently building in PHP, I found that for quite a complicated solution I had no unit testing at all.

After searching around I found PHPUnit, however, it all hinted at a Linux only environment. A short while later I found a blog that described how to set it up for Windows: http://usingzendframework.blogspot.com/2007/12/setting-up-phpunit.html. I use Xampp, so I did not have to change the memory limit.

Once installed I used the online pocket guide to start me off: http://www.phpunit.de/pocket_guide/index.en.php

Inside my code folder I created a tests folder where I placed all my php tests, inside that I created an includes folder for all the test related code.

folders.jpg

The first thing that the common include does is turn on all the error reporting an strict reporting. This should ensure the most quality coding.

<?php
error_reporting(E_ALL | E_STRICT);
require_once('PHPUnit/Framework.php');
?>

Once that is done, I could start with writing all the tests.

<?php
include('includes/common.php');
class ExampleTests extends PHPUnit_Framework_TestCase
{
 public function testSomeObjectTest()
 {
  /* Test code here */
 }
}
?>

Once that was done, I created a msbuild script to test them all using the TestSuite class

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
    <PropertyGroup>
        <BuildDir>$(MSBuildProjectDirectory)</BuildDir>
    </PropertyGroup>

    <ItemGroup>
        <CodeFiles Include="$(BuildDir)***.php" Exclude="$(BuildDir)**.svn***.*;
                                                           $(BuildDir)**tests***.*" />
    </ItemGroup>

    <Target Name="Build">
        <CallTarget Targets="RunTests" />
    </Target>

    <Target Name="RunTests">
        <Exec Command='phpunit --verbose "$(BuildDir)testsTestSuite.php"' WorkingDirectory="$(BuildDir)tests" />
    </Target>

</Project>

I had to add the framework folder and the php folder onto the PATH environment variable so that I could just call msbuild from the commandline

RGB to Hex Converter

I have been working on my dads website, using a wordpress theme generator and this handy colour scheme book that I bought a couple of years back. (Yeah! I have a book with lots of colour swatches in it. I’m borderline dyslexic and don’t have any colour co-ordination.)

This book, has a small section in the back for web safe colours with hex values, the rest is all RGB and CMYK values for the printed page. Because there is a greater range of swatches in the first half, I created this small app to quickly turn an RGB value into Hex:

RGB Converter Image

Features: 

  • Automatically copies the hex value to the clipboard
  • Automatically skips to the next RGB colour value after a valid 3 character colour has been entered (enter 0’s for padding)
  • Ocassionally will skip over an RGB colour field
  • Pressing any other key when an RGB colour field has focus will automatically validate that field

Grab the source code here

It is not a perfect solution but it allowed me to quickly key in an RGB value and get the hex code. The result was quite good actually, quite a few of the RGB/CYMK printed colour schemes worked well in a web browser.

HWMonitor, temperature monitor alternative

With the install of Vista, I have had some issues with my system monitoring software. The new ASUS PC Probe II leaves windows all over the place and is difficult to read and quickly check the temps.

 The nVidia hardware monitor worked for a short time up until I installed some other nVidia drivers which broke it. I shortly also learned that it wasn’t supposed to work in Vista either =/

 So I was out of options, I had nothing to monitor my system with. I am a little nuerotic about it, I am constantly worried that my old hardware will melt the next time I play a game or a fan will fail and the computer won’t tell me in time. I have been nursing my computer for the past year, to keep it ticking over until I get a new machine.

CPUID’s Hardware Monitor – http://www.cpuid.com/hwmonitor.php solved all these issues. It hooks into all the sensors on your machine and reports thier values. I now have a one application that soaks up very little CPU time to monitor everything on my system. Even some sensors that I didn’t know I had!

It can get a few things wrong, there are a couple of my sensors that don’t move or report wrong values. They have a pro version for 20 euros and even a development SDK for 999 euros… SDK is a bit much for just me, might get pro after a while.

Wordpress Theme Generator

I am currently creating a website for my father. I chose Wordpress as a base, its nice simple UI will be adequate for what he needs to do, it has a simple plugin system and I should be able to rapdily design a website for him.

Well its been 4 weeks and I am still stuck trying to design a template. The saviour of the day however is A Wordpress Theme Generator by Yvo Schaap - http://www.yvoschaap.com/wpthemegen. Using this really simple generator, I have been plugging in various colours before I get something that looks right. I will now go off, modify the template myself and provide some drops for dad to look at :)

FileZilla, the SmartFTP alternative

With SmartFTP not offering a free license anymore there is now a space for another robust FTP client. I don’t blame them, they offered such a high quality product for free for such a long time I could see that they would do this at some point. However I feel that they could have offered a really simple cut down FTP client for the simple joe, I only need to download or upload the odd file. Maybe change a few permissions, I don’t use all the features that SmartFTP offered.

As a result, I went hunting for an alternative FTP client and FileZilla ranked highly: http://filezilla-project.org/ Its an open source client and server (separate installs) and does the job nicely.