Click to Expand
Projects

Find an assortment of projects in various states of completion.

Javascript Validator for jQuery

The jQuery validator is a script written to assist with datatype validation when submitting forms. Originally written in Mootools using OO principles, the script did not work alongside any other javascript libraries, and when ASP.Net projects started coming around, another validator was needed to work with the ASP.Net Ajax Javascript library.

With jQuery having no true class/object model, the script was written using a home-brewed variety of the module pattern (more info here) instead of creating a reusable class like was done with the Mootools version. The jQuery version is a singleton, but can handle separate 'groups' of form controls to validate against.

Usage is as such on an ASP.Net webform:

DataTypes
  • string
  • email
  • date
  • number
  • byte
  • short
  • money
  • postalcode (CAN)
  • phone
  • and more
var app = Sys.Application;
app.add_load(setupForm);
function setupForm(event) {
  Sys.UI.DomEvent.addHandler($get('<%= cmdSubmit.UniqueID %>'), 'click', validateForm);
  var v = oValidator;
  v.addCtrl('#<%= txtName.ClientID %>','Name');  
  v.addCtrl('#<%= txtEmail.ClientID %>','Email','email');        
}
function validateForm(event) {
  event.preventDefault();
  if (oValidator.validate()) {
    __doPostBack('<%= cmdSubmit.UniqueID %>','');
  } 
}

where 'cmdSubmit' is the submit button you are assigning the validate event to, and 'txtName' and 'txtEmail' are asp.net textboxes.

Method: addCtrl

Adds a control to the validator

Signature:
oValidator.addCtrl(element, title[, datatype, required, groupname]);
Arguments:
  1. element - (string) A string selector of the form field to validate against.
  2. title - (string) The title of the field. Usage is '"title" is a required field'.
  3. datatype - (string, optional) A string that determines the datatype to validate the associated form field with. Defaults to 'string'
  4. required - (boolean, optional) A bool value that sets whether the form field is a required field and cannot be empty. Defaults to true
  5. groupname - (string, optional) A string used to group controls together to validate. See oValidator.validate(). Defaults to 'group'

Method: validate

Validates the page or form (depending on setup).

Signature:
oValidator.validate([groupname]);
Arguments:
  1. groupname - (string, optional) The matching string from the addCtrl method. Defaults to 'group'
Returns:
  • (boolean) If the assigned form fields validate, returns true. Otherwise, returns false, alerts the user, and the first failed field will be brought to focus.
Download
Close
Javascript Validator for Mootools

The Mootools validator was the original attempt at creating an all-encompassing validation script that would validate a number of different data types, alert the user when validation fails, and be easy enough to extend for use in multiple projects. It's old so don't expect all the features from the jQuery version.

Class: oValidator

A validation queue class that collects inputs, vaidates them, returns the result while placing focus on the control in queue that failed.

Syntax:
new oValidator(form);
Arguments:
  1. form - (string) A string of the id for the form to validate. Required.

Example

window.addEvent('domready', function() {
	var form = $('j_ContactForm');
	$('j_btn').addEvent('click', function(e){
		new Event(e).stop();
		var v = new oValidator(form);
		v.addCtrl('j_name','Title');
		v.addCtrl('j_email','Email','email');
		if(v.validate()) {
			//Success
		} else alert(v.message);
	});
});

where 'j_ContactForm' is the id of the form, j_btn is the id of the submit button firing the validation event, j_name/j_email are input[type=text].

Method: addCtrl

Adds a control to the validator

Signature:
obj.addCtrl(element, title[, datatype]);
Arguments:
  1. element - (string) A string id of the form field to validate against.
  2. title - (string) The title of the field. Usage is '"title" is a required field'.
  3. datatype - (string, optional) A string that determines the datatype to validate the associated form field with. Defaults to 'string'

Method: validate

Validates the form provided at initialization.

Signature:
obj.validate();
Returns:
  • (boolean) If the assigned form fields validate, returns true. Otherwise, returns false with messages in the queue.
Download
Close
Javascript Compressor

The Google Closure compiler was built to work hand in hand with the Closure library, the Javascript library used to build Gmail and the other Google properties on the internetz.

The compiler itself is provided as a standalone jar file, which you can download from their labs here. As it is a jar file, you can use it with Coldfusion to compress your own javascript. On windows, just drop the compiler.jar file into your '/lib' folder located in your Coldfusion installation folder.

See the blog post on tomb.ca for syntax or download the cfm file below for an example.

Download
Close
Bulletproof Templates
Content coming soon.
.Net File Manager for TinyMCE
Content coming soon.
SessionSafe session manager for Coldfusion
Content coming soon.
xLife Musician Framework
Content coming soon.
WCF Uploader
Content coming soon.
Close
Click to Expand
Process

Find examples, extensions, and walk-throughs.

Visitor Pattern & Object Data

How often have we seen something like this and groaned there has to be a better way?

public class Person
{
	public Person(DataRow persondata)
	{
		this.PersonID = persondata["id"];
		this.PersonName = persondata["name"];
		this.PersonAge = persondata["age"];
	}
	public Guid PersonID { get; set; }
	public string PersonName { get; set; }
	public int PersonAge { get; set; }
}

