Archive for the Category Development

 
 

Firefox add-ons I can’t live without

With the recent upgrade to Firefox 3, a couple of my add-ons were incompatible so I had to spend sometime waiting for a few of them to play catch-up. Despite the fact that alphas, betas, and release candidates had been out for months at a time, developers still failed to update their add-ons on time. That’s another issue entirely, so I digress. During the short period that I had to wait for a few of the add-ons to be updated, I ended discovering just how dependent on several of them I had become. As of now, here are some of the add-ons that I can’t live without.

Firebug
https://addons.mozilla.org/en-US/firefox/addon/1843

If I was ever in a situation where I had pick one and only one add-on to keep, this would be it. If you do any form of web application development, Firebug will be your new best friend - it provides DOM inspection, JavaScript debugging, the ability to change CSS on the fly, load-time analyzers, AJAX monitoring, etc, etc, etc. It’s hard to imaging building sites without it.

Web Developer Toolbar
https://addons.mozilla.org/en-US/firefox/addon/60

This is another extremely useful add-on if you’re developing web sites. Web Developer Toolbar provides you with the ability to disable cookies, completely strip out any-and-all CSS (inline, linked, or embedded), various form manipulation tools, toggling of images, outlining page elements, resizing the browser window, code validation, and so on. For anyone that is mindful of various screens, resolutions, and accessibility standards, Web Developer Toolbar helps immensely when attempting to meet then all.

ColorZilla
https://addons.mozilla.org/en-US/firefox/addon/271

This is possibly the simplest add-on I have installed. Essentially, ColorZilla provides an eyedropper tool that allows you to grab the color of any element on a web page. It will then allow you to copy that color’s RGB or hex values to your clipboard in a multitude of formats typically used in CSS or image editors. It’s great when you’re working with color themes or trying to match a similar color on an existing web site. In addition to the eye dropper feature, ColorZilla also provides the ability to zoom in on a page and measure the distances between elements.

Foxmarks
https://addons.mozilla.org/en-US/firefox/addon/2410

If you do a lot of work from within a web browser, you’ve likely accumulated a set of bookmarks that you visit daily. If you’ve got multiple machines, then you’re apt to want those bookmarks replicated across your machines. Since Google Browser Sync is now defunct, I’ve ended up going with Foxmarks. Similarly to Google Browser Sync, Foxmarks allows you to securely synchronize your bookmarks across all instances of Firefox permitting the local copy has Foxmarks installed.

There are more add-ons I use, but these are the ones that I can’t live without. I’m sure I’ll eventually have a few new ones to add to the mix over time, so I may end up doing a follow-up post. Do you have any add-ons that you can’t live without? If so, let me know - I’d hate to be missing out on something.

Managing Internet Explorer, JavaScript, and client and offset values returning zero

I’ve been working on building a custom modal control for someone else that will ideally be used in a variety of places throughout their site. Essentially, the control will allow a developer to create a dialog and style it how s/he would want it to appear, and then pass it to my code. My code will then process it, bundle it up with a semi-transparent background, and then overlay their dialog centered above all of the other elements on the page.

For the most part, it was going well - the control was performing the exact same way across all of the major browsers, and it was easy to plug existing code into it; however, while testing it on a variety of pages, I came across a bug that ended up plaguing me for much longer than it should have. There’s a function in the JavaScript that uses each element’s offsetWidth and offsetHeight values to center that element in the middle of browser window regardless of its size. Oddly enough, on one of the pages that I was testing, I was noticing that Internet Explorer was not properly centering the element. Upon further investigation, I noticed that the element’s offsetWidth, offsetHeight, clientWidth, and clientHeight values were all being returned as zero.

Naturally, I ended up googling around for a solution to the problem. I didn’t come up with much, but I did find this page on MSDN which ended up giving some insight - the page contained tables and they were the culprit for this behavior. Although this helped me pinpoint this problem, it didn’t help revealing a solution. Additionally, Firefox, Safari, and Opera all displayed it correctly regardless of if tables were present on the page or not. So, I resolved to spending some time understanding how tables caused this problem in hopes of coming up with a way to manage it. Ultimately, I came up with a solution and thought I’d share it here. Before diving into code, I thought I’d explain how it works.

About document.readyState

Internet Explorer implements a property on the document object called readyState. Technically, it’s present for the sake of the XmlHttp object, but it can used to determine the state of the current document (which is useful, as you’ll read shortly). There are five different ready states:

  1. Uninitialized
  2. Loading
  3. Loaded
  4. Interactive
  5. Complete

