Category Archives:

Quick Tips

Posted on August 26, 2008 by Doug Burns

Securing Java Objects for Plain Text Transport

Recently I needed a way to secure some data that was going to be placed into an XML document. By using the Java APIs SealedObject class, along with the public domain Base64 class, I was able to secure an entire object, then encode it as text for inclusion in the XML.

To accomplish this, I created a class called Encrypter which provides one method for encryption and serialization, and another for reversing the process. I've listed the code for that class below, as well as another that demonstrates its use.

Update: We have posted the source for Encrypter, along with a compiled .jar to the Arc90 lab.

Continue reading "Securing Java Objects for Plain Text Transport" »

| Comments (0) | Technorati Tags :

Posted on August 15, 2008 by Joel Potischman

Empty Subclasses Are Good

I write lots of server-side software with XML APIs. I'm constantly taking an XML document as input, maybe transforming it to another format, sending that XML doc somewhere for processing, then returning the resulting XML back to the client. It's all nice and flexible and loosely coupled, but if all my parameters are of type XmlDocument my code is hard to read, and I may accidentally confuse parameters and still compile just fine. By subclassing XmlDocument and adding no new code, I can get compile-time checks against parameter confusion, better readability, and all the XmlDocument functionality I know and love still works unchanged.

Continue reading "Empty Subclasses Are Good" »

| Comments (0) | Technorati Tags :

Posted on August 4, 2008 by Ben Sgro

DoubleChecking your PHP

PHP allows you to define variables anywhere, at any time. They do not have to be defined prior to use. This can lead to silly bugs when you misspell a variable name. Anytime I found one of these errors in my code, I'd say to myself, "I wish I had a script that could show me alphabetized variable lists with a count" - so I built this script to save myself debugging time.

DoubleCheck (db.php) can be run against a PHP file and will output an alphabetized list of variables with their count. It will also print out methods with their count. Its still in version 0.1 and I hope to expand on it in the future.

Feel free to contact me with request or bug fixes.

Enjoy!

| Comments (2) | Technorati Tags :

Posted on July 30, 2008 by Chris Dary

Mac OS X: A Keyboard Shortcut for Maximize Window

This is probably one of the most useful 'custom' tweaks I've added to my mac since I got it - I use it constantly.

Add a Keyboard Shortcut to Maximize the Current Window using Quicksilver

I use Command-Shift-M.

| Comments (1) | Technorati Tags :

Posted on July 30, 2008 by Joel Potischman

Otherwise Blow Up

Our applications frequently need to convert XML documents between systems. While straight XSL does a great job at mapping System A's enumerations to System B's, I've found it's very handy to include an <xsl:otherwise> to make sure mismatches are mapped to an obvious error value instead of just being quietly lost in translation.

Let's say my homegrown candy inventory system uses numeric enumerations to indicate different types of candy, but our vendor-made candy production system uses text codes. The following XSL snippet will translate MyCandyType to VendorCandyType:

Continue reading "Otherwise Blow Up" »

| Comments (1) | Technorati Tags :

Posted on July 25, 2008 by Javier Julio

Defining Dynamic XML Literals in ActionScript 3

Recently, I was working on my first Flex project where I was consuming XML via a service. Whenever I wanted to make data changes with the service, I was required to send in an XML packet. Since AS3 has native support for XML literals, I wanted to create my small XML packet inline. For example:

var changeSet:XML = 
    ACTIVEQUOTE
          ;

Continue reading "Defining Dynamic XML Literals in ActionScript 3" »

| Comments (1) | Technorati Tags :

Posted on July 22, 2008 by Chris LoSacco

Charles, SSL, and you

Is Charles messing with your SSL traffic? You can fix it by telling Firefox (or, shudder, IE) that the Charles SSL proxy is a valid certificate provider. Here are the instructions:


| Comments (0) | Technorati Tags :

Posted on July 17, 2008 by Chris Dary

Use grep? Try ack!

For you command line addicts like myself.

I find myself using grep constantly to search within files. Most often in the format 'grep -r "phrase" * | grep -v .svn' To search subdirectories, and then filter out any subversion files. Which sucks.

I recently stumbled upon 'ack', which is a similar search function, but with a whole lot more features, and way faster by default.

With it, I only need to type 'ack "phrase" *' to get the same result. Neat!

Some reasons to use ack:
  • Ignores subversion directories by default.
  • Color highlighting of matches.
  • Full perl regular expression search capable
  • type specific filtering with --php, --perl, etc
  • Regular expression based file matching

It's neat. Check it out: http://petdance.com/ack/

| Comments (1) | Technorati Tags :

Posted on July 10, 2008 by Alex Gutierrez

Extending Column Background Color--without Images!

Lets go straight to the HTML:

My title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

My title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

My title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

and its corresponding style:
* { margin: 0; padding: 0; }
body { text-align: center; /*Hello IE*/ }
p { padding-bottom: 1em; line-height: 1.4; }
#canvas { width: 49em; margin: 0 auto; text-align: left; background-color: #F0F0F0; }
#right { float: right; width: 25%; }
#right ul { margin-left: 2em; }
#left { margin-right: 25%;background-color: #FFF; }
Explanation: Use the id "canvas" to assign the right column color. Then give id "left" a background color of white. Click here to view an example.

| Comments (0) | Technorati Tags :

Posted on June 26, 2008 by Javier Julio

