Ed’s blog

Latest updates from what I’m doing now

Whats this?

Eddie's techie blog. Mostly concerned with ColdFusion, PHP, Asterisk, C++, games , Flex amongst others.

As the title says, I’m going to finish up blogging on techie stuff for the moment due to the travelling! you can keep up to date with the travels at http://travel.edmundlong.com

Hi all haven’t posted in a while have a couple of posts to catch up on :)

I’ve recently have the need to perform locking in php on the server level. Basically I want just a single php script to execute a piece of code at any time. This requirement was brought about by race conditions whereby two php scripts would go and execute the same piece of code which would consequently conflict with one another. I needed to stop this. The solution is nice and easy and works a treat.

Whenever a php script comes in and requests a lock on a piece of code it attempts to create a directory using phps mkdir with a specific name myLock1. If the directory already exists then the mkdir returns false and the locking fails. If the mkdir completes then the php script has locked the section of code. Now when another seperate php script comes in and tries to create the directory mkdir will return false and the locking will fail.

When the php script is finished with a piece of code then it unlocks by deleting the directory using rmdir. Now a new php script is free to come in lock the piece of code again.

This locking works across all php scripts (i.e. is server wide) and provides named locks as you can give the directories different names. So one section of code may be locking a myLock1 directory and another part be locking myLock2 directory but these won’t interfere with one another. I’ve attached the code for this simple locking below and highlighed how it would be used to lock a piece of code.


class FLock
	{	private $files = array();
		private $oUUID = "";

		function __construct()
		{	$this->oUUID = new UUID();
		}	

		function __destruct()
		{	foreach($this->files as $file)
			{
				fclose($this->files['$file']);
			}
		}

		private function saveFileHandle($filepath)
		{
			if(!array_key_exists("$filepath",$this->files))
			{
				$this->files["$filepath"] = array();
				$this->files["$filepath"]['directory'] = $filepath;
				$this->files["$filepath"]['locked'] = false;

			}

		}

		public function attemptFileLock($filepath=false, $lockFile=true)
		{
			global $fileLockingLocation; 

		    $this->saveFileHandle($filepath);

			$canLock = false;

		    if($lockFile == true)
			{	if(!$this->files["$filepath"]['locked'])
				{	try
					{
						$canLock = mkdir("$filepath");
						if($canLock)
						{
							$this->files["$filepath"]['locked'] = true;

						}

					}
					catch(Exception $ex)
					{
						LogError($ex);
					}
				}
			}
			else
			{	if($this->files["$filepath"]['locked'])
				{
					rmDir("$filepath");

					$this->files["$filepath"]['locked'] = false;

					//TODO - Fix
					return true;

				}
			}

		    return $canLock;
		} 

		public function removeAllFileLocks()
		{	foreach($this->files as $file)
			{	rmDir($file['directory']);
				$this->files[$file['directory']]['locked'] = false;
			}
		}
	} 

To lock the some code you need to just do like what I’ve done below.


$this->oFL = new fLock();
$fileLockResult = $this->oFL->attemptFileLock("/fileLocks/".$lockName."_lock",true);
if($fileLockResult)
{
      //Perform mySQL inserts,deletes etc.
      $fileLockResult = $this->oFL->attemptFileLock("/fileLocks/".$lockName."_lock",false);
}
else
{
     //Sleep between 0.5 - 1 second
     usleep(500000+(mt_rand(1,10))*500000);
}

I’ve had to perform php redirects of late also, its nice and easy but as Michael found out, even when you put a redirect in a chunk of code, the rest of the script gets parsed and the redirection doesn’t occur straight away. So you may want to put in a die() or something after the redirect if you wish to abort the rest of the page’s processing.


header( 'Location: http://www.yoursite.com/new_page.html' ) ;