The important thing to take away from this is that IE will not have the offsetWidth/offsetHeight/clientWidth/clientHeight values calculated until state five, but the JavaScript function was processing the element in step four.

Capitalizing on document.readyState with IE

My fix capitalizes on document.readyState. Because Firefox, Safari, and Opera all returned ‘undefined’ for this property, it meant I didn’t have to re-write a lot of the existing functionality - I just needed to incorporate a single case for managing IE’s behaviors. Assume that this.bIsE is a flag set earlier in the code determining whether or not I’m using IE. Also assume that _InitializeComponents() contains logic responsible for getting some of the page’s elements ready. Here’s what I did:

if(this.bIsIE && document.readyState != ‘complete’) {

var self = this;
self.onLoadHandler = window.setInterval(function() {

if(document.readyState == ‘complete’) {

self._InitializeComponents();
window.clearInterval(self.onLoadHandler);

}

}, 100);
} else {

self._InitializeComponents();

}

Basically, the way this works is that is that if it’s not IE, initialize the components and proceed; otherwise, if IE is the current browser and it’s not in the ready state, then fire the readyState check every 100ms. If the document eventually reaches the ready state, then initialize the components and stop the interval function. Overall, it’s not perfect, but it works and it accomplished what I needed.

Organizing Knowledge Generated in Software Development

For anyone that’s ever been responsible for working a website or software application that someone else has created, or for anyone that frequently works on developing a large piece of software, you’re likely to touch various pieces of code in that application. We’ve all got our own style of writing code, but given any major piece of software, there are going to be standard ways for creating certain types of objects.

For example, given any distributed web application, there is likely to be several ways to get information from the front end to the back end and have it replicated across all of the databases. For any desktop application, there are ways to correctly generate objects at runtime that will do exactly what you need them to do as opposed to creating giant objects are design time to cover every major scenario for your situation.

Obviously, and as with most things in programming, there are n-different ways to accomplish any given task; however, I firmly believe that well-designed software and good software engineering practices setup standard ways (or even frameworks) that are conducive to providing a correct way of accomplishing a task versus a way that works.

Ultimately, the longer you spend working on any large piece of software, the more likely you are to touch a wide breadth of areas in the code base. Additionally, you’re likely to hit varying degrees of depth in that code, as well. For every step across the code that you take and for every level deep in the code that you go, you may find yourself in a situation where you need to create a new object or refactor some existing code. Assuming that there is a standard way for creating to objects, integrating new features, or whatever else you may be doing, you’re going to be gaining experience with this area of the code. With that experience, you’re likely to be expected to be able to do something similar in the future.

What happens, though, in three months down the line when you’re neck deep in front-end development and you’ve just been asked to dive down into the application layer to develop some new code that will be responsible for translating information passed down from the front end and process it in some way before sending it over to the back end system? For some, no big deal - they’re gifted in that way. For others, they are likely to copy/paste from some similar code, patch it up, and release it. Copy/Paste is a terrible idea and, in my opinion, should never be done in almost any situation. Others may refer to some old notebook that they keep filed away from previous projects. Whatever works best for you is what you should do (except for Copy/Paste!).

Personally, I’ve been running a wiki on my local development box in which I keep all notes relative to nuances for various languages, framework notes, development techniques, and general reference notes that I come up with while working on aspect of a project. I’m a fan of doing this not only because it’s really easy to keep a web browser open on one monitor keeping notes based on code that’s open in an IDE on another monitor, but because it’s easier to organize than a notebook. Using links and a search engine beats bookmarks and skimming pages for me any day.

I like doing this because it prevents my file cabinet from getting too filled with stacks of notebooks, but it also rids me of the uncertainty of Is this the right way to do this? I can’t remember away and replaces it with Is this is the right way to do this? Let me check what I’ve done before. Generating knowledge in any given situation is always great, but it’s only as good as your ability to reuse it in the future. Keeping that information organized and easily accessible helps.

Just in case you’re wondering, I’ve been using Instiki and it has served me well. I’m not saying it’s the best or anything, but if you’re looking for something that is easy to setup and with which it is easier to interact, then I recommend it. Do you keep notes on various projects that you work on? What utilities do you use to help out with that?

Addressing Prototype, setStyle, Internet Explorer, “Object doesn’t support …”

While working on the latest version of Slideshow, I was working on a feature that involved dynamically creating an element, creating a text node, and ultimately setting styles on the new element. Unfortunately, IE6 and IE7 kept throwing the error “Object doesn’t support this property or method”. When searching for the bug, I had narrowed it down to the function responsible for setting the styles of this newly generated element. Initially, my code looked something like this:

this.Message = document.createElement(’div’);
var msg = document.createTextNode(’[message goes here]‘);
this.Message.appendChild(msg);
this.Message.setStyle({

// styles

});

I traced the problem to the line where the styles were being set (this.Message.setStyle). The fix is pretty simple - rather than saying:

this.Message = document.createElement(’div’);

I needed to do this instead:

this.Message = $(document.createElement(’div’));

From what I can tell (and I could be way off), IE manages the DOM a bit differently than Opera, Safari, and Firefox and, although Prototype seeks to grab the element using the $() function in the code, you must explicitly use $() when creating your node.

PHP & IIS: Addressing “Fatal error: Call to undefined function mysql_connect()”

I’ve been working on a project that is hosted in a Windows environment, but requires PHP and MySQL. My development and test environments are using the LAMP stack with which I’ve never had any trouble getting the two modules to play nicely. Going into the project, I knew that it was a little more of a headache to setup PHP and MySQL with an IIS webserver, but I also knew it could be done. I installed PHP and MySQL and also made the appropriate changes to the PHP.ini file. Unfortunately, PHP was still not able to interface with the database and I received this error:

Fatal error: Call to undefined function mysql_connect()

If you’ve suffered from this problem, here are a couple of things to check in a roughly appropriate order.

  • Make sure that you have the correct parameters in your PHP code. Often times in development, you’ll be connecting to a development database or a test database and forget to modify the script when you push to production.
  • Verify that php_mysql.dll is located in your PHP installation directory and that you uncomment the line in PHP.ini that contains extension=php_mysql.dll.
  • Lastly, make sure that you’ve setup your Environmental Variables in Windows. To do this, Start | Settings | Control Panel | System. Click on the ‘Advanced’ tab, then click the ‘Environmental Variables’ button. In the ‘System Variables’ frame, click on ‘New’ and then give the variable name ‘PHPRC’ and give the value to the root directory of your PHP installation (such as C:\PHP). Restart the machine (not just the webserver).

I failed to perform Step 3 in my initial configuration; however, after I restarted the server everything worked exactly as it should. If you’ve experienced this error, and none of the above help to address the problem, leave me comment - I’m interested to see any other erratic behavior that may occur in an IIS/PHP/MySQL environment.

Edit: May 22, 2008
Matt left a comment about a MySQL function freezing his machine that was running IIS6. Despite a few initial thoughts, I really wasn’t sure what had happened. After a short email exchange, he let me know what the problem was and how to fix it, so I’m including his response as another tip for this post:

  • “It turns out that the IIS installer (.msi version) doesn’t put the proper PHP path in the mime type. It comes out reading like c:\php\PHP5~.dll which fails to run. I had to change it to the proper path c:\php\php5isapi.dll without the Windows truncation.

    As for the corruption, I have no idea what happened. I had to re-install PHP5 and configure php.ini all over again to get my sites back up.”

Disabling Tab with JavaScript

Occasionally when building web applications, the need arises to stop event propagation and/or event bubbling (for more information, check out this page).

I’ve been working on a control that sits above all of the other elements of the page and must maintain focus of the mouse and keyboard while it is being displayed. In order to do this, I needed to prevent the default behavior of the Tab key whenever this control was visible on the screen. Without going into too many details, I’ll just add that I’m needing to override this behavior in order to make sure the user interacts with the control and cannot bypass it - ultimately, it’s a security measure and it’s for their own good.

Before continuing, I’d like to add that I’m not really a fan of overriding behavior like this. From a usability standpoint, it contradicts what the user thinks will happen when they perform an action versus what will happen. As such, it breaks their conceptual model of how they believe the thing work. Knowing that I’m doing all of this makes me feel lame. Regardless, it’s for their own good. The ends justify the means.

With that said, the major browsers name their event object differently, so you need to get a reference to that object before capturing the event. Next, we only want to stop the default behavior based on the Tab key (which has the keycode of 9). Here’s how to do it such that it works in IE, Safari, and Firefox:

document.onkeydown = DisableTab;
function DisableTab(evt) {

var evt = (evt) ? evt : ((event) ? event : null);
if(evt.keycode == 9) {

return false;

}

}

Again, this is one of those solutions that I’m not really a fan of, but is needed. Many of the alternatives that I found when looking around didn’t work correctly across the major browsers so I ended up doing it this way and it worked.

IE’s KB927917 Error

I’m currently working on a web application and am trying to take advantage of the ASP.NET AJAX framework (which I think is kinda weak is comparison to some other frameworks, but I digress).