Enabling A Drop Shadow On A Flex Container

To set a drop shadow on say a VBox or HBox component you simply set the boolean property dropShadowEnabled to "true" -- but this is not enough to make the drop shadow appear. An example:

Continue reading " Enabling A Drop Shadow On A Flex Container" »

| Comments (0) | Technorati Tags :

Posted on June 25, 2008 by Joel Potischman

In praise of System.Object

In this Quick Tip, I show you how to make a method that deals with System.Object parameters more type-safe by converting it to use generics. Last year I had written a wrapper class to talk to the ASP.NET caching system for me. It returned cached objects as System.Object for maximum flexibility. The client would cast to the desired type, but it always bugged me, because it wasn't very type-safe. Consider the following chunk of code:

It will compile just fine, but it will blow up when I run it, because silly me, WhenDidIDoThis contains a DateTime, not an integer. It's far safer to rewrite my code to use generics:

Hmm. Actually, that same logic error still compiles just fine, but hey, at least my code now signals its intent more clearly. The bigger problem is now I'm getting a compiler error elsewhere. Let's see why.

Continue reading "In praise of System.Object" »

| Comments (2) | Technorati Tags :

Posted on June 12, 2008 by Javier Julio

Using ColdFusion and LCDS in AIR-powered Flex Applications

Previously, I've discussed how to use ColdFusion Components (CFCs) in AIR-powered Flex applications but I never got a chance to follow up on how to use CF8's integrated LiveCycle Data Services ES in AIR.

Continue reading "Using ColdFusion and LCDS in AIR-powered Flex Applications" »

| Comments (0) | Technorati Tags :

Posted on June 11, 2008 by Doug Burns

Layers of Java Logging

The Java Logging API is great for tracking the internal workings of your application, both during development and after it goes to production. The API is based on a highly flexible configuration model that gives you complete control over what gets logged and where it gets logged.

I recently started using the API after some time away, and it took a bit to get reacquainted with some of its concepts. In my first few attempts, I ended up with either all logging statements output or none, when what I really wanted was output from only a few specific classes.

I think my problem stemmed from confusion between the various ways to filter output. In the end, I found it easiest to think of the API as two separate layers - a filtering layer that answers the question "What should be output?" and a handler layer that answers the question "How should it be output?"

Continue reading "Layers of Java Logging" »

| Comments (1) | Technorati Tags :

Posted on June 9, 2008 by Ben Sgro

Getting started with PDO_MSSQL

The Zend framework requires that if you want  your application to work on both Windows and Linux, and take advantage of Zend's ORM (DB_Table_Abstract) functionality, you have to install and use the PDO_MSSQL driver.
    
 

Continue reading "Getting started with PDO_MSSQL" »

| Comments (3) | Technorati Tags :

Posted on June 6, 2008 by Alex Melman

An Easy Way to Implement Namespaces in JavaScript

(Object-Oriented JavaScript Series)

Namespaces are a great way to uniquely distinguish objects from different projects. Unfortunately, JavaScript does not have native support for namespaces, but we can approximate it, by putting our objects inside other empty objects.

For example, to create a namespace called arc90.components, we would first define arc90 as an empty object:

arc90 = {}

If an object called arc90 already exists, we don't want to erase it; so we will check for it first, then create an empty object only if the arc90 object doesn't already exist. We can do that like so:

if (typeof(arc90) == "undefined")
        arc90 = {}

The type of operator returns the type of an object as a string. If the object does not exist at all, a value of "undefined" will be returned. This is what we are checking for:

Now that arc90 is defined as an object, we can go ahead and define the next level of the namespace, arc90.components. We basically repeat what did for the arc90 part of the namespace:

    if (typeof(arc90.components) == "undefined")
        arc90.components = {}

By now, you must be thinking, "Boy, we're repeating a lot of code here. There must be an easier way." Well, don't worry, there is. There are two options. You can use the YUI Library, which already contains a namespace function, or we can create a simple namespace function ourselves. Since I don't want my tip to consist of just a link to Yahoo!, I will do things the long way and show you how to create a namespace function.

The most important part of the function is the use of the eval operator. This lets you pass in JavaScript code as text, allowing you to dynamically create object names. This is important, because normally, object names must be hard-coded, which would prevent us from creating new objects dynamically, if not for the eval operator.

Now, we will create a function, which will create a namespace object out of the string you pass in. For example, calling:

createNamespace("arc90.components");

will create an object called arc90.components. It also returns the object that was created, so that you can create an alias. For example, calling the function this way:

var alias = createNamespace("arc90.components");

will create the namespace object and set alias to reference the same value. Now, if we were to define a new object called Checkbox within the namespace, we can either use the fully qualified name, like so:

arc90.components.Checkbox = function() {}

or we can use the alias:

alias.Checkbox = function() {}

You can use either the fully qualified namespace or the alias to reference the same objects. The only thing you must be aware of is that you cannot give your alias the same name as any part of the namespace. For example, if you have a namespace called arc90.components, you cannot name your alias arc90, or components. This will overwrite the object in the original namespace.