Performing error logging with PHP is another task I’ve wanted to do of late. Basically I’ve created a php wrapper page that takes in a script location from the Asterisk dial plan and executes the passed in script within a try catch block. Wrapping the script execution within the try provides a simple error logging mechanism. Anywhere I want to log errors that are fatal to the application I can just perform a throw within a php script and the top-most wrapper will always catch and log the error.


#!/usr/bin/php -q
<?php

	require_once $phpScriptPath.'common/phpagi.php';
	require_once ("utility/logging.php");

	global $agi;
	try
	{	if(!isset($agi))
		{	$agi = new AGI();
		}
		$scriptName = $agi->get_variable("scriptName");
		$agi->exec("AGI",$scriptName['data']);

	}
	catch(Exception $ex)
	{	if(!isset($agi))
		{	$agi = new AGI();
		}

		$errorFileName = 'error-'."date-".date("dmy_His");
		$errorInfo = "Error message: ".$ex->getMessage();
		$errorCode = "Error code: ".$ex->getCode();
		$errorFile = "File: ".$ex->getFile();
		$errorLineNo = "Line number: ".$ex->getLine();

		if(!isset($agi))
		{
			$errorCode = $errorCode." - AGI cannot be created.";
			$errorFile = $errorFile." - applicationWrapper.php catch block.";
		}

		//Log to error log directory
		writeVariableToFile($errorInfo,$errorFileName);
		writeVariableToFile($errorCode,$errorFileName,true);
		writeVariableToFile($errorFile,$errorFileName,true);
		writeVariableToFile($errorLineNo,$errorFileName,true);

		if(isset($agi))
		{	//Log to terminal if possible
			$agi->verbose($errorInfo);
			$agi->verbose($errorCode);
			$agi->verbose($errorFile);
			$agi->verbose($errorLineNo);
			$agi->text2wav($ex->getMessage());
		}

		//Log to php error log
		error_log($errorInfo);
		error_log($errorCode);
		error_log($errorFile);
		error_log($errorLineNo);

		exit(0);

	}

	exit(0);

?>

The error_log is a built in php error logging system. You can specify where PHP logs errors to within you php.ini config file, I set it up to log to the system log by uncommenting the error_log = syslog line but you can easily setup your own location for logging errors.

From the Asterisk dial plan i.e. the extensions.conf you basically have something like

exten => s,n,Set(scriptName=/my/Path/To/File/myfile.php)
exten => s,n,AGI(/path/to/wrapper/applicationWrapper.php)
exten => s,n,Hangup()

Hi again,

I’ve been delving into the wonderful world of Farcry CMS. I needed to create a custom type and having never created one before didn’t really know where to start. Luckily for me I’m working with one of the ex-developers of Farcry Michael and he stepped me through how to create it. This process is for the latest beta version of Farcry 5 so may be different for other versions of the CMS.

First and foremost you need to need to create a new type cfc in you /webroot/farcry/projects/#projectName#/packages/types directory. I created a CFC called Products(although I think you may be better of leaving it all lower case, more on that later) which contains several properties. The properties contained in this CFC define what is to be contained in the request stObj whenever someone hits/calls the new types page. The products cfc extends the farcry core types cfc and so inherits all the generic stuff like status verison, object id etc properties that are common across all farcry objects. Next I began to include my own custom ’stuff’ that I want specific to that object. I created a title, display method and product type. The title is just a string and the display method goes off and creates a drop down list of all objects in the products directory in the webskin that begin with ‘displayPage’, again more on that later. The product type is a list of allowed types of products. I specified this as a string but it can easily be replaced by a query or you can pull in other Farcry objects. Finally we need an edit function that tells farcry where to look when editing the object in the back-end. I specified that farcry should look in the _Products directory and for edit.cfm. So whenever we are editing an object in the back end Farcry will load up edit.cfm and this page essentially becomes a regular form style page with a little difference as you need to save the changes back to the Farcry object & DB when completed.


