Archive for the ‘Quick Tips’ Category

Getting started with PDO_MSSQL

Monday, June 9th, 2008

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.

You can first try to install via PECL (however this didn’t work in our case):

bens@arc90-dev-02:~/PDO_DBLIB-1.0$ sudo pecl install PDO_DBLIB
pear/PDO_DBLIB requires PHP extension “pdo” (version >= 1.0)
No valid packages found
install failed

bens@arc90-dev-02:~/PDO_DBLIB-1.0$ sudo pecl install PDO
Skipping package “pecl/PDO”, already installed as version 1.0.3
No valid packages found
install failed

Instead, download the source and use phpize (which prepares the extension compiling) in the root directory of PDO:

bens@arc90-dev-02:~/PDO_DBLIB-1.0$ phpize
Configuring for:
PHP Api Version:         20041225
Zend Module Api No:      20060613
Zend Extension Api No:   220060519

Then execute the configure script to build the pdo module.

bens@arc90-dev-02:~/PDO_DBLIB-1.0$ sudo ./configure 
checking for grep that handles long lines and -e… /bin/grep
checking for egrep… /bin/grep -E
checking for a sed that does not truncate output… /bin/sed
…[removed for brevity]….
———————————————————————-
Libraries have been installed in:
   /home/bens/PDO_DBLIB-1.0/modules

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR’
flag during linking and do at least one of the following:
   – add LIBDIR to the `LD_LIBRARY_PATH’ environment variable
     during execution
   – add LIBDIR to the `LD_RUN_PATH’ environment variable
     during linking
   – use the `-Wl,–rpath -Wl,LIBDIR’ linker flag
   – have your system administrator add LIBDIR to `/etc/ld.so.conf’

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.

———————————————————————-

If all went successful, you should see a similar message. Now, copy the module (pdo_dblib.so) from the build directory to your php directory:

bens@arc90-dev-02:~/PDO_DBLIB-1.0/modules$ sudo cp pdo_dblib.so /usr/lib/php5/20060613+lfs/
Then, copy the pdf_dblib.so to /usr/lib/php5/20060613+lfs/

Make a backup of your php.ini file and add the following to the php.ini file:

extension=pdo_dblib.so

Restart apache add the following to your config.ini in the Zend project you would like to use the PDO driver (on Linux):

database.adapter          = “pdo_mssql”
database.pdoType        = “dblib”

PDO should be setup and working. Enjoy.

An Easy Way to Implement Namespaces in JavaScript

Friday, June 6th, 2008

(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  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.

A More Convenient Zend_Registry

Monday, June 2nd, 2008

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.

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;

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.