Avatar

orangexception

@orangexception / orangexception.com

Hello World. My name is Bradley Moore. I'm an application developer and usability adventurer.
My resume has details on my professional experience. My achievements show off my personal goals.
Avatar

Status

This site inactive. The archive remains open.

Avatar

Text-transform Regular Expressions

I've been formatting emails lately. The CSS support is horrible at best. I've found it's easier to go ahead and apply `text-transform` while I'm building an email rather than let the email client try. Here's a couple of regular expressions that I built to handle text transformation with ColdFusion. ## Uppercase // Uppercase Words (text-transform: uppercase) sWords= REReplace( sWords , "(\w+)" , "\U\1\E" , "all"; ## Lowercase // Lowercase Words (text-transform: lowercase) sWords= REReplace( sWords , "(\w+)" , "\L\1\E" , "all" ); ## Capitalize // Capitalize Words (text-transform: capitalize;) sWords= REReplace( sWords , "(\w+)" , "\u\1" , "all" );

Avatar

SQL Server Suppression Table

## Suppress Stored Procedure Output I execute stored procedures from inside stored procedures a lot. It is a nice to reuse code so that the system behaves the same way for similar events. However, I don't always want the returned resultsets from an invoked stored procedure to interfere with the resultsets from the calling stored procedure. The question then is, "How do you suppress the output of stored procedures in SQL Server?" MySQL has a nice black hole that you can shove anything into and it disappears. The idea here is to implement this in SQL Server. This is not as robust of a solution as a black hole, but it works fairly well. You'll need to create a temporary table and allow the stored procedure results to insert into it. You'll need to craft the suppression table to match the resultset of the invoked stored procedure so that the$ -- SQL Server Suppression Table -- Suppress Stored Procedure Output -- Create Suppression Table CREATE TABLE #SuppressionTable ( Value000 VARCHAR(MAX) ) -- Insert ResultSet into Suppression Table INSERT INTO #SuppressionTable -- Execute Stored Procedure EXECUTE StoredProcedureThatReturnsUselessData -- Forget Suppressed Data DROP TABLE #SuppressionTable You can check out the gist at https://gist.github.com/4277332.

Avatar

Conditional SQL Server Statements without the Security Hole

This technique allows you to write a single query with conditional SQL without using the security hole of `EXECUTE`. I won't go into the security hole details in this post. If you're building conditional statements with `EXECUTE( @SQLString )`, then you have security problems. This technique will allow you to rewrite that $ Without further interruption, here's my code snippet: -- Skip The First Conditional WHERE 1= 1 -- Conditional SQL: -- If @iUserStatusID is 0, then no limit is imposed. -- If @iUserStatusID is not 0, then Users.StatusID must equal @iUserStatusID. AND Users.StatusID= CASE WHEN @iUserStatusID = 0 THEN Users.StatusID ELSE @iUserStatusID END You can check out the gist at https://gist.github.com/4060217. Okay, now to explain my choices. ## Skip The First Conditional -- Skip The First Conditional WHERE 1= 1 You can use any kind of mathematical constant here, but `1 = 1` is simple and lends itself to boolean thinking. When you compare a value to itself, then you do not affect the number of records in a query. Commenting conditionals on the `WHERE` line is messy and annoying. If you're only working with `AND` and/or `OR`, then the conditionals are easier to code, manipulate, debug and your code is consistent. ## Conditional SQL -- Conditional SQL: -- If @iUserStatusID is 0, then no limit is imposed. -- If @iUserStatusID is not 0, then Users.StatusID must equal @iUserStatusID. AND Users.StatusID= CASE WHEN @iUserStatusID = 0 THEN Users.StatusID ELSE @iUserStatusID END The idea here is similar to the one above. If a value is compared to itself, then it won't affect the number of records in a query. The trick is to modify the statement so that when needed, it does affect the number of records in a query. The `CASE` statement allows you to conditionally toggle the use of a variable. In this case, the statement is looking for a `0` value, but this can be changed to any kind of comparison. ## Conclusion You now have a way to create dynamic conditional statements in SQL Server without writing multiple queries. This technique is handy for those stuck with only stored procedure access to a database.

Avatar

Determining Truth When x of n Values Are True