<cfcomponent displayname="Products" extends="farcry.core.packages.types.types" output="false" buseintree="true">
<cfproperty ftSeq="1" ftFieldset="General Details" name="title" type="string"hint="Product title." required="yes" default="" blabel="true" ftlabel="Product Title" />
<cfproperty ftSeq="2" ftFieldset="General Details" name="displayMethod" type="string" hint="Display method to render this HTML object with." required="yes" ftLabel="Display Method" ftType="webskin" ftPrefix="displayPage">
<cfproperty ftSeq="3" ftFieldSet="General Details"  name="productType" type="string" hint="The product type" required="true" default="Type1" ftLabel="Product Type" ftType="list" ftList="Type1:Type1,Type2:Type2,Type3:Type3,Type4:Type4">
<!--- Object Methods --->
<cffunction name="edit" access="public">
	<cfargument name="objectid" required="yes" type="UUID">

	<!--- getData for object edit --->
	<cfset stObj = this.getData(arguments.objectid)>
	<cfinclude template="_Products/edit.cfm">
</cffunction>

</cfcomponent>

The edit.cfm is quite long but I’ve edited it a bit and included it anyway.


<cfsetting enablecfoutputonly="yes" />

<!--- import tag libraries --->
<cfimport taglib="/farcry/core/tags/navajo/" prefix="nj" />
<cfimport taglib="/farcry/core/tags/widgets" prefix="widgets">

<!--- determine where the edit handler has been called from to provide the right return url --->
<cfparam name="url.ref" default="sitetree" type="string">
<cfif url.ref eq "typeadmin">
	<!--- typeadmin redirect --->
	<cfset cancelCompleteURL = "#application.url.farcry#/content/dmProducts.cfm">
<cfelse>
	<!--- site tree redirect --->
	<cfset cancelCompleteURL = "#application.url.farcry#/edittabOverview.cfm?objectid=#stObj.ObjectID#">
</cfif>

<!--- default form elements --->
<cfparam name="form.title" default="">
<cfparam name="form.productType" default="">

<!--- local variables --->
<cfparam name="errormessage" default="">
<cfset lProductTypes = "Type1, Type2, Type3, Type4">

<!------------------------------------------------
	Form Action
	 - self posting form
------------------------------------------------->
<!--- action: cancel --->
<cfif isDefined("form.cancel")>
	<!--- cancel content item lock --->
	<cfset setlock(locked="false")>
	<cflocation url="#cancelCompleteURL#" addtoken="no">
</cfif>

<cfif isDefined("form.update")>
	<!--- action: update --->
	<cfset stProperties = structNew()>
	<cfset stProperties.objectid = stObj.ObjectID>
	<cfset stProperties.label = form.title>
 	<cfset stProperties.title = form.title>
	<cfset stProperties.datetimelastupdated = Now()>
	<cfset stProperties.lastupdatedby = session.dmSec.authentication.userlogin>
	<cfset stProperties.displayMethod = form.displayMethod>	 

	<!--- update the OBJECT if no error occured and reloacte--->
	<cfif NOT len(errormessage)>
		<!--- remove content item lock --->
		<cfset setlock(locked="false")>
		<!--- update content item --->
		<cfset setData(stProperties=stProperties)>

		<!--- if not typeadmin edit then refresh JS tree data --->
		<cfif url.ref neq "typeadmin">
			<!--- get parent to update site js tree --->
			<nj:treeGetRelations typename="#stObj.typename#" objectId="#stObj.ObjectID#" get="parents" r_lObjectIds="ParentID" bInclusive="1">
			<!--- update site js tree --->
			<nj:updateTree objectId="#parentID#">
			<!--- relocate iframes for tree and edit areas using JS --->
			<cfoutput>
			<script type="text/javascript">
			if(parent['sidebar'].frames['sideTree'])
				parent['sidebar'].frames['sideTree'].location= parent['sidebar'].frames['sideTree'].location;
				parent['content'].location.href = "#cancelCompleteURL#"
			</script>
			</cfoutput>
			<cfabort>

		<cfelse>
			<cflocation url="#cancelCompleteURL#" addtoken="no">
		</cfif>

	<cfelse>
		<!--- show error --->
		<cfoutput><p id="fading1" class="fade"><span class="error">#errormessage#</span></p></cfoutput>
	</cfif>