There is a better way, and it follows a common pattern set out by the GOF. It’s called the visitor pattern. Objects are the perfect visitor, they usually start empty and along their travels they pick up all kinds of goodies. Even in real life, we are conceived by the ultimate visit (between mum and dad), where we pick up some of our attributes. Our humble computer objects can have the same course in life; empty pockets need to be filled with stuff.

First let start by tweaking that original person object (I'll go through the c# example first and follow it up with some javascript):

public class Person : Base
{
	public Person() { }
	public int PersonID { get; set; }
	public string PersonName { get; set; }
	public int PersonAge { get; set; }
}

Simple is better right? First thing you should notice is the inheritance.

public abstract class Base : IDataContainer
{
	public IDataContainer BindData(IDataSource v)
	{
		v.fill(this);
		return this;
	}
	public void SaveData(IDataSource v)
	{
		v.retrieve(this);
	}
}

This is the basis of the visitor object. Better to build to an interface than an object, so the methods come from this interface, labeled IDataContainer.

public interface IDataContainer
{
	IDataContainer BindData(IDataSource v);
	void SaveData(IDataSource v);
}

It's a little strange, but in the end it boils down to our object needs to either fill his pockets (BindData) or empty his pockets (SaveData). If this seems a little backwards to you, you are right. It's totally backwards.

The object is really just a temporary entity that carries data from point A (say a browser) to point B where we need to save it (say the database), or in reverse providing data from the DB to the client.

Philosophy aside, the IDataContainer interface contains a reference to another interface:

public interface IDataSource
{
	void fill(IDataContainer obj);
	void retrieve(IDataContainer obj);
}

Notice how the datasource doesn't actually return anything?

Now any data repository which implements this interface can immediately start filling our data containers. Say we have a controller which implements IDataSource:

public void fill(IDataContainer obj)
{
	var item = (Person)obj;
	var data = DataContext.People.Where(p => p.id == item.PersonID).Single();
	item.PersonName = data.name;
	item.PersonAge = data.age;
}

We leave the passing of the filled object to the data container, and keep the passing of the data to the object the job of the controller. Which is personally how I think things should be, keep the data management, in the data layer, and keep your objects as simple as possible. POCO.

Right now I’m sure all of this seems like a lot of work to do the same thing you can do within the object itself, but wait until you seem implementation before you totally write off the process.

var Tom = new Person() { PersonID = 5 }.BindData(new PersonIO);

Who doesn’t like fluent programming? Now I'll provide a javascript example you can copy and paste to see how things work with a little less code when things aren't strictly typed.

var DataSource = new Class({
	local_data : 
		{
			"1001": {
				"type": "Regular",
				"cost": "$4.99"
			},
			"1002": {
				"type": "Chocolate",
				"cost": "$9.00"
			},
			"1003": {
				"type": "Blueberry",
				"cost": "$7.99"
			},
			"1004": {
				"type": "Devil's Food",
				"cost": "$14.99"
			}
		},
	local_hash: "",
	initialize: function() {
		var jData = eval(this.local_data);
		this.local_hash = new Hash(jData);
	},
	fill_object: function(pojo) { 
		if (this.local_hash.has(pojo.id)) {
			var data = this.local_hash.get(pojo.id);
			pojo.name = data.type;
			pojo.cost = data.cost;
		}				
	}
});
var DataContainer = new Class({
	id: "",
	initialize: function(key) {
		this.id = key;
	},
	data_bind: function(v) { 
		v.fill_object(this);
		return this;
	}
});
window.addEvent('domready', function() {
	var datasource = new DataSource();
	var batter = new DataContainer("1001");
	var test = batter.data_bind(datasource);
	alert(test.name);
	var test2 = new DataContainer("1002").data_bind(new DataSource());
	alert(test2.name);
	alert(test2.cost);
});

Note: the example above requires Mootools. The download should have examples in c#, coldfusion, and javascript. If it doesn't, it will soon.

Download
Close
Javascript Validator Usage
Content coming soon.
POSTing to WCF from jQuery and Mootools
Content coming soon.
Consuming WCF web services from Coldfusion
Content coming soon.
Live logging using websockets and Google Chrome
Content coming soon.
Overclocking the AMD processor
Content coming soon.
RAM Timings and OC settings for various hardware configurations
Content coming soon.
Virtualizing on the Microsoft Hyper-V platform
Content coming soon.
Close
Click to Expand
Tomb<Blog>
Recent Posts on tomb.ca
Automatically Colorizing your Coldfusion

I tried to publish this on my blogger account where I publish these snippets, but it wouldn't accept the syntax. Good thing I have my own blog too. Thank you MangoBlog

<cfset obj = createObject("java","coldfusion.util.FormatSource")>
<cfoutput>
    #obj.formatFile(Expandpath('coloring.cfm'))#
</cfoutput>
Mootools bug with the HTML5 meter tag

If you are wondering why this does not work:

var v1 = $('metertag').get('value');

on the new HTML5 <meter>  tag you are not alone.

This works so no biggy:

var v1 = $('metertag').getAttribute('value');

I'd inform the mootools crowd but I hate them.

Note: For some reason this works in IE8. Not google chrome, firefox, opera or safari (latest builds). Without the shiv. Weird.

TinyMCE, custom plugins and ASP.Net

'theForm.__EVENTTARGET' is null or not an object

If you encounter this error in Internet Explorer there is an easy fix, just add

 onload="javascript: theForm = document.forms[0];"


to the body tag of the aspx page you are having problems with.

I was able to reduce the problem to a single javascript file tiny_mce_popup.js, but since there is no uncompressed version available out there I wasn't able to see what the problem really was. There were however, a lot of other people encountering the same issue but strangely enough, no fix from MoxieCode. And the fix I found came from their forums.

References:
http://tinymce.moxiecode.net/punbb/viewtopic.php?id=12744
http://tinymce.moxiecode.com/punbb/viewtopic.php?id=10686 

Using the Google Closure Javascript Compiler with Coldfusion

It took me a couple of hours, but I was finally able to piece together enough of the Google closure snippets out there to create a functioning example of code so that you too can start testing the wonderful world of javascript compression.

<cfset strJSFilePath = ExpandPath("uncompiledscript.js") /> 
<cfset strJSFileOutPath = ExpandPath("compiled.js") /> 
 
<cffile action="read" file="#strJSFilePath#" variable = "js" /> 
 
<cfset compiler = createObject("java","com.google.javascript.jscomp.Compiler") /> 
<cfset instance = compiler.init() /> 
<cfset options = createObject("java","com.google.javascript.jscomp.CompilerOptions").init()  /> 
<cfset level = createObject("java","com.google.javascript.jscomp.CompilationLevel")  /> 
<!--- cfset level.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options)  / ---> 
<cfset level.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options)  /> 
<cfset jsfile = createObject("java","com.google.javascript.jscomp.JSSourceFile")  /> 
<cfset extern = jsfile.fromCode("externs.js", "function alert(x){};") /> 
<cfset jscript = jsfile.fromCode("input.js", "#js#") /> 
<cfset result = instance.compile(extern, jscript, options) /> 
 