Today's problem involves a common issue. **How do you determine if 2 of 3 values are true?** The first bit of conversation that pops into my head. "Well, that's easy." Quickly shut down by. "No, it ain't." I came up with two approaches to the problem: a manual and a functional solution. ## Functionally Determine When x of n Values Are True The function should accept an array of truthy and falsy values and the number of truths needed. The function should return true if the number of truths is found. Otherwise, it should return false. Those are some pretty simple requirements. I ended up writing this function, which is O(n). function hasXTrueValues( abTruthyAndFalsyValues , iRequiredTrueValues ) { var iTruthCount= 0; for( var bTruthyOrFalsyValue in abTruthyAndFalsyValues ) { if( bTruthyOrFalsyValue ) { iTruthCount++; if( iTruthCount == iRequiredTrueValues ) { return true; } } } return false; } This allows us to write a simple conditional statement. For example, here's how it would look if you wanted to determine if 2 of n values are truthy. if( hasXTrueValues( abTruthyAndFalsyValues , 2 ) ) { ... } t's a fairly simple solution. It's reusable. In the worst case scenario you're doing n checks. ## Manually Determine When x of n Values Are True What do I mean by manual? I mean creating a if statement by hand, which you probably do every day. Let's make a quick conditional that is truthy if 2 of 3 values are truthy. ( A && B ) || ( A && C ) || ( B && C ) Not bad. We can rearrange it as well. ( A && ( B || C ) ) || ( B && C ) You may have picked up that this is a factorial based statement, O(n!). It's not horrible to write on a small scale of x and n, but due to the factorial nature of the statement, it will grow quickly in size. Nothing's better than an example, so here's a manual conditional that is truthy if 2 of 5 values are truthy. ( A && B ) || ( A && C ) || ( A && D ) || ( A && E ) || ( B && C ) || ( B && D ) || ( B && E ) || ( C && D ) || ( C && E ) || ( D && E ) We can rearrange it as well into: ( A && ( B || C || D || E ) ) || ( B && ( C || D || E ) ) || ( C && ( D || E ) ) || ( D && ( E ) ) The statements certainly look pretty. You can almost imagine that this is how code is supposed to look. While you're imagining things, let's replace the letters with proper variable names. ( abTruthyValues[ 1 ] && ( abTruthyValues[ 2 ] || abTruthyValues[ 3 ] || abTruthyValues[ 4 ] || abTruthyValues[ 5 ] ) ) || ( abTruthyValues[ 2 ] && ( abTruthyValues[ 3 ] || abTruthyValues[ 4 ] || abTruthyValues[ 5 ] ) ) || ( abTruthyValues[ 3 ] && ( abTruthyValues[ 4 ] || abTruthyValues[ 5 ] ) ) || ( abTruthyValues[ 4 ] && ( abTruthyValues[ 5 ] ) ) Well, I know one thing for certain. My refactor list just found a new entry. The manual method is harder to read and update. It's also a slower algorithm to write and execute. The manual method is more prone to error. I tend to fix the odd parenthesis or remove redundant statements all the time. Now, I'll just be replacing these manual statements with a function call instead. # Conclusion All things considered, I'm a fan of speed. I'll take the functional method of O(n) over the manual method of O(n!) every day.

Avatar

Regular Expression to Insert Character after every X Characters

I had a simple problem today. I needed to validate some files, but all of the line breaks were missing. I was dealing with a fixed width format data. A quick regular expression later and I had readable data. Here's a few examples to demo the idea. ## Insert a line break after every 94 characters Find `(.{94})` Replace `\1\n` ## Insert a comma after every 10 characters Find `(.{10})` Replace `\1,`

Avatar

wget Reponse to Variable

I had a small problem to solve at work. A quick search or two later and here's a quick shell script to call a webpage and return the result to a variable. That's kind of cool, but I also work with development and QA servers that don't have valid SSL certificates. Adding `--no-check-certificate` eliminate those pesky self-signed or just badly signed SSL certif$ I also added `-t 1` to limit the retry count. Otherwise `wget` will retry forever, which is horrible if your servers go down or you're trying to run a job only once. This leaves us with the following: Enjoy.

Avatar

A better way to load your JavaScript. I've shared this on Google+ before.