<!--- set default values for form--->
<cfelse>
	<!--- Lock content item for editing--->
	<cfset setlock(locked="true")>

	<cfset title = stObj.title>
	<cfset productType = stObj.productType>

</cfif>

<!------------------------------------------------
	Form Display
------------------------------------------------->
<!--- output form UI --->
<cfoutput>
<form action="#cgi.script_name#?#cgi.query_string#" class="f-wrap-1 wider f-bg-medium" enctype="multipart/form-data" name="fileForm" method="post">
	<fieldset>
<h3>#application.rb.getResource("generalInfo")#: <span class="highlight">#stObj.title#</span></h3>
		<label for="title"><b>#application.rb.getResource("titleLabel")#</b>
			<input type="text" name="title" id="title" value="#title#" maxlength="255" size="45" /><br />
		</label>

		<!--- <widgets:fileUpload fileFieldPrefix="css" fieldLabel="Upload CSS:" uploadType="file" fieldValue="#stObj.filename#" previewURL="/css/" bShowPreview="0"> --->
		<widgets:displayMethodSelector typeName="Products" prefix="displayPage">

		<label for="productType"><b>Product Type:</b>
			<select name="productType" id="productType" multiple="true"><cfloop index="iProduct" list="#lProductTypes#">
				<option value="#iProduct#"<cfif ListFindNoCase(productType,iProduct)> selected="selected"</cfif>>#iProduct#</option></cfloop>
			</select><br />
		</label>
	</fieldset>
	<div class="f-submit-wrap">
	<input type="submit" name="update" value="OK" class="f-submit" />
	<input type="submit" name="cancel" value="Cancel" class="f-submit" />
	</div>
</form>
</cfoutput>
<cfsetting enablecfoutputonly="no" />

Now you’ve created your products.cfc log into the farcry backend and go to the Admin tab. Select COAPI management from the dropdown and then select types on the left hand nav. You should now see your newly created products object here ready to be deployed. You can select deploy and your products should be available in the backend. However you need to do one more thing before you can begin to create products in the backend and view them on the front end, you need to define how products are to be displayed on the front end. To do this create a products directory in the /webroot/farcry/products/#appName#/webskin/ and within this create a page called displayPageStandard. Whenever this page is called the stObj struct is passed into the page and you can now access all the properties of this specific product and display it as you wish. So within this page I just dumped the stObj and then created a simple table of the object title and type. Obviously you can do much more complex stuff than this but this is really just a tutorial on how to do it.

Now you should be able to create product objects select a display method and edit them according to your own custom edit.cfm. One problem I never encountered on my Mac but did in staging was that I had created the products cfc with a large “P” and had use the same casing everywhere around the project. No problem there but in staging an error occurred saying that the table ‘products’ couldn’t be found. Looks like Farcry LCASEs the products name when creating the table, Mac’s NFS filesystem was forgiving but on Linux the problem reared it’s head. Had to rename the table manually and it all worked fine again. Perhaps this is just a bug in the beta that will be fixed come the release date.

I wrote this based entirely off my memory do hope I haven’t left anything out!!!

Hi all haven’t posted in a while.

Been doing a fair bit of PHP recently and have come across some useful PHP snippets.

I was looking to perform multiple MySQL queries but the plain old mysql_query doesn’t allow it unfortunately. After doing a little bit of digging around I found that you need to use mysqli_multi_query to perform multi-queries. Of course you need to connect to your MySQL database using mysqli_connect(and I believe you need to have enabled a seperate mysqli module for php).