<cfif result.success> 
<cffile action = "write" file = "#strJSFileOutPath#" output = "#instance.toSource()#" /> 
</cfif>

The advanced compilation mode is commented out if you want to try messing with that setting. I wasn't able to get my test script to work with that on but I'll keep trying. The documentation is sketchy out there right now, but I'm sure it'll improve once people get to play with these things a little more.

Remember to add the jar file to your Coldfusion library path if you want this example to work.

Code Coloring / Example / Documentation 

LDAP Connection String for ASP.NET ActiveDirectoryMembershipProvider in SBS2003

I have been working on an intranet project that connects directly to the companies AD. Problem is that the domain controller is on a Microsoft Small Business Server 2003 server and where the connection string of 

LDAP://domain.local/CN=Users,DC=domain,DC=local

 

will work on a normal enterprise or standard server 2003 installation, on SBS it will not. On SBS2003 things are set up a little differently.

LDAP://domain.local/OU=SBSUsers,OU=Users,OU=MyBusiness,DC=domain,DC=local

 

Embarrassingly, it took me WAY too long to figure that out.

Javascript History Bugs in Google Chrome

If you are having problems with google chrome and the infamous history.go() function look no further.

This will not work:

<a onclick="history.go(-1)" href="#">test</a>

This does:

<a href="javascript:history.go(-1)">test</a>

I hate losing time to quirky crap like that since they have been building these things for close to two decades now. Hope I can save someone else time lost.

Regex for Byte and Short

Took way too long to find the regex for byte, and I couldn't find one at all for a short (int16)

Did find this though. I love the internet machine sometimes...

Byte: 
(^(
    [0-9]|
    [1-9][0-9]|
    1[0-9][0-9]|
    2[0-4][0-9]|
    25[0-5]
)$);
Short: 
(^(-?
    [0-9]{1,4}|
    [12][0-9]{4}|
    3[01][0-9]{3}|
    32[0-6][0-9]{2}|
    327[0-5][0-9]|
    3276[0-7]|
    -3276[0-8]
)$);

 

I think the short one needs a little massaging. I still have to do one for int32, but I'm going to look for a better way to do numeric ranges with regular expressions.

Edit: Put regexes on separate lines.

ASP.Net DropDownList SelectedIndex Extension

I hate having to always look up the safe method of assigning values to a drop down list in asp.net plus I think its a little verbose.

Here is the old way I've been doing things:

DropDown1.SelectedIndex = DropDown1.Items.IndexOf(DropDown1.Items.FindByValue(value)); 

And now here is my extension class:

public static int SelectedIndex(this DropDownList ddl, string key)
{
    return ddl.Items.IndexOf(ddl.Items.FindByValue(key));
} 

And the implementation is like this:

DropDown1.SelectedIndex = DropDown1.SelectedIndex(value)); 

I went further and set the index right in the extension. Less code is better if it reads the same.

Close