Emil Stenstr?m created the script and explains everything on his post, (Lazy Loading Asynchronous JavaScript)[http://friendlybit.com/js/lazy-loading-asyncronous-javascript/]. The code is pretty simple. You change s.src to the script you want to load. (function() { function async_load() { var s= document.createElement('script'); s.type= 'text/javascript'; s.async= true; s.src= '/archive.js'; var x= document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } if ( window.attachEvent ) { window.attachEvent( 'onload' , async_load ); } else { window.addEventListener( 'load' , async_load , false ); } })(); After the window finishes loading, then the script loads and runs. Welcome to faster page loading.

Avatar

Making FW/1 Dance: Customizing ColdFusion Frameworks

This post covers customizing FW/1 to use a custom directory structure. This post is part of a mini-series on Making Frameworks Dance: Customizing ColdFusion Frameworks.

I like how Rails 3 applications are setup. I wanted to keep the following directory structure when converting the application to ColdFusion.

+app +assets +documents +images +javascripts +stylesheets +controllers +layouts +model +views +assets +lib +{framework} Application.cfc index.cfm

Moving FW/1 to /lib

FW/1 is a single compenent that resides at /org/corfield/.

You can safely move /org inside of /lib.

The only reference you need to update is in /Application.cfc. In /Application.cfc, change extends="org.corfield.framework" to extends="lib.org.corfield.framework".

Moving FW/1 Application Folders to /app

Application folders are all of the folders I listed under the /app directory, which includes: controllers, layouts, model, and views.

FW/1 also has a services folder that we're going to add to the /app folder.

FW/1 has a nice feature that easily allows you to move the application folders relative to the application root.

https://github.com/seancorfield/fw1/wiki/Developing-Applications-Manual
base – Provide this if the application itself is not in the same directory as Application.cfc and index.cfm. It should be the relative path to the application from the Application.cfc file.
In addition you can override the base directory for the application, which is necessary when the controllers, services, views and layouts are not in the same directory as the application’s index.cfm file. variables.framework.base should specify the path to the directory containing the layouts and views folders, either as a mapped path or a webroot-relative path (i.e., it must start with / and expand to a full file system path). If the controllers and services folders are in that same directory, FW/1 will find them automatically. If you decide to put your controllers and services folders somewhere else, you can also specify variables.framework.cfcbase as a dotted-path to those components, e.g., com.myapp.cfcs assuming that com.myapp.cfcs.controllers.Controller maps to your Controller.cfc and com.myapp.cfcs.services.Service maps to your Service.cfc.

The FW/1 wiki is refering to `variables.framework.base` within /Application.cfc. In order to move the application folders to /app we need to set this value.

Add the following to /Application.cfc:

variables.framework.base= "/app";

Conclusion

FW/1 is a pleasure to dance with. It is by far the easiest ColdFusion framework to customize. It was designed with motion in mind. The only customizing was in /Application.cfc, which is where I'd expect to find it.

Other Frameworks in Mini-series

I'll be covering multiple frameworks and the issues in getting them to work in the directory structure above. Each framework will be it's own post. This post will be updated with links to all posts in the mini-series so you can easily jump to your favorite.

Frameworks:

Avatar

Center Block Elements

There are several ways to center block elements. This is my reference on each method I've encountered.

It's good to know multiple ways to solve the problem, because you need to choose a solution that fits your layout.

These demos show the basics of various techniques to center a block element. Primary focus is only using CSS, but JavaScript is used when necessary.

  • Horizontal: Margin Auto
  • Positioned Absolutely
  • Positioned Absolutely With Unknown Dimensions
  • Vertical: Table Cell

Horizontal: Margin Auto

A block element can be horizontally centered by setting the left and right margins to auto.

margin: auto;

Positioned Absolutely

A block element with known dimensions can be centered by using absolute positioning.

Set top and left to 50% to find the middle of the space.

position:  absolute; top:        50%; left:        50%;

Elements are positioned from the top left corner. Offset the origin by setting the top and left margin to minus half of the height and width of the element.

height: 10em; width:  20em;
margin:         auto; margin-top:     -5em;   /* height / 2 * -1 = 10em / 2 * -1 = -5em */ margin-left:    -10em;   /* width / 2 * -1 = 20em / 2 * -1 = -10em */

Positioned Absolutely With Unknown Dimensions

You cannot offset the origin if you don't know the target element's height and width. JavaScript enables these values to be known.

Centering #target element using jQuery

$( document ).ready( start ); function start() {     centerTarget(); }
function centerTarget() {     var iWidth=    $( "#target" ).width();     $( "#target" ).css( "margin-left" , iWidth / 2 * -1 );        var iHeight=    $( "#target" ).height();     $( "#target" ).css( "margin-top" , iHeight / 2 * -1 ) }

You must wait for images to finish loading before finding their dimensions. Most JavaScript frameworks have a technique that will work. jQuery uses the .load() function.

Centering #target element that is an image or contains images using jQuery

$( document ).ready( start ); function start() {     $( "#target" ).load( centerTarget ); }
function centerTarget() {     var iWidth=    $( "#target" ).width();     $( "#target" ).css( "margin-left" , iWidth / 2 * -1 );        var iHeight=    $( "#target" ).height();     $( "#target" ).css( "margin-top" , iHeight / 2 * -1 ) }

Vertical: Table Cell

This method utilizes display: table-cell; to make vertical centering easy. See http://www.quirksmode.org/css/display.html for supported browsers (IE6 & IE7 do not support this method).

This method also relies on setting properties of the parent element.

#target-parent {     /* Vertical Centering */     display:            table-cell;     vertical-align:     middle;     height: 10em;     width:  20em;     background: #83BA00; } #target {     /* Horizontal Centering */     /* margin: auto; */          height: 5em;     width:  10em;          background: #f55500;      }

Source code for this post is available on GitHub. https://github.com/orangexception/centering-elements

Avatar

CFFTP Using a RSA Key

A short guide to connecting to a secure FTP server using a RSA key and ColdFusion.

This guide uses Windows XP, PuTTY Key Generator, and ColdFusion 8.

Download PuTTYgen from the linked web site and launch it.

Generate Key Files

  1. Press Generate Button
  1. Wiggle your mouse.
  1. Save your public key. Press the Save public key button.
  1. Give your key an awesomr name. This file is your public identification.
  1. Send your public key to your remote connection. You don't need to worry about sending this file over non-secure channels. As the name suggests, this file is for public use.
  2. (Optional, but you really should do this step.) Add a passphrase to your key. If you want to add additional security to your private key, then enter a value into the passphrase boxes. You'll need to enter this value again every time you use your private key.
  1. Save your private key. Make sure you export you key into the OpenSSH format. Under the Conversions menu, press Export OpenSSH key. Do NOT press the Save private key button (I'll explain later).
  1. Give your private key an awesomr name. This file must be kept secure.
  1. Your private and public keys should be created at this point.

Give your public key to your remote connection. They'll use it to validate your private key connection.

Move your private key to the server that will be using it. Make sure the file is not publicly accessible. This is a private file. If someone steals it, then they can impersonate you.

CFFTP Open Connection

CFFTP doesn't change much between using a password and using a key. When using a key, we add the attribute key and the attribute password becomes the passphrase field for the private key. If you skipped the passphrase step, then you do not use the password attribute for cfftp.

Here's a simple connection.

<cfset settings = { server= "remote-connection.com" , user= "orangexception" , passphrase= "theRefreshingException" secure= 1 , directory= "/" , connection= "SFTPWithRSAKey" , key= "e:/xact/path/to/PrivateOpenSSHKey" } /> <cfftp action= "open" connection= "#settings.connection#" server= "#settings.server#" username= "#settings.user#" key= "#settings.key#" password= "#settings.passphrase#" secure= "#settings.secure#" stopOnError= "yes" retryCount= 1 /> <cfftp action= "close" connection= "#settings.connection#" />

You should get a successful connection to your remote connection. Once connected, you can do normal SFTP operations with CFFTP.

You should use a passphrase, it's easy to setup and adds a bit of security to your private key. If you do use a passphrase, then you should definitely keep it encrypted. I used a plain-text passphrase as a quick example. 

Do NOT Press the Save Private Key Button Explanation

I found this post on Adobe's forums very useful. SFTP Secure FTP and PPK, invalid privatekey

ColdFusion does not recognize the normal PuTTY generated private keys. When you attempt to connect, then ColdFusion will throw an error. Error: invalid privatekey: e:/xact/path/to/key.ppk

Make sure you export you key into the OpenSSH format. Under the Conversions menu, press Export OpenSSH key.

You are using an unsupported browser and things might not work as intended. Please make sure you're using the latest version of Chrome, Firefox, Safari, or Edge.