I’ve also been doing quite a bit of string manipulation with php. I was looking for a similar function to Coldfusion’s ListContainsNoCase whereby I needed to search a comma seperated list for a specific value. Didn’t find anything especially useful so learnt that using the explode function converts a string separated by a specified delimiter into an array which can then be searched using the in_array function. The strict flag is especially useful if you require an element of the array to match exactly the original term you’re looking for in the list.

String comparison was another sticking point last week. I had a string containing a single character, “*” and attempted compare this string variable using the double equality operator(i.e. $myVar == “*”) but was getting a false match every time. After printing out the variable many times and ensuring that it did indeed have the right value I began to think something else was wrong and had a look at the php documentation. After trying out the Strcasecmp function I began getting the matches I expected. strcasecmp is a binary safe case-insensitive string comparison. A binary-safe function is essentially one that treats its input as a raw stream of data without any specific format. It should thus work with all 256 possible values that a character can take (assuming 8-bit characters). Most functions are not binary safe when using any special or markup characters, such as escape codes or those that expect null-terminated strings. A possible exception would be a function whose explicit purpose is to search for a certain character in a binary string.(thank you Wikipedia). As I was working with a special character my string comparison was crapping out, now I know why.

Creating a singleton class in PHP is something that is a very common operation and after looking at a handy tutorial I came up with a handy singleton class which is used to obtain and instantiate singleton objects. Further work needs to be done on this to allow for multiple objects to be instantiated but it works pretty well for me.(sorry about the indentation, Wordpress screwed it up on pasting it in)


<?php

class Singleton
// ensure that only a single instance exists for each class.
{
	function getDBConnection()
	{	static $db = null;
		global $dbLocation;
		global $dbusername;
		global $dbpassword;
		global $cstdatabase;

		if($db == null)
		{	$db = mysql_connect($dbLocation,$dbusername,$dbpassword);
			mysql_select_db($cstdatabase) or die( "Unable to select database");
		}

		return $db;

	}

	//TODO: Make this more flexible for parameters into inited functions, possibly an array
    public function &getInstance ($class, $classPath=null,$arg1=null)
    // implements the 'singleton' design pattern.
    {	$lowerClassName = strtolower($class);
        static $instances = array();  // array of instance names

        if (array_key_exists($lowerClassName, $instances)) {
            // instance exists in array, so use it
            $instance =& $instances[$lowerClassName];

        } else {
            // load the class file (if not already loaded)
            if (!class_exists($lowerClassName)) {
                if($classPath)
				{
					require_once "$classPath/$class".".php";
				}
				else
				{
					switch ($lowerClassName) {
	                    case 'object1':
	                        require_once 'object1/Object1.php';
	                        break;

	                    case 'object2':
	                        require_once 'object2/Object2.php';
	                        break;
	                    default:
	                        require_once "$class".".php";
	                        break;
	                } // switch
				}

            } // if

            // instance does not exist, so create it
            $newClass = new $class();

	    $instances[$lowerClassName] = $newClass;	

	    if(method_exists($newClass,"init"))
	    {	  if($arg1 != null)
		 {	$newClass->init($arg1);
		 }
		 else
		 {
			$newClass->init();
		 }
	   }

	   $instance =& $newClass;
        } // if

        return $instance;

    } // getInstance

} // singleton

?>

A couple of links for iTouch stuff again. Theres a hand-recognition application out for the iTouch, it works…….kinda. Check out the demo at Gizmodo.

I saw today that its possible to setup Voip on the iTouch. I’ve not tried it yet but looks cool. You need a mic addon to get it working but doesn’t look especially hard to get going. Touchmods.

Recently I’ve had the need to setup an Asterisk machine to connect to Voxbone via IAX. So basically a person would dial a DID from a normal phone, Voxbone picks this up and then through the URIs you setup on their site maps from the DID to your own Asterisk box. When a call comes in the call gets routed according to your Asterisk’s iax.conf to a context you setup in your extensions.conf Below are the conf files that we used to get Voxbone working with Asterisk there are still some issues with calls not getting through on occasion but hopefully that will be fixed soon.

