<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>BIT Consultants &#187; Code Snippets</title>
	<atom:link href="http://www.bitconsultants.net/tag/code-snippets/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bitconsultants.net</link>
	<description></description>
	<lastBuildDate>Sat, 28 Jan 2012 02:19:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Javascript Querystring Parameters</title>
		<link>http://www.bitconsultants.net/2011/javascript-querystring-parameters/</link>
		<comments>http://www.bitconsultants.net/2011/javascript-querystring-parameters/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 22:39:37 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.bitconsultants.net/?p=486</guid>
		<description><![CDATA[Hi all, just wrote up a javascript object to parse url parameters. You can take parameters out of the querystring or the url hash. Usage Script]]></description>
			<content:encoded><![CDATA[<p>Hi all, just wrote up a javascript object to parse url parameters. You can take parameters out of the querystring or the url hash.</p>
<p>Usage</p>
<pre class="brush: jscript; title: Code Example; notranslate">
//assuming <a href="http://www.example.com/index/?foo=bar&#038;baz=baa#test=true" rel="nofollow">http://www.example.com/index/?foo=bar&#038;baz=baa#test=true</a>

url.href;
//returns <a href="http://www.example.com/index/?foo=bar&#038;baz=baa#test=true" rel="nofollow">http://www.example.com/index/?foo=bar&#038;baz=baa#test=true</a>

url.path
//return /index/?foo=bar&amp;baz=baa#test=true

url.get('foo');
//returns 'bar'

url.get('test');
//returns true
</pre>
<p>Script</p>
<pre class="brush: jscript; title: Code Example; notranslate">
var url = (function(){
	var _href = location.href;
	var _path = location.pathname;
	var _qs = location.search.replace(/\?/, '');
	var _hash = location.hash.replace(/\#/, '');

	var _parse = function(string){
		var params = string.split('&amp;');
		var holder = [];

		for(var i = 0; i &lt; params.length; i++){
				var temp 	= params[i].split('=');
				var key 	= temp[0];
				var val 		= temp[1];
				holder[key] = val;
		}
		return holder;
	};

	var _qs_params 	= _parse(_qs);
	var _hash_params = _parse(_hash);

	return {
		href:_href,
		path:_path,
		get:function(name){
			var retval = null;
			if(_qs_params[name] !== undefined){
				retval = _qs_params[name];
			} else if(_hash_params[name] !== undefined) {
				retval = _hash_params[name];
			}
			return retval;
		},
		go:function(loc){
			location.href = loc;
		},
		back:function(item){
			if(item !== undefined){
				item = -1;
			}
			history.go(item);
		}
	};
})();
</pre>]]></content:encoded>
			<wfw:commentRss>http://www.bitconsultants.net/2011/javascript-querystring-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simplified Interface to HTML5 local storage</title>
		<link>http://www.bitconsultants.net/2010/simplified-interface-to-html5-local-storage/</link>
		<comments>http://www.bitconsultants.net/2010/simplified-interface-to-html5-local-storage/#comments</comments>
		<pubDate>Wed, 29 Dec 2010 06:00:45 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.bitconsultants.net/?p=336</guid>
		<description><![CDATA[Documentation &#038; Sandbox: http://rmcvey.github.com/jsper Cart example: http://rmcvey.github.com/jsper/cart_example.html I decided it was time to dive into the HTML5 local storage API the other night, knowing that it has<a href="http://www.bitconsultants.net/2010/simplified-interface-to-html5-local-storage/"> Read More...</a>]]></description>
			<content:encoded><![CDATA[<p><strong>Documentation &#038; Sandbox:</strong> <a href="http://rmcvey.github.com/jsper">http://rmcvey.github.com/jsper</a><br />
<strong>Cart example:</strong> <a href="http://rmcvey.github.com/jsper/cart_example.html">http://rmcvey.github.com/jsper/cart_example.html</a><br />
<br />
I decided it was time to dive into the HTML5 local storage API the other night, knowing that it has a lot of potential. There are a few  problems inherent to using it, the biggest problem being lack of support in older browsers (and to a lesser degree that it is not implemented exactly the same across browsers). The other major problem I have with localStorage is that you can only store strings. I have found a few classes that help with localStorage, but I have problems with them too because:</p>
<ul>
<li>they utilize browser plugins like Flash</li>
<li>are enormously cumbersome to use with too many configuration options,</li>
<li>and once again, only store strings. </li>
<li>no unit tests</li>
<li>buggy</li>
<li>did I mention they are cumbersome to use and only hold strings????</li>
</ul>
<p>So, I have set out to resolve these grievances and have come quite close with jsper.  JSPER is a wrapper class around local storage that provides a more friendly api to localStorage using simple get and set methods:</p>
<pre class="brush: jscript; title: Code Example; notranslate">
jsper.set('foo', {bar:'baz',boz:{bez:'biz'}});
//jsper.get returns the type of object you gave it; in this case, an object
var my_object = jsper.get('foo');

jsper.set('arr', ['a', 'b', 'c', 'd']);
// returns an array
var my_array = jsper.get('arr');
</pre>
<p>In addition to automatic serialization/deserialization, there are a number of other useful methods, most of which (non-getters) are chainable, overloaded and accept callbacks. Jstore allows you to inspect the current storage engine, force a different storage engine (including session-lifetime storage).</p>
<p>Iterating over a collection</p>
<pre class="brush: jscript; title: Code Example; notranslate">
// set an array in storage
jsper.set('an_array', ['This', 'is', 'pretty', 'cool']);
var message = &quot;&quot;;
// perform iteration, data is the stored value and index is numerical index
jsper.each('an_array', function(data, index){
   message += &quot; &quot;+data;
});
console.log(message);//outputs: &quot;This is pretty cool&quot;
</pre>
<p>Lots more information @github: <a href="http://github.com/rmcvey/jsper">http://github.com/rmcvey/jsper</a><br />
Also, I made it into a jquery plugin if you are into that sort of thing: <a href="http://plugins.jquery.com/project/jsperdb"></p>]]></content:encoded>
			<wfw:commentRss>http://www.bitconsultants.net/2010/simplified-interface-to-html5-local-storage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Validating Data with Enhanced Declarative Data Integrity Rules</title>
		<link>http://www.bitconsultants.net/2010/validating-data-using-tuples-stored-in-column-comments/</link>
		<comments>http://www.bitconsultants.net/2010/validating-data-using-tuples-stored-in-column-comments/#comments</comments>
		<pubDate>Sat, 08 May 2010 05:48:09 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.bitconsultants.net/?p=255</guid>
		<description><![CDATA[Visit us at our new Google Code project page: http://code.google.com/p/metadata-validator/ Problem Definition Data validation and integrity assurance are complex subjects that have strong opinions tied to the<a href="http://www.bitconsultants.net/2010/validating-data-using-tuples-stored-in-column-comments/"> Read More...</a>]]></description>
			<content:encoded><![CDATA[<p><strong>Visit us at our new Google Code project page: <a href="http://code.google.com/p/metadata-validator/">http://code.google.com/p/metadata-validator/</a></strong></p>
<h2>Problem Definition</h2>
<p>Data validation and integrity assurance are complex subjects that have strong opinions tied to the way they are implemented. Some strongly feel that the database can handle validation using the column&#8217;s attributes (size, data type, etc) and TRIGGERS/STORED PROCEDURES can provide means to enforce complex business rules. This is true, but there are many caveats and arguments against this approach. Should a data source be performing logic? According to <a href="http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/triggers.htm#g22503">Oracle&#8217;s website</a>:</p>
<p style="padding-left: 30px;">&#8220;<em>Although triggers are useful for customizing a database, use them only when necessary. Excessive use of triggers can result in complex interdependencies, which can be difficult to maintain in a large application</em>&#8220;</p>
<p>Those in opposition to this approach feel that it is not the job of the database to perform logic, only to store data. So, who is right?<br />
How should data validation be handled? Triggers or code? Honestly, both is usually the practice. The current implementations of Declarative Data Integrity Rules in the database marketplace give us simple rules to validate against (again: size, data type, nullable, etc) and if we don&#8217;t validate data in our code prior to insertion the database errors out. Though mindless and tedious, it is a straightforward task to code validation prior to executing SQL in your programming language.</p>
<p>I think that both opinions are correct, but both approaches are inadequate. Logic <strong><em>should </em></strong>be separated from data. However, rules about data stored in your database are really metadata. Why should programmers have to tweak code every time the table changes? Why should DBAs have to worry that programmers validation is insufficient and not have any control over the data integrity? I believe the database should dictate to us, in specific terms, what it is expecting. In addition, programmers and DBAs should be able to work together to formulate the data validation and that is should be in only one place.</p>
<h2>Current Practice</h2>
<p>Most of the time, a DBA will create a table with data type, length, unique and referential constraints. These rules are enforced by the database, programmers are handed back an error message which has to be parsed into a friendly error. In some shops, STORED PROCEDURES and TRIGGERS are used to validate data prior to insertion. As we pointed out above, this is not an encouraged practice and makes a data source a logic engine.</p>
<p>Let&#8217;s say we have a table defined as such:</p>
<pre class="brush: sql; title: Code Example; notranslate">

id INT(8) NOT NULL,
name VARCHAR(40),
zip_code VARCHAR(10)
</pre>
<p>Programmers take the constraints defined above (i.e. &#8220;INT&#8221;, &#8220;NOT NULL&#8221;, 40, etc) and write up code validation for each of those columns. If DBAs alter the number of columns or the metadata of any one of the columns, the code needs to be updated accordingly. Conversely, if the programmers don&#8217;t properly validate the raw data in code, we could easily end up with &#8220;NOTAZIP&#8221; in our zip_code field. In this way, the technologies are seemingly blind of each other except for a tin-can phone that can pass simple messages back and forth. This is not a knock against the technology, they were made to be platform independent (in terms of interfacing) and not necessarily to know everything about each other.  This is the price we have to pay for an exceedingly friendly means of storing and retrieving data.</p>
<h2>Proposed Solution</h2>
<p>Utilizing dynamic functions, JSON and metadata stored in column comments of my database I was able to validate data against any table with only one validation class (that isn&#8217;t very long!). I have yet to see a column or table comment be anything slightly useful (if anything at all). Up until two days ago, every time I saw the field to insert a comment in phpmyadmin  I would think &#8220;I guess that&#8217;s a nice feature&#8230;&#8221;, and then move on. Then I realized that using (in MySQL) SHOW FULL COLUMN FROM {TABLE}, I can get that comment&#8217;s value back. And using my programming language (PHP), I could do the following:</p>
<pre class="brush: php; title: Code Example; notranslate">

$data = json_decode($comment);
</pre>
<p>I now am holding an object created from metadata to do what I will with.</p>
<p>The initial data I inserted into a column COMMENT was a minified representation of this:</p>
<pre class="brush: jscript; title: Code Example; notranslate">
'{	&quot;insert_helpers&quot;: {
		&quot;functions&quot;: {
			&quot;func1&quot;:{
				&quot;name&quot;:&quot;strtotime&quot;,
				&quot;params&quot;:{
					&quot;param1&quot;:&quot;+20 years&quot;
				}
			},
			&quot;func2&quot;:{
				&quot;name&quot;:&quot;str_replace&quot;,
				&quot;params&quot;:{
					&quot;param1&quot;:&quot;!!&quot;,
					&quot;param2&quot;:&quot;!&quot;,
					&quot;param3&quot;:&quot;@this&quot;,
				}
			}
		}
	},
	&quot;validators&quot;: {
		&quot;maxlength&quot;:&quot;10&quot;,
		&quot;minlength&quot;:&quot;2&quot;,
		&quot;patterns&quot;:{
			&quot;pattern1&quot;:{
				&quot;pattern&quot;:&quot;[^0-9]&quot;,
				&quot;example&quot;:&quot;This is data without numbers&quot;
			}
		}
	}
}'
</pre>
<p>This was then validated with code very similar to this:</p>
<pre class="brush: php; title: Code Example; notranslate">
/**
*
* NOTE: I have not tested this code
* I typed directly it into notepad++ for your reading,
* not for executing, if it works, great!
*
*/
$json 				= json_decode($comment);
$helper_functions 	        = $json-&gt;{'insert_helpers'};
$validators			= $json-&gt;{'validators'};
$errors				= array();

//$row_value = $result['field'];
foreach($helper_functions as $function)
{
	$params = array();
	foreach($function-&gt;{'params'} as $param)
	{
		//insert row value
		if($param == '@this')
		{
			$param = str_replace(&quot;@this&quot;, $row_value, $param);
		}
		array_push($params, $param);
	}
	if(is_callable($function-&gt;{'name'})
	{
		$row_value = call_user_func_array($function-&gt;{'name'}, $params);
	}
}

if(is_object($validators))
{
	if(is_object($validators-&gt;{'minlength'})
	{
		if(sizeof($row_value) &lt; $validators-&gt;{'minlength'})
		{
			array_push($errors, &quot;$row_value is not long enough&quot;);
		}
	}
	if(is_object($validators-&gt;{'maxlength'})
	{
		if(sizeof($row_value) &gt; $validators-&gt;{'maxlength'})
		{
			array_push($errors, &quot;$row_value is too long&quot;);
		}
	}
	if(is_object($validators-&gt;{'patterns'})
	{
		foreach($validators-&gt;{'patterns'} as $pattern)
		{
			if(preg_match(&quot;/$pattern-&gt;{'pattern'}/&quot;, $row_value))
			{
				array_push($errors, &quot;$row_value is not in correct format [example: $pattern-&gt;{'example'}&quot;);
			}
		}
	}
}
</pre>
<p>If you didn&#8217;t pick it up by reading through the code, these functions couldn&#8217;t care less what table you are dealing with and the same set of code works against any and all columns. In addition, the validation rules (JSON) can be handed to the client side code to perform validation prior to reaching the server. All major databases have a comment column and most modern programming languages allow behavior like the example I posted.</p>
<p>I will post my php class that facilitates this process soon.</p>
<p>Anxious to hear people&#8217;s thoughts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.bitconsultants.net/2010/validating-data-using-tuples-stored-in-column-comments/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using xcache
Page Caching using xcache
Object Caching 394/451 objects using memcached

Served from: www.bitconsultants.net @ 2012-02-05 16:08:49 -->