Now, let's create the createNamespace function:

   function createNamespace(ns)
    {
        // First split the namespace string separating each level of the namespace object.
        var splitNs = type.split(".");       
        // Define a string, which will hold the name of the object we are currently working with.  Initialize to the first part.
        var builtNs = splitNs[0];   

        for (i = 0, i < splitType.length; i++)
        {
            // Add the next part of the namespace only if we are at the second level or further.
            builtNs += (i > 0) ? ("." + splitType[i]) : "";
            // Check if the object we want to add exists, and add a new empty object if it doesnt.
            eval(builtNs + " = typeof(" + builtNs + ") =='undefined' ? {} : " + builtNs + "; ");
        }

        return eval(ns);    // Return the namespace as an object.
    }

The above code first splits the namespace string into parts, so that a namespace called arc90.components will be split into two strings, arc90, and components. The function then loops, adding the next string to the first as it goes. On the first iteration, we have only arc90, which will then be created as an object by the line:

eval(builtNs + " = typeof(" + builtNs + ") =='undefined' ? {} : " + builtNs + "; ");

This is essentially the same code we wrote at the beginning, rewritten using a one-line ternary operator, and wrapped in an eval statement. After the eval statement runs, the code generated would look like this (on the second iteration):

arc90.components = typeof(arc90.components) == 'undefined' ? {} : arc90.components;

So, there we have it; a function to create JavaScript namespaces. Enjoy.

| Comments (4) | Technorati Tags :

Posted on June 2, 2008 by Dave Hauenstein

A More Convenient Zend_Registry

The Zend_Registry is a pretty useful part of the MVC architecture of the Zend Framework. It’s a singleton class that keeps the developer from having to define global variables throughout their application. The downside is that retrieving the variables stored in the Zend_Registry can be tedious and annoying if you’re doing it often. Here’s an example:

$config = Zend_Registry::get('config');

Pretty verbose, huh? From that point on you can access the variables inside of config:

If($config->settings->environment == ‘development’) …

Wouldn’t it be much simpler if, whenever you needed to retrieve something from the Zend_Registry inside of your controllers, you could access them inline? For example:

$this->registry->config->settings->environment

In order to get this to work, you need to extend the Zend_Controller_Action class and overload the __get method. Here’s the code:

class Zarc_Controller_Action extends Zend_Controller_Action

{
   /**
    * overload __get in order to easily retrieve values from the Registry
    * and other sources. Throw an exception if the param could not be found.
    */
   public function __get($param)
   {
       if($param == 'registry' || $param == 'r')
       {
           return new Zarc_Registry();
       }
       else
       {
           throw new Exception("Could not find property {$param}");
       }
   }
}

All of your controller classes should now extend the new controller class you just created. For example:

Class IndexController extends Zarc_Controller_Action

Next, you need to write a class that searches the Zend_Registry for the property that is being requested.

/**
 * Applies an interface to the Zend_Registry that is cleaner and more
 * accessible than doing it the verbose Zend Framework way.
 */
class Zarc_Registry
{
   public function __get($param)
   {
       if(Zend_Registry::isRegistered($param))
       {
           return Zend_Registry::get($param);
       }
       else
       {
           throw new Zarc_Exception("Could not find property {$param}");
       }
   }
}

Then, save the two classes you created to your include path. Now, from your controller action methods you can access any variable stored in the Zend_Registry like this:

$this->registry->param
and this:
$this->r->param

This saves some time and makes your code much cleaner. You can also do this with sessions. Try it out, or ask us questions! If you need a deeper understanding leave us some comments and we’ll help you out.

| Comments (0) | Technorati Tags :

Posted on May 30, 2008 by Joel Potischman

try { go_fish(); } catch(JDOMException){}

In .NET, calling the selectSingleNode() method on XML documents returns a single node if the XPath expression finds a hit, and null if it doesn't.

So imagine my surprise when I found that JDOM in Java throws a JDOMException if no node was found! I think of exceptions as being exceptional events, so the designers of JDOM either disagree, or they think that not finding a node is a truly rare event. I'd argue that JDOM is wrong. Even strongly-typed XML documents can have optional elements, so throwing an exception when you don't find one is a serious escalation on a perfectly foreseeable outcome.

The Go Fish equivalent of selectSingleNode() either gets you the card you asked for, or your opponent squealing "Go Fish!". The JDOM version of Go Fish would instruct your opponent to either return a card or punch you in the face, and would instruct you to defend yourself from being knocked out in case your card wasn't found.

Hence, I wrote the following utility function to return a null result instead of an exception when we don't find our node:

public static Element selectSingleNodeSafe(Object xmlContext, String xPath) {
     try {
          return (Element) XPath.selectSingleNode(xmlContext, xPath);
     } catch (JDOMException e) {
          return null;
     }
}

| Comments (1) | Technorati Tags :

Posted on May 29, 2008 by Alex Gutierrez

Troubleshooting Presentation for IE6/7

I've had my share of issues with IE6/7. From my end, they mostly come in layout issues - not forgetting transparency for IE6.

Below is my two step approach when dealing with this monster:

  1. Make use of conditional statements for IE and create a separate css file. Lets name this file "ie_style.css"
  2. Use the underscore hack to address IE6 like so:

#myJucyTable {
	width: 100%; /* Hi IE7 */
	_width: 99%; /* Hi IE6 */
}

Note: Make sure to address IE7 first.


EXAMPLE:

Below we have mark-up for a two column layout. The left container(#left) has an inner two column layout(.col_container).

<div id="right">
	Navigation
</div>
<div id="left">
	<div class="col_container">
		<div class="left">
			Left Container
		</div>
		<div class="right">
			Right Container
		</div>
	</div>
</div>

Styled like so:

#right { width: 9em; float: right; }
#left { margin-right: 9em; }

.col_container div { border: 1px solid #000; }
.col_container:after { /* Used to clear the float */
    display: block;
    clear: both;
    content: " ";
}
.right { margin-left: 50%; }
.left {
	float: left;
	width: 50%;
}

Adding content to the layout and previewing on IE6/7 show the right inner container(.right) to not have the given 50%.

Add the property below to ie_style.css and presto.

.col_container { height: 1%; /* for both IEs */ }

Here is a preview of IE7:

An alternative way of laying out elements is with the position property.

Add this mark-up to our left container(#left)

<div id="user_account">
	<h2>Account Name</h2>
	<ul>
		<li><a href="#">Edit Account</a></li>
		<li><a href="#">Delete Account</a></li>
	</ul>
</div>

And style:

	#user_account { position: relative; }
	#user_account ul { margin: 0; position: absolute; top: 0; right: 0; }
	#user_account li { display: inline; }

Refreshing IE6 show the unordered list leaks to the right container(navigation)

To fix this, add the property below to ie_style.css and refresh browser.

#user_account { _height: 1%; /* Hello IE6 */}
		

Using "height: 1%" is my #1 tool when dealing with IE. What's yours?

| Comments (1) | Technorati Tags :

Posted on May 29, 2008 by Javier Julio

Centering an Application or Window In AIR

I've run into several AIR applications that don't center the main window on your desktop by default. This positioning is something I would prefer because I've had many AIR applications that have installed partially hidden under my OSX dock.

Originally, I came across a simple way of centering a window by doing the following on the applicationComplete event:

If you add the above block in your MXML component containing the WindowedApplication tag, you won't need to import anything for the centering to take place. However, you do need to apply it on the applicationComplete event, otherwise an error occurs on the last line.

Recently, though, I came across a sample in the Adobe Flex LiveDocs where a much shorter snippet performs the same desired functionality and works in all three events: initialize, creationComplete and applicationComplete.

| Comments (0) | Technorati Tags :

Posted on May 22, 2008 by Javier Julio

jQuery Docs: Bookmark It!

Recently, a fellow developer asked me for some help to see if there was an easier way to filter a collection of objects than just writing a long for loop with some logic. My instincts had us head straight to the jQuery documentation site, and we were not disappointed. Their jQuery docs are some of the best we'd seen. Nicely categorized, information on all properties, example code, and demos provided.

Sifting through the Array/Object operations section we came across the "grep" utility method. With the "grep" method, you can easily filter any array with a callback function that returns a boolean. Return true to keep the element and false to remove it. A simple solution to a simple, yet common, problem. This is all the developer really needed but he was probably over-thinking it.

The lesson? Well, to put it bluntly: Documentation is your best friend. I've always felt that, most of the time, a simple, built-in method (or set of methods) is all you need to solve a problem. Or at least the common ones I get asked about. Do yourself a favor, bookmark the docs, and don't be afraid to embrace it. Make it a habit. A good one.

| Comments (0) | Technorati Tags :

Posted on May 20, 2008 by Joel Potischman

But It Worked On Dev!

If you use SQL Server's CLR integration to write .NET stored procedures, you may one day deploy your working proc to another server, only to see it blow up with an error like the following:

Msg 6522, Level 16, State 1, Procedure prcMyCLRProc, Line 0
 A .NET Framework error occurred during execution of user-defined routine or aggregate "prcMyCLRProc":
 System.TypeInitializationException:
    The type initializer for 'System.Data.SqlClient.MetaType' threw an exception. --->
 System.TypeLoadException:
    Could not load type 'System.DateTimeOffset' from assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
 System.TypeLoadException:
    at System.Data.SqlClient.MetaType..cctor()
 System.TypeInitializationException:
    at StoredProcedures.prcMyCLRProc(String query)

You check permissions. You confirm CLR integration is enabled and configured properly. You even backup the database on the working box and restore it on the offending one, but no dice. The culprit? Both your servers have .NET Framework 2.0 installed, but only the working one has Service Pack 1, and you're using one of the new types or methods it introduced.

In our case, SP1 seems to have been corrupted by an extra-large batch of Windows updates, causing System.DateTimeOffset to cease to exist. Not that we're bitter.

| Comments (0) | Technorati Tags :

Posted on May 16, 2008 by Corey Maass

A jQuery Tip: Don't Use jQuery

Sometimes, there's too much of a good thing. jQuery fires its "$(document).ready()" as soon as the DOM is loaded, but what if that's too soon?

I recently ran into a problem when I was using a script that will resize an iframe, but the iframe hadn't loaded yet. So, after some debugging I realized that--for once--jQuery was not the answer. Resorting to the classic window.onload, which waits until everything is loaded, solved the problem.

The real solution here? Sometimes a Ferrari just won't replace the old pick-up truck.

| Comments (2) | Technorati Tags :

Posted on May 14, 2008 by Doug Burns

Unit Testing with JUnit 4 and Spring

I really like Java annotations for reducing XML configuration and simplifying code. Spring 2.5 introduced a new annotation-based unit test framework that further improved the great one it already provided. Using this, along with JUnit 4, you can create Spring unit tests without having to subclass anything.

An example unit test is shown below, along with an explanation of the annotations used.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/applicationContext.xml"})
public class ExampleTest
{
	ExampleObject objectUnderTest;
	
	@Test
	public void testSomethingTrue() {
		Assert.assertNotNull(objectUnderTest);
		Assert.assertTrue(objectUnderTest.getSomethingTrue());
	}
	
	@Test
	@Ignore
	public void testSomethingElse() {
		Assert.assertNotNull(objectUnderTest);
		Assert.assertTrue(objectUnderTest.getSomethingFalse());
	}

	@Autowired
	public void setObjectUnderTest(ExampleObject objectUnderTest)
	{
		this.objectUnderTest = objectUnderTest;
	}
}
  • @RunWith - JUnit annotation that specifies that the Spring class runner should be used for running the test.
  • @ContextConfiguration - Specifies the location of your Spring application context xml file(s). This gets inherited by subclasses, so you can use it in a base class to configure all of the tests in your application.
  • @Test - Indicates that the method should be run as a test. Note that although I used the pre JUnit 4 naming conventions (class names postfixed with "Test" and method names prefixed with "test"), this is not a requirement.
  • @Ignore - When this annotation is added, the associated test method will not be run. This is a great alternative to commenting out the methods which was required prior to JUnit 4. In this case, the test would fail if the @Ignore annotation wasn't used because objectUnderTest.getSomethingFalse() does not equal true.
  • @Autowired - Indicates that Spring should "wire" this dependency when initializing the test. In this case, a Spring bean named objectUnderTest will be provided.

| Comments (0) | Technorati Tags :

Posted on May 13, 2008 by Ben Sgro

Formatting Debug Output with print_r(

PHP's built in debugging functions, var_dump and print_r, are great for displaying a structured representation of a complex object or array and for viewing data printed to stdout. But what if you want to write that information to a log file?

There are a few decent recursive functions that iterate through the array or object. But there's really nothing quite like the format provided by print_r.

Many programmers don't realize that you can supply the print_r function with a second boolean argument. When set to TRUE (example below), debugging output will be not be rendered to stdout, which allows you to save it to a variable instead.


PHPCODE

   $complexDebug = print_r($_SERVER, TRUE);
   error_log($complexDebug);

END_PHPCODE

The previous code will take the print_r output of the SERVER array and save it as a string to the 'complexDebug' variable.The second line writes the string (preserving its format) to the error log file.

| Comments (0) | Technorati Tags :

Posted on May 9, 2008 by Javier Julio

Multiple File Extension Filters For CFDirectory

In a recent blog post by Ben Nadel (which should be his...oh, I don't know...56,423rd CF tip?!) he explained that by using the pipe character you can specify multiple file extension filters on the cfdirectory tag. For example, you can do the following:

That would return only Excel and CSV files. You can specify more filters by simply separating them with a pipe character. It seems like the Adobe Documentation team needs to update the ColdFusion Reference because it currently states the following for the filter attribute:

"File extension filter applied to returned names, for example, *.cfm. One filter can be applied."

Such a helpful tip really ought to be stated in the documentation or, even better yet, used as an example. So instead, I'll do all the work for you! Here is an example I wrote up matching the style used in the cfdirectory reference page:

| Comments (5) | Technorati Tags :

Posted on May 5, 2008 by Doug Burns

Java Quick Tip: Restlet & Spring Integration

Here at arc90 we use the Restlet framework for Java REST web services. Recently, we’ve also been considering Spring for dependency injection and AOP within these services. Restlet 1.0.x provides an extension for Spring integration, but I had a hard time finding an example of its use, so I thought I would post one here.

DemoApplication Class

package com.arc90.demo;

import ...

/**
 * Starts the Restlet application and defines its resources
 */
public class DemoApplication extends Application
{
	private static final String RESOURCE_MAP = "resourceMap";
	private static final int HTTP_PORT = 8182;
	
	public DemoApplication(Context context)
	{
		super(context);
	}

	/**
	 * Initialize the application when this class is executed.
	 * @param args
	 */
	public static void main(String[] args)
	{
		try
		{
			Component component = new Component();
			component.getServers().add(Protocol.HTTP, HTTP_PORT);
			DemoApplication application = new DemoApplication(component.getContext());
			component.getDefaultHost().attach(application);
			component.start();
		}
		catch (Exception e)
		{
			/*
			 * Convert any checked exceptions to unchecked for the purpose of this demo.
			 */
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Set up the spring-defined resources
	 */
	public Restlet createRoot()
	{
		Router router = new Router(getContext());
		
		/*
		 * Retrieve a map of available resources from spring and attach each to the router
		 */
		ApplicationContext context = 
			new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
		Map<String, Finder> resourceMap = (Map<String, Finder>) context.getBean(RESOURCE_MAP);
		for (String key : resourceMap.keySet())
		{
			router.attach(key, resourceMap.get(key));
		}
		
		return router;
	}
}

DemoResource Class

package com.arc90.demo;

import ...

/**
 * Handles all requests to the demo resource.
 */
public class DemoResource extends Resource
{
	@Override
	public void init(Context context, Request request, Response response)
	{
		super.init(context, request, response);
		getVariants().add(new Variant(MediaType.TEXT_PLAIN));
	}

	@Override
	public Representation getRepresentation(Variant variant)
	{		
		return new StringRepresentation("Restlet Spring Integration Demo", MediaType.TEXT_PLAIN);
	}
}

Spring applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
		
	<util:map id="resourceMap">
		<entry key="/demo">
			<bean id="configurationFinder" class="org.restlet.ext.spring.SpringFinder">
				<lookup-method name="createResource" bean="demoResource"/> 
			</bean>
		</entry>
	</util:map>
	
	<!-- Resources classes -->
	<bean name="demoResource"
		class="com.arc90.demo.DemoResource" scope="prototype" />
</beans>

This uses Restlet's built in HTTP server, so to access the demo resource, simply run DemoApplication, then point your browser to: http://localhost:8182/demo

As you can see, it takes a little non-Spring code to get Restlet up and running. However, the Resources themselves are Spring beans, so everything from the Resource level down can be wired by Spring.

Restlet version 1.1 (currently in testing) provides improved Spring integration where the entire Restlet framework can be configured in the Spring application context. I plan to post another quick tip demonstrating the 1.1 configuration soon.

| Comments (0) | Technorati Tags :

Posted on May 1, 2008 by Dave Hauenstein

Supporting Milliseconds Date Formatting in Strtotime()

Today I ran into an issue where the values being returned from datetime columns in my MSSQL database were unreadable by PHP's strtotime() function.

Here's what was happening: All the values were in this format: Aug 27 2007 12:00:00:000AM. This was problematic because PHP's strtotime() function cannot parse dates where milliseconds are separated from the seconds by a colon rather than a period (dot).

At first, I was concerned about why this was happening and, according to a bug report on php.net, it was due to the combination of FreeTDS + php5.2.3 + MSSQL and their formatting of columns cast as datetime. Although it's fixed in the trunk of PHP's repository, it hasn't made its way to a release. So, if you happen to run into this--here's a solution:

    strtotime(preg_replace("/:\d{3}([AP]M)$/", " $1", $timeStamp));

In this case, $timeStamp is equal to Aug 27 2007 12:00:00:000AM. So use preg_replace() to replace the milliseconds (:000) with a space and then puts the am/pm back at the end. Now strtotime() has a value that's readable.

That's it!

| Comments (0) | Technorati Tags :

Posted on April 24, 2008 by Ben Sgro

Gaining Insight into Your Zend Queries

Zend Framework is great. However, there is a limitation when using the database abstraction layer: You are unable to see the SQL query Zend is generating. Below is a patch that can be applied to the Pdo.php class. It will log all SQL queries to a file. It requires that your development directory structure includes a log/directory and a sql.log file, with the correct permissions. Of course, you can change this to fit your development environment.
-- Pdo.php.bak 2008-04-21 11:04:26.000000000 -0400
+++ Pdo.php     2008-04-21 13:35:54.000000000 -0400
@@ -227,6 +227,15 @@ class Zend_Db_Statement_Pdo extends Zend
   */
  public function _execute(array $params = null)
  {
+        /**
+         * This does not go into production code.
+         * To use:
+         *
+         * # touch sql.log
+         * # chmod 777 sql.log
+         */
+        file_put_contents("../log/sql.log", date("D M j G:i:s T Y") . ':' . $this->_stmt->queryString . "\n", FILE_APPEND);
+
      try {
          if ($params !== null) {
              return $this->_stmt->execute($params);

To install the patch, move to the Pdo.php directory and execute:

patch -p0 < PdoPatch.txt

Once the patch is installed, you can conveniently tail the sql.log file and watch each query.

# tail -f sql.log

It's not the most elegant hack, but it works fine for development. This is not recommended for production environments.

| Comments (3) | Technorati Tags :

Posted on April 21, 2008 by Matt Williams

Preventing Accidental File Deletion in Unix

Every seasoned command-line user has at least one horror story involving an accidental file deletion.

Unfortunately, experience won't prevent this from happening again as fingers will still occasionally outrun (or outmaneuver) the preoccupied brain.

One way to defend against this is to use the -i flag with potentially destructive commands such as cp or rm. Even if it were possible, however, to train yourself into this habit 100% of the time, that's 3 extra characters to type with every file manipulation command - not exactly efficient.

The best line of defense is to modify the .bashrc (or .bash_profile) file in your home directory to alias these commands.

alias rm="rm -i"
alias cp="cp -i"

Great, but...

...deleting a directory containing many files can become a huge annoyance, since the -i flag will prompt you about deleting each file. This is what the less popular -I (uppercase i) flag is for. Unfortunately, this isn't available with every implementation of rm (looking at you OS X!), but if your *nix supports the flag (man rm and look for the flag if you're unsure), you'll get a single prompt when you try to delete a directory using the -r flag asking if you want to recursively delete. If you prefer this (I do) and if your *nix allows it (Debian does), just modify the alias that you just created.

| Comments (0) | Technorati Tags :

Posted on April 21, 2008 by Javier Julio

Adding A ContextMenu To A Flex Tree

I've been working on an AIR application for managing SQLite databases where I've been using the Flex Tree component to list out all databases. I've been having a hard time finding good resources on working with a ContextMenu (right click menu) on a Tree component.

I tried my luck on adding a ContextMenu to the Tree component itself and managing it there. But that idea went sour because I couldn't find a way to get the current Tree item selected since right-clicking doesn't actually select it. After checking out what others have done, this wasn't getting any easier because I wasn't convinced by the solutions provided. They seemed more like hacks when I knew this should be pretty simple.

It never occurred to me to try adding the ContextMenu on a Tree ItemRenderer, so when I originally thought of it, I figured eureka, that's it! Ultimately, though, I didn't think it through that well since adding a renderer would also remove the folding arrows and folder/leaf icons. Ouch! Although now I know what was needed, I realized that adding a TreeItemRenderer is not the same as another List-based renderer such as one for a DataGrid or List component.

After following the solution on the Flex Cookbook, I dropped in that demo item renderer and was able to attach a ContextMenu object to it in the renderer constructor. So something like this:

public function DatabaseListRenderer()
{
super();

var contextMenu:ContextMenu = new ContextMenu();
var menuItems:Array = [];
var edit:ContextMenuItem = new ContextMenuItem("Edit Name");
edit.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, databases_menuItemSelectHandler);

menuItems.push(edit);

contextMenu.customItems = menuItems;
this.contextMenu = contextMenu;
}

private function databases_menuItemSelectHandler(event:ContextMenuEvent):void {
trace("menu item selected: " + data);
}

Now when I right-click on a particular item and select a menu option, the event handler fires and I see my trace message. Notice I dump out the data to see what's there (debugger is a better place for this) and I see the data for that specific Tree item as if it were selected. Problem solved!

| Comments (9) | Technorati Tags :

Posted on April 18, 2008 by Avi Flax

Patrick & Avi's Java Tips #2: Graceful JVM Shutdown in Eclipse

If your Java application has any Shutdown Hooks, you probably want them to run every single time you stop your app - even when it's running within Eclipse. Unfortunately, when you click the red "Terminate" button in Eclipse, it kills the JVM process abruptly; Shutdown Hooks don't have a chance to run.

<p>Here's my approach to this problem:

  1. Add an environment variable to your run configuration, in the Environment tab. I call it RUNNING_IN_ECLIPSE, I like to be super-explicit. Set its value to TRUE.
  2. Add this block to the bottom of main():
    /* a hack to make sure that our shutdown hooks get called from within eclipse */
    if (Boolean.parseBoolean(System.getenv("RUNNING_IN_ECLIPSE")) == true)
    {
           System.out.println("You're using Eclipse; click in this console and
    press ENTER to call System.exit() and run the shutdown routine.");
           System.in.read();
           System.exit(0);
    }
    

As the code says: from now on, any time you run your app using this run configuration, the console will listen for input, blocking. As soon as you click in the console to give it focus and press enter, the next line will call System.exit(0), which will tell the JVM to gracefully shut down, which includes calling your shutdown hook.

| Comments (0) | Technorati Tags :

Posted on April 15, 2008 by Joel Potischman

Parameterized XPath Expressions in .NET

Escaping parameters in an XPath expression in .NET is hard. Quick, which of the following is right?

Beats the hell out of me. Maybe one works, but I'm guessing not, and I'd assume a weird search term like Hello >:-< "How're you?" would blow me up. Fortunately, I found the wonderful Mvp.Xml .NET library, which will handle the tough work of escaping for me by letting me parameterize my XPath expressions, thereby protecting me from blowups and XPath injection attacks, like a search for '|@superuser='true. I can rewrite that search as follows:

How nice is that?

| Comments (0) | Technorati Tags :

Posted on April 9, 2008 by Javier Julio

JQuery Plugins: Callbacks and Now Triggers

Recently, I helped a developer with the JQuery TableSorter plugin where he needed to run some code whenever the TableSorter finished sorting. The plugin didn't provide any callbacks in its configuration which seemed odd, as this is normal practice with any JQuery plugin.

After digging through the plugin source code, I noticed it was using JQuery's "trigger" method which dispatched a built-in or custom event. From there, the solution was simple. When initializing theTableSorter plugin, we used the "bind" method to listen for any event bubbled up from within the plugin. In this case, we listened for the "SortEnd" event. An example can be seen below:

$("table.sortable")
	.tablesorter()
	.bind("sortEnd", function(){
		// fired when sorting has finished
	});

I had used the "trigger" method in an earlier project but never seen it used before with a JQuery plugin. We can expect to see two standards now on how to tap into a plugin event-- one using callbacks, and the other using events. If you run into a plugin that doesn't give the option to pass in a callback, be on the look out for a custom event trigger!

| Comments (0) | Technorati Tags :

Posted on April 5, 2008 by Javier Julio

ColdFusion 8.0.1 Released With New Features!



What's new you say? Well for starters we now have 64-bit support! AJAX libraries have been updated such as Ext to 1.1.1, Spry to 1.6 and YUI to 2.3. The <cftextarea> tag's rich text editor (using FCKEditor) now upgraded to 2.5. Not to mention some of the features that the CF team couldn't get into the initial release but we finally have.

1. Support for nested inline array and struct creation. You can now do the following:

<cfset myNestedArray = [ {version = "8.0.1"}, [1,2,3], [4,5,6], [7,8,9] ]>

2. Support for mixing attributeCollection and individual tag attributes with the latter replacing any occurrences in the former. So we can now do the following:

<cfquery attributeCollection="#queryProperties#" result="resultStatus">
...
</cfquery>

I definitely suggest checking out the release notes as the updater includes several bug fixes and a lot more specifics on what tags and other areas have been touched up. They also cover known issues with the updater that may affect you. A great release by the CF team with much appreciated features!

| Comments (0) | Technorati Tags :

Posted on April 4, 2008 by Javier Julio

Using ColdFusion Components (CFCs) in AIR Powered Flex Applications

Recently, I took one of my Flex/CF projects here at work to see how much effort and time it would take to deploy it on AIR without any of the desktop enhancements. I had no prior experience with AIR so I wasn’t sure what was involved.

The application uses the RemoteObject component in Flex to connect to CFCs to pass data and typed objects back and forth. Since it's deployed as a web application, Flex can figure out the “endpoint” automatically but since we are now on AIR, we need to provide that. An example if you were doing local development would be something like:

All I had to do was to add the "endpoint" property to all of my RemoteObject definitions. Since I used the PureMVC framework I had that nicely abstracted out as delegates within a business folder so it was even easier to find and get too. No other changes at all were required because my application now functioned on AIR as it would if it were in a browser.

| Comments (0) | Technorati Tags :

Posted on April 1, 2008 by Joel Potischman

Exception-Based Programming : A Primer

One of the hallmarks of modern programming languages is structured exception handling. Put simply, exception handling is a way for programs to handle "exceptions" to expected behavior. An error occurs, and it rockets up the call stack until code that knows what to do with it "catches" it. If it's left uncaught, the program shows a big ugly error message to the user and exits. This reduces cross-cutting concerns by allowing application logic to separate cleanly from exception-handling logic.

Continue reading "Exception-Based Programming : A Primer" »

| Comments (1) | Technorati Tags :

Posted on March 27, 2008 by Patrick Force

XML Design in SQL Server 2005

Utilizing the XML data type in SQL Server 2005 can be a good way of creating a more flexible data model. Design of a SQL Server 2005 DB, however, should not discount the use of standard SQL data-type columns and the power of pure relational data. During the design phase, carefully think about what data SHOULD be in XML by identifying areas where the structure of the data could change frequently and/or drastically. Also assess whether particular pieces of data need to be strictly relational (belong in a standard SQL type column), or if they could benefit from a more flexible relational structure such as hierarchical XML elements (XML data type). Think about data placement and if something is a pivotal piece of data for the related system, such as whether it will be searched on often, or even retrieved in searches that will return larger data sets--these types of data are better candidates for standard SQL type columns.

Overall, the basic rule of thumb that I like to follow: if there's little reason to maintain a piece of data in a more flexible structure or relational structure, then don't put it in an XML data type.

In our next tip, we will explore using schema in SQL Server 2005 to define your data in order to more effectively hide the relational/XML split.

| Comments (0) | Technorati Tags :

Posted on March 26, 2008 by Andy Lewisohn

Posting XML as a parameter to a SOAP WebService Method

SOAP is an XML-based communication protocol, but you can't actually pass XML to a SOAP method without a little bit of finessing. The reason for this is straightforward: XML is not a native data type like int, uint, string, etc., and SOAP can be implemented in a number of languages, none of which implement XML in the same way. The ActionScript solution to this problem is simple, but hackish. Wrap the XML document in a CDATA tag and pass the whole thing as a string:
var stringifiedXML:String = "<![CDATA[" + xml.toXMLString() + "]]>"
Now you can pass a stringified XML document to your SOAP service without worrying about special characters.

| Comments (0) | Technorati Tags :

Posted on March 25, 2008 by Matt Williams

Unix Directory Creation

One of the most common inefficient habits of Unix users is iterative directory creation:

$ mkdir project
$ cd project
$ mkdir docs
$ cd docs
$ mkdir html

You may (or may not) already be aware of the -p flag, which allows you to create parent AND child directories in one command:

$ mkdir -p project/docs/html

Not many people are aware, however, that you can create arbitrarily complex directory trees using the -p flag and some curly braces:

$ mkdir -p proj/{bin,etc,docs/{html,txt,pdf},src}

If the example above represented a common project layout, you could add a quick alias to .bashrc in your home directory:

alias mkproj="mkdir -p proj/{bin,etc,docs/{html,txt,pdf},src}"

| Comments (1) | Technorati Tags :

Posted on March 20, 2008 by Avi Flax

Avi's REST Tip #1: Resources First

When designing a RESTful web application, many of us will frequently jump right to representations--what types should be offered, how their content should be structured. This is particularly true when the primary representation type of an application is XML - often we'll have something in mind, we can almost see the XML document structure needed to accomplish the goal, so why not just start with that?

Because you've got to define what it is that your representation is representing before you define the representation. The reason is simple: your representations will be better, because while you're crafting them, you'll have in mind the thing that you're representing

This may seem kind of obvious, and the truth is, I think I agree. It is obvious - but only if you're designing this application on your own. Once you're designing an application with one or more other people, there's a very good chance that you don't all have exactly the same conception of your resources - and the best way to obviate that is to clear that up from the get-go. Start with your resources.

| Comments (0) | Technorati Tags :

Posted on March 19, 2008 by Javier Julio

Debugging Data Through the Console in ColdFusion 8

If you start the ColdFusion server by using the command line, you should note several of the enhancements made to the <cfdump> tag. One of them is a new attribute named "output" which can dump data to the browser (default), output to a file (set an absolute file path), or output to the server console. A simple example:

<cfdump var="#variables#" output="console">

I've been working on a Flex/ColdFusion project that makes remoting calls to CFCs. Debugging has become a breeze by simply setting the output attribute to "console" which then appropriately formats the data dumped to the console. Out of the many new features in CF8, this is the one I've used the most.

| Comments (0) | Technorati Tags :