Within the Voxbone menu create a new URI of type IAX(Configure->URIs->Create or modify URI). The uri value I set to be : {E164}@xxx.xxx.xxx.xx - where the X’s should be replaced by the IP of your Asterisk machine.
After that go to Configure->DIDs&Trunks. You should see a list of DIDs you own and map a DID to the URI you just setup. Next go to POP and setup the POP to be the closest location to your own location. I selected US-LA but changed again to US-NY after that stopped working. Once you’ve selected and updated your POP then go and get a list of the host IPs for that region on the same page as the POP update. Get the list of IPs and add then to your IAX conf file in the host string like what I’ve done below.

Iax.conf


[general]
bandwidth=low
jitterbuffer=no
tos=lowdelay

autokill=yes
[voxbone]
disallow=all
allow=ulaw
allow=gsm
canreinvite=no&no&no&no&no&no&no&no&no&no&no&no&no
context=default
host=81.201.84.21&81.201.84.22&81.201.84.24&81.201.84.25&81.201.84.26&81.201.84$
insecure=very&very&very&very&very&very&very&very&very&very&very&very&very
type=friend

extensions.conf


[default]
exten => DID_ASSIGNED_BY_VOXBONE,1,Goto(menu,1,1)

When a call comes in from one of the IPs listed in the host string the call is routed to the default context which in turn routes the call to an internal menu system.

Hi,

I’ve recently upgraded to Google Apps for my site. It allows me to use Google Mail for my own personal site and I can use all the Google Documents, Spreadsheets and the rest of their free applications. I just had to modify my MX records for my site to point at Googles MX server(which takes a while to go through). Check it out if you’re a webmaster, I was previously using SquirrelMail so using Gmail is a massive improvement!

http://www.google.com/a/help/intl/en/admins/editions.html

Recently when I booted up into the Windows XP partition using bootcamp of the Intel Mac I’m using I needed to access the files on the Leopard OSX partition of the hard-drive. After looking around for a bit I found HFSExplorer which can read from a HFS partition(i.e. Mac OS filesystem) and copy from it if needed. It is read-only though which is a bit of a bummer but is open-source and worked pretty well when I used it.

I see that bots have cracked both Gmail and Hotmail Live’s captcha methods. Not only that but did it in 60 seconds, very impressive. Read about it here and more in depth here.

I’ve also been playing around with some Ajax stuff recently. I had to make a modal window that contains a form, the form set a session variable that is set just once for a user’s session. I looked around for a bit, tried a few samples and found Control Modal which is a pretty lightweight, easy to use Modal window Ajax API built on top of Prototype. Check out the demos and grab a version at the Control Modal site. Below is some code I wrote to place the form in the Modal window.


<a href="##test_one_contents" id="modal_link_one"></a>
<div id="test_one_contents">
<form id="hcForm"
	action="#cgi.script_name#" method="post">
       <h3>Select an option</h3>
       <input type="submit" value="Yes" name="yes">
       <input type="submit" value="No" name="no">
</form>
</div>
<script>
	new Control.Modal('modal_link_one',{
		opacity: 0.95,
		position: 'absolute',
		width: 300,
		height: 70
	        });

	Event.observe(document, 'dom:loaded', function(){
	           $('modal_link_one').onclick();
	});

Note: Took us ages to figure that onclick was the right Prototype JS event to fire the click event, we were previously using click() but it wasn’t working. So now when the page loads a dom loaded event is triggered which then goes and creates a click event on the modal_link_one id which creates the Ajax modal window.

Hi again,

I’ve been fishing around for new iTouch apps and have found some excellent new ones out there. Check out Simplify Media, its brilliant allows you to connect to your iTunes library as long as you have a Wifi connection. Just install the app on your Mac or PC, create an account and download the Simplify Media app from the iTouch Installer and log in there too. Takes a little while to get the libraries the first time but after that its very fast. The songs then buffer as if you were streaming them, I’m very impressed with the speed of it - a must have for any iTouch/iPhone owner.

