Archive for May, 2008

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

Friday, May 30th, 2008

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;
}
}

Troubleshooting Presentation for IE6/7

Thursday, May 29th, 2008

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?

Centering an Application or Window In AIR

Thursday, May 29th, 2008

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:

var rect:Rectangle = new Rectangle();
var maxSize:Point = new Point(Capabilities.screenResolutionX, Capabilities.screenResolutionY);
rect.width = 700;
rect.height = 570;
rect.x = (maxSize.x - rect.width) / 2;
rect.y = (maxSize.y - rect.height) / 2;
stage.nativeWindow.bounds = rect;

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.

var screenBounds:Rectangle = Screen.mainScreen.bounds;
nativeWindow.x = (screenBounds.width - nativeWindow.width) / 2;
nativeWindow.y = (screenBounds.height - nativeWindow.height) / 2;

Keynote Suggestion: Add Diagramming Support

Thursday, May 22nd, 2008

Just submitted to Apple via their Keynote Feedback page:

I’m using Keynote all the time to display complex diagrams step by step. I find that by building the components in one by one I can walk people through a complex diagram much, much easier than if I make a static diagram in OmniGraffle, where I’d need to show the entire thing all at once. And then, after I’ve built in all the various components of the diagram, I can even use the awesome animation actions to move things around and change things, to explain a plan to people.

So, I’m frequently creating diagrams in Keynote. And it’s going well – it’s totally worth it. But there are a few things that Keynote could make easier for me. The #1 thing would be the ability to connect shapes using lines (usually with arrowheads). That way if I move a shape around, the connections to it would move with it.

Another feature which would be very helpful would be more alignment help. In OmniGraffle, when I drag a shape around, little lines will appear which help me know how the shape is aligning with other shapes. This is very useful for making diagrams which have an orderly feel to them.

Thanks for the great software!

Avi Flax

Thus continues my infatuation with Keynote.

jQuery Docs: Bookmark It!

Thursday, May 22nd, 2008

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.

But It Worked On Dev!

Tuesday, May 20th, 2008

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.

A jQuery Tip: Don't Use jQuery

Friday, May 16th, 2008

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.

Unit Testing with JUnit 4 and Spring

Wednesday, May 14th, 2008

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.

Formatting Debug Output with print_r()

Tuesday, May 13th, 2008

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.

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

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.

Multiple File Extension Filters For CFDirectory

Friday, May 9th, 2008

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:

   1. 

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:

  

  


  




The file look-up found #qUploads.recordCount# Word and Excel files in #uploadsDirectory#.