I was attempting to use the modal pop-up control, but the framework is apparently manipulating a node in the DOM before it has been closed. If you check out Microsoft’s support page, you’ll notice that they don’t have any real solutions - only workarounds. Lame.

Unfortunately, none of these workarounds are feasible given the current environment in which I’m working so I’m having to essentially create my own modal pop-up. If you’ve got experience with this issue and have come up with a solution (versus a work-around), please leave a comment.

Edit June 5, 2008: Commenter tbela99 suggested verifying that all of your existing XHTML is well-formed (with no closing tags). This is always a step that should be done prior to releasing; however, it’s a difficult thing to do whenever you’re adding functionality to a project that has already been released. tbela99 made a couple of additional suggestions that are more JavaScript oriented, as well - check out the comments.

Testing 1, 2, 3…

Recently, I’ve been working on a project that will ultimately require new users of the system to create their accounts with stronger passwords than the application has typically allowed. Existing users will be required to update their accounts with stricter passwords. The software is a distributed web application, and the code that I am working is a the application layer.

I’ve used a couple of design patterns to essentially build a framework that allows us to setup a password object and add and remove policies to it at runtime via XML flags. Policies are nothing more than rules that will evaluate the password against a single requirement, such as its length or whether or not it contains a specified number of digits and/or symbols. For every policy that the password is evaluated against, the framework will generate a set of error messages as well as a password strength rating and will return them once the rating process has completed.

Ultimately, this will all be bound to the front-end when the overall project is completed; however, for now, there’s no UI against which to test the framework’s performance. Since testing is arguably one of the most important phases of software development and since there’s no true UI to provide any level of feedback from this framework, I chose to take a true test-driven development approach to the password and its policies.

Write Test Cases First
Because we designed the software upfront, we new how the system should behave before we actually began building it. This made it relatively easy to write test cases first - we new what our inputs were going to be and we new exactly what outputs to expect for each case. After writing these cases, I found myself to be more conscientious of the code I was writing for the actual system.

Although it’s wrong, it’s not uncommon for developers to first build their application and then right the test cases (numerous articles are available online about this). This is incorrect for a number reasons primarily because you’re basically writing tests for a system you’ve already built - in the same way that writing code after the test cases made me more aware of what I was writing, writing your test cases after building the components will likely result in writing cases that fit the existing system. This completely misses the mark on the purpose of Test Driven Development. Writing test cases to fit the software is backwards - write your software to fit your test cases.

How long did it take?
This took a little bit longer to do for several reasons. First off, writing a test suite to cover branches, statements, outputs, etc. of your system adds to the amount of time to complete the project (or phase of the project). Couple that with updating various components and then developing new test cases for those changes, you’ve got a pretty full plate of things to maintain. Ultimately, it may result in a slightly longer period of time to complete, but if this is taken to account in project planning it shouldn’t be that big of a deal. Additionally, you’re only increasing the quality of the software, so I’d argue that it’s worth it more often than not.

Combinations and Permutations of Policies
This was the fun part. Initially, we started off with a small set of policies; however, as the project matured and we gathered more input, we had to create additional policies. This resulting in us testing possible error messages as well as the various strength ratings for each arrangement of the policies. It’s really not that big of a deal if you’ve got a couple of people working on the project, but it’s easy to see how fast something can increase in complexity by simply introducing one or two more components.

Overall Impressions

Building this framework using Test-Driven Development was great. It prevented the project and it’s various combinations of outputs from getting away from us very early in development. It also resulted in a great feedback of a system that doesn’t have an interface with which to interact. Finally, it generated a strong sense of software quality once the system was developed and all of the test cases passed.

Maybe I’ll revisit this project to show off the interface once we’ve finished it, but that’s not really something I’m planning to focus on showcasing. We’ll see.

That’s it for now,
Tom

Using local variables with JavaScript’s replace() function

Recently, I’ve been working on some client-side code for a web application that needed to encode some data prior to invoking an AJAX request, and then needed to decode the response data upon receiving a successful response; however, I discovered a nuance in JavaScript’s replace() function that required a little bit of extra work to get it operator with the degree of flexibility that I wanted.

Because ampersands are usually used to delimit query string parameters, the server wasn’t handling the submitted data correctly. To mitigate this issue, the ampersand character needed to be encoded. We stored the encoded representation of the ampersand in a local variable [creatively] called _ampersand.Next, we wrote a function that takes in the data to be sent across the wire, encodes the characters, and does some additional processing, before returning the encoded data:

function encodedData(strInput) {

return strInput.replace(/&/g, _ampersand);

}