Another site that has lots of recommendations but isn’t quite working for me yet is Seeqpod which is basically a search engine that searches for music in Safari and apparently can stream the audio over the net. The audio doesn’t start for me yet, not sure why. There does seem to be a HUGE amount of music there though.

iPhysics is very very cool ‘game’, you can draw lines, objects and then the physics engine takes over and the new objects bounce around under gravity and as you would expect under Newtonian phyiscs. The really impressive thing is that it is dynamic, you can create objects on the fly and they’ll interact with one another and bounce around the place, fun. The game part involves moving a ball across a level to a small red box, there’s tons of user-created levels so its quite fun from what I’ve played of it. Here’s a video of something similar I found a few weeks ago, thought it was only a college experiment though :)

Similar to the SimplifyMedia is the telekinesis project. It looks really cool and I’ve not had a chance to test this yet but will give it a goo this evening and see how it works.

Also ScummVM is available for the iTouch now which means that……….yes Monkey Island my all-time favourite game can be played on it. Also can play all the ScummVM developed games, Sam & Max, Indy series and all the other classic adventure games. Hurray!

MobileCast is an other app that can be installed via the Installer. It allows you to fetch podcasts from RSS feeds without having to sync up with iTunes, this wil be handy when I’m travelling and can just pick up random Wifi hotspots.

I’ve recently upgraded the firmware on my PSP to version 3.90 M33-3, mainly because I want to play Pro Evo 2008. Check out Dark Alex’s site with all the releases there, I upgraded from version 3.51. Always pretty nervous when doing it but he hasn’t let me down yet.

Linky to his site

Finally here’s how to quickly create a tar gz archive. Here it is

tar -pczf nameOfArchive.tar.gz /directoryToZip

Hi again,

Been a while since my last post so quite a bit to post, will probably split into two.

I was having a very strange problem in CF last week where CF was unable to find any Application.cfc of any of my sites. I did many updateapps, restarted ColdFusion a couple of times, ensured the relative paths were correct and there were no errors in the cfc. After reaching my wits end with it, I asked a co-worker(cheers Sharmo!) for his assistance. We checked the logs and a whole bunch of other things with no avail to figure out what was going wrong. Michael then explained how cfcs are converted into Java bytecode classes in the backend so we figured that there could be something funky going on with the caching in the backend or on of the classes had become corrupt. So we deleted all the classes from /Applications/JRun4/servers/cfusion/cfusion-ear/cfusion-war/WEB-INF/cfclasses and did a restart of ColdFusion and voila…all working again.

I’ve been performing a lot of exception checking for ColdFusion of late. There are several different types of ColdFusion error listed below. Some exceptions CAN contain exception specific data thrown along with the error. Every exception contains a message and a type(i.e. database, application etc. ). Each exception can also include two members of the cfcatch struct called rootCause and cause which include data that can explain the reason behind the exception.

Database - Mysql errors
Special variables

  • cfcatch.rootcause.datasource : the SQL datasource

  • cfcatch.rootcause.sql : the problematic sql code

Application - Errors in the application scope

    Special variables

  • cfcatch.extendedInfo : exactly what it says on the tin

Template - Occurs when a template which is included can’t be found

    Special variables

  • cfcatch.missingfileName : The name of the missing template

Security - Occurs with ColdFusion sandbox and other security exceptions

    Special variables

  • Couldn’t find any in specific but I’m sure there are, had some sandbox setup issues :)

MissingInclude - Thrown when a CF resource isn’t found when using cfinclude, cfmodule

    Special variables

  • cfcatch.misingFilename : The missing include filename

Lock - Exceptions which occur when failed locking operations occur.

    Special variables

  • cfcatch.lockName : the name of the lock that failed
  • cfcatch.lockOperation : the type of lock operation that failed(timeout, mutex or unknown)

Object - Object exceptions, occur when an operation is performed on an object or something invalid is done with an object

    Special variables

  • Nothing special

Expression - Exceptions thrown by invalid CF expressions

    Special variables

  • cfcatch.errNumber : The expression error number

Any - Other errors including custom errors, search engine errors and other Java exceptions not caught by CF.

I’m sure there more but this is what I found from testing. You can find Adobe’s (rather poor) explanation of the CF8 exceptions here

I recently had the need to disable ColdFusion passwords for both the Administrator and the Sandbox security sections of the CF backend. The best way to do this is to directly modify the security xml file that ColdFusion reads in. On the Mac I’m working on this security file was located in /Applications/JRun4/servers/cfusion/cfusion-ear/cfusion-war/WEB-INF/cfusion/lib/neo-security.xml

Alter the end of this file and there are a few booleans there that be set to disable sandbox security, disable admin security, disable rds security and set the admin user name(I believe thats what the final entry is, I haven’t looked into it)


<var name='sbs.security.enabled'><boolean value='false'/></var>
<var name='admin.security.enabled'><boolean value='false'/></var>
<var name='rds.security.enabled'><boolean value='true'/></var
<var name='admin.userid.root'><string>admin</string></var>

Hi there,

Google have been at it again, this year with a little more unbelievable April fools jokes..

http://www.google.com.au/intl/en/gday/index.html
http://mail.google.com/mail/help/customtime/index.html

On a more serious Google matter….they have began to release offline version of Google Docs to a limited number of users to begin with, not me yet unfortunately :( Need to install Google Gears and if you see an offline icon on the top right at docs.google.com you’ve got it. Only support for Wordprocessor so far, support for Spreadsheets and Presentations coming soon.

http://googledocs.blogspot.com/2008/03/bringing-cloud-with-you.html

I’ve only recently heard of the Acid3 test, which is a test to see how well your browser complies with web-standards
http://acid3.acidtests.org/

The new Windows/Linux versions of Opera claim to have 100% compliance..
http://labs.opera.com/news/2008/03/28/

I ran a couple of more tests on a Macbook Pro for the browsers I have on my machine out of curiosity.
FireFox 3.0b4 - 67/100
FireFox 2.13 - 53/100
Safari 3.0.4 - 41/100

Hi,
Haven’t had time to post recently and this is a relatively short one.

I’ve been coding with PHP again recently and was looking for something similar to ColdFusions cfdump and didn’t know until last week that the var_dump function existed, its very handy although it doesn’t output the dumped variable in a very user-friendly fashion.

As I posted previously I jailbroke my iTouch and was looking for a good app for IM. I installed Apollo IM hearing that it was meant to be very good but it only has .Mac, MSN, AIM and one other I can’t remember, the main problem with the app is that there doesn’t seem to be Google Talk support. After looking around for a bit I found Beejive which is excellent, very nice to use but unfortunately only works from within Safari and isn’t a standalone app but will do for the moment. Check it out at Beejve.

I had this error during the week when doing some CF troubleshooting. I couldn’t figure it out for a while and the error message wasn’t especially helpful.

Element 25316 is undefined in a Java object of type class coldfusion.runtime.TemplateProxy.

The error occurred (I don’t know why I was doing this) when I was trying to index into a CF object as you would a struct! So if I had an object oObject and try to do something like oObject[”someValue”] you will get an error like above.

Finally just a couple of quick really useful MYSQL snippets I picked up during the week. I needed to rename a MYSQL table, the SQL below does this nicely.


rename table myOriginalTable TO newTableName;

Another really great piece of SQL performs an insert if a record doesn’t exist and if it does exist it performs an update on the record.


INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

Coalesce is a nice MYSQL function, it returns the first non-null in a list. If there is nothing besides NULL in the list, 1 is returned as in the case below.


SELECT COALESCE(NULL,1) FROM tbl_test