It worked fine; however, the replace() function proved to require a little additional work for it to decode the data correctly. Since we needed to do a global replacement of the ampersand token, we were using the g operator, but inserting a variable into the replace() function does not work. Actions speak louder than works, so here’s what I mean:

// this does not work…
function restoreAmpersands(strInput) {

return strInput.replace(”/” + _ampersand + “/g”, “&”);

}

At first, it seems as if it work work fine - concatenate /’s on the value stored in _ampersand and then let JavaScript get to it. Unfortunately, this isn’t how it works. One solution would be to simply hardcode the value of the _ampersand variable into the replace() function, but that’s poor coding. The solution I ended up using is actually extremely simple and it makes perfect sense.

Because replace() requires a regular expression to work its magic, giving it a concatenated string literal will not work. Instead, I ended up first creating a regular expression that includes the _ampersand variable and the global operator, then I passed it into the replace() function. Have a look:

var sRegExInput = new RegExp(_ampersand, “g”);
return strInput.replace(sRegExInput, “&”);

Extremely simple solution to a problem that, in my opinion, shouldn’t have been much of an issue at all. Oh well, at least I know that I wasn’t alone.

Issues with Opera, Prototype, and dom:loaded

I’ve been working on a small JavaScript library that is built using Prototype, and discovered a small quirk that caused Opera and Safari to respond differently than IE and Firefox when using the dom:loaded event with the document.observe function.

According to the Prototype documentation dom:loaded will “fire immediately after the HTML document is fully loaded, but before images on the page are fully loaded.” My script manipulates a set of images that are on the page, and I needed to process each image before the page loaded. If I waited until the document had fully loaded, then a flicker would occur in a couple of browsers. Unfortunately, it wasn’t happening in every browser so this made it difficult to diagnose.

Initially, my approach was to first intercept the images, hide them (save for the first image), and instantiate my object all before the DOM had finished actually loading the images. This is basically what I was doing:

document.observe(’dom:loaded’, function() {

// error checking, reading images into an array here
images.each(function(i) {

if(i != images.first()) {

i.hide();

}

});

// apply some specific margin styles here

});

The end result worked well - it behaved exactly as I had anticipated across IE6, IE7, Safari, Opera, and Firefox but the problem didn’t occur until I uploaded everything to a web server and began running tests across these same browsers. That’s when I found an ugly bug: Opera appeared to be completely ignoring all of the initial processing. Safari occasionally demonstrated the same exact error, but it was inconsistent - sometimes it worked, sometimes it didn’t.

Rather than try to hack the code to get it to bend just enough for Opera, I wanted to investigate it and figure out exactly what was going wrong. Sadly, Opera doesn’t have a nice DOM debugging console (at least not that I found), so I had to resort to creating some test cases to pinpoint the issue.

First, the reason that the error didn’t show its face until the script was running on a web server is because the images were stored locally so there was close to no time required for the images to load - on a web server, that’s obviously different.

Secondly, regarding the script, I’m not 100% positive that this is the problem, but it’s as close as I could come based on the results of my tests. What I found is this:

Earlier, I mentioned that the dom:loaded event is triggered prior to when the images are loaded, right? Well, I was initially trying to access the image.height property during this processing. Whereas the other browsers were already parsing each image’s properties, Opera was not. From what I gather, the other browsers are loading up the properties of each image prior to actually displaying them, and Opera is delaying all of this until the dom:loaded event has completed. Basically, this makes it impossible to process any of the images until they are visible on the screen.

After discovering this, I made some changes to the code. I was somewhat reluctant to do this at first because I didn’t wanna sacrifice some of the slight performance issues that would come as a result of the fix; however, the cost of flexibility outweighs the minimal performance decrease, in my opinion. Here’s what I did:

document.observe(’dom:loaded’, function() {

// error checking, reading images into an array here
images.each(function(i) {

if(i != images.first()) {

i.hide();

}

});

});
Event.observe(window, ‘load’, function(evt) {

// apply some specific styles to the images here

});

Ultimately, this still allows me to hide all of the images prior to them being displayed so none of the actual visuals are affected, but I delay the image processing until the images are actually loaded by the browser. This proved to completely fix the bug in Opera and also stopped the inconsistency issues in Safari.

As I mentioned before, I’m not 100% positive that the results of my testing are correct, but it seems to be close based on the results. Additionally, this fix ended up addressing the cross-browser quirks so I’m content with the solution. If any of you are familiar with the issue that I was having, or have had any similar experience, leave me a comment.

Later, I’ll go more in depth on this library that I’ve been working on, but I’m not quite done with it so there may be more issues to discus.

Until then,
Tom