Archive | Programming RSS feed for this section

Regular Expression for dollar amount validation

I’m finishing up a small project that required validating dollar amounts on web-based form fields, and luckily I was using the wonderful Validation jQuery plugin.

Although this plugin doesn’t come with an out-of-the-box dollar validator method, it’s very easy to add your own. The trick was to find an appropriate regular expression. Although Google turned up several regex examples for validating dollar inputs, none met my exact criteria (the ultimate goal being to provide users with the greatest amount of data-entry leeway):

  • Allow the user to type in the $ (or not)
  • Allow amounts less than one dollar (i.e., 0 – .99)
  • Allow an optional one or two decimal places
  • No negative dollar amounts

So this is what I came up with, and it seems to be working. Two notes: (a) this expression allows inappropriate commas, but I’m stripping those out during the server-side validations, and (b) it is used in conjunction with the max() validator function to ensure the user doesn’t enter anything that could blow up a SQL Server money column:

^\$?[0-9][0-9\,]*(\.\d{1,2})?$|^\$?[\.]([\d][\d]?)$

The final jQUery validator method:

1
2
3
4
//custom validator for money fields
jQuery.validator.addMethod("money", function(value, element) {
	return this.optional(element) || /^\$?[0-9][0-9\,]*(\.\d{1,2})?$|^\$?[\.]([\d][\d]?)$/.test(value);
}, "Please provide a valid dollar amount (up to 2 decimal places)");

Comments { 3 }

Swiz framework for Flex

Swiz sample application

View the sample app code.

Some folks in Wharton Computing, namely Nathan and Adam, have had positive experiences using the Swiz framework for Flex applications.

I haven’t used Flex frameworks in the past because a) I was still learning Flex and wasn’t ready to throw a framework into the mix and b) the only real option was Cairngorm, which seemed like complete overkill.

Now that I’m more comfortable with Flex and understand some of its limitations, however, I can endorse Swiz.

Why do I like Swiz?  Because it doesn’t impose a strict structure and because it solves actual problems.  Even if you don’t care about separating your model from your views or abstracting service calls, Swiz is worth investigating for these reasons:

Event Handling: You can dispatch events at will and add the corresponding event listeners where required.  You don’t have to worry about the fact the Flex events bubble up and not down—Swiz just takes care of it.

Command Chains:  It’s often the case that Flex remote object calls need to occur in a particular sequence or that a series of remote object calls needs to complete before moving on to the next piece of code.  The logic required to ensure everything happens in the right order can get messy and only gets worse over time.  Swiz allows you to define a series of commands (called a CommandChain) and execute them together (sequentially or in parallel).

The Swiz Google code page and the Swiz Framework site have some instructions for getting started with Swiz.  The code samples are piecemeal and outdated, however, so I created a small project that demonstrates basic Swiz functions.  It’s a pretty silly app, but I created it so the Wharton Computing developer community could reference some well-commented code that works in our environment.

Because the back-end services are written in ColdFusion and it’s not especially practical to invest in CF hosting just to demo this, what you see here is just a screenshot* and the code.

Thanks to Nathan, who unknowingly provided some of the code for this sample app.

*Note the Phillies colors on the demo app. The default Flex theme is not meant for public viewing.  Ever.  It’s not hard to spiff up your apps a bit!

Comments are closed

SQL Server operand type clash!

Note:  This article was originally published to the Wharton Computing Developer Center.

Yesterday a fellow developer hit a strange SQL error and determined that the culprit was a T-SQL CASE statement used in his ORDER BY clause.

1
2
3
4
5
6
7
8
9
10
ORDER BY
CASE
WHEN UPPER(@orderBy)='GROUPMESSAGEID' THEN groupMessageID
WHEN UPPER(@orderBy)='GAMEID' THEN gameID
WHEN UPPER(@orderBy)='GROUPID' THEN groupID
WHEN UPPER(@orderBy)='MESSAGEID' THEN messageID
WHEN UPPER(@orderBy)='ROUNDSENT' THEN roundSent
WHEN UPPER(@orderBy)='SENTON' THEN sentOn
ELSE groupMessageID
END

This code results in the following message:
Operand type clash: uniqueidentifier is incompatible with datetime

After some digging around, we found the underlying cause of the error:  the case statement return values have different data types.  In some cases, returning different data types will behave as expected.  However, mixing numeric and character data causes problems.

In the statement above, gameId, groupID, roundSent, and groupMessageID are integers, sentOn is a datetime, and messageID is a uniqueidentifier.  Because the data type precedence pecking order in this case is datetime, int, and then uniqueidentifier, SQL choose datetime as the return type. Uniqueidentifiers cannot be converted to datetimes, hence the error message.

It all became clear after reading this article by George Mastros.  Thank you to George.

Comments are closed

Backtest the musical

In September of 2007, the Learning Lab rolled out Backtester,a Flex-based backtesting tool for use in investment classes.  I learned a lot about Flex and ActionScript while working on Backtester and am particularly proud of application’s wizard component, which allows users to design an investment strategy in 3 easy steps and test it against historical data.

We made a short screencast* for last spring’s faculty meeting and have been using it to test video tagging toys such as Viddler and Veotag. This post is just a test of Viddler’s new customizable player.

Comments are closed

ColdFusion: keep it girlie

Attention, female ColdFusion developers. I found the following information in some recent internet travels:

Silly CF Banner

I, for one, refuse to “upgrade” to a less girlie version of ColdFusion.  In fact, my pores are clogging at the mere thought.  Does anyone have a recipe for scones?

Girlie CF Banner

Comments are closed

HTTPService: passing XML between ColdFusion and Flex

We recently had some trouble with a Flex RemoteObject call. It kept throwing timeout errors on a method that invokes a CFHTTP call, even though we could invoke the same method from a ColdFusion page with no problems.

After increasing the timeout parameters of both the CFHTTP statement and the RemoteObject definition to ridiculous amounts, we decided to use the mx:HTTPService function as an alternative.  Kind of annoying to have to add the extra layer, but it works.

No doubt there is a perfectly logical explanation for the RO timeout, but we needed to get this proof of concept code working as quickly as possible.

The ColdFusion file.
This invokes the method that contains the problematic CFHTTP call and returns the status info in an XML blurb.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    <cfsetting showdebugoutput=”no” />
 
    <cfset structResult = StructNew() />
    <cfset structResult.backtestId = url.backtestId />
 
    <cffunction name=”RunBacktest” access=private” output=false” returntype=”struct” hint=”run a specified backtest”>
 
       <cfinvoke component=”TheProblemComponent” etc />do some stuff….
       <cfreturn structResult />
 
    </cffunction>
 
    <cfset result = RunBacktest() />
    <cfoutput>
    <cfxml variable="resultXML">
       <runResult>
          <backtestResult>
             <backtestId>#result.backtestId#</backtestId>
             <returnCode>#result.returnCode#</returnCode>
             <msg>#result.msg#</msg>
          </backtestResult>
       </runResult>
    </cfxml>
    </cfoutput>
 
    <cfcontent reset =”yes” type=”text/xml; charset=UTF-8>
 
    <cfoutput>#resultXML#</cfoutput>


The Flex HTTPService definition from Services.mxml:

1
2
3
4
5
6
7
8
<mx:HTTPService id=”runBacktest”
   method="GET"
   resultFormat="e4x"
   result="resultTesty(event);" >
   <mx:request xmlns="">
      <backtestId />
   </mx:request>
</mx:HTTPService>


The result handler
Example of how to reference the XML coming back from CF, even though we ended up not needing to do this.

1
2
3
4
5
6
private function resultTesty (event:ResultEvent):void
{
   var backtestRunResult:XML = new XML(event.currentTarget.lastResult);
   Alert.show(event.currentTarget.request.backtestId);
   do some stuff;
}


Invoking the service call:

1
2
3
4
5
6
private function runBacktest(backtestId:Number):void
{
   Application.application.srv.runBacktest.url = "SuperSecret/RunBacktestFolder/RunBacktest.cfm";
   Application.application.srv.runBacktest.request.backtestId = backtestId;
   Application.application.srv.runBacktest.send();
}

Comments are closed

Enhance the default Flex form validation

Note: this article was originally published to the Wharton Computing Developer Center.

Do you write or support Flex applications? Do you rely on the built-in functionality to validate form fields? Do your users get confused because the validation error messages don’t show up unless they use a mouse to hover over said form fields?

This post by Aral Balkan shows how you can get those “hovering” tool-tip error messages to display inline, as the user fills out the form: http://aralbalkan.com/1125

Comments are closed

Using Eclipse and Ant for Flex team development

Note: this article was originally published to the Wharton Computing Development Center.

Eclipse Ant Screenshot

Recently the Learning Lab has been discussing ways to do team development as we transition to Flex 2 and the Eclipse IDE. We’re starting a project now that will involve four developers, so we’ll need to keep our own working copies of the project. Not an earth-shattering idea, but it’s new for us–we usually share a single code base during development.

Ted, who has the most Eclipse experience in the group, suggested that Ant, a java-based build tool, could be used to make the team development process smoother. Because Ant ships with Eclipse and because Adobe recently released custom Flex Ant tasks, in theory it should be possible to create an Ant script that will mimic the default Flex build process and also perform extra tasks such as moving files around.

In practice, however, it’s not easy to create such a script if you’re new to Flex 2, Eclipse, and Ant because the documentation is scattered between all three products (as well as some blogs). So I munged the available information into a single “how to.” The steps below show how to implement a very basic Ant build script that will copy Flex code from the “master” code base to your working area, compile it, and create the swf html wrappers.

1. If you’re using the stand-alone version of Flex Builder, follow these directions to set up the Ant environment: http://www.peterelst.com/blog/2006/09/03/flex-builder-2-ant-support/. Skip this step if you’re using the plug-in version of Flex Builder.

2. Download the Flex Ant tasks from Adobe Labs and follow the installation instructions: http://labs.adobe.com/wiki/index.php/Flex_Ant_Tasks
Note: The instructions say to copy the flexTasks.jar file to “Ant’s lib directory.” I put my files in the locations below, which seems to work fine:

  • Stand-alone: C:Program FilesAdobeFlex Builder 2plugins
  • Eclipse plug-in: C:Program FilesEclipsepluginsorg.apache.ant_1.6.5lib

3. Open your Eclipse Flex project and add a build file to it. An Ant build file is an XML document that contains a series of tasks called “targets.” A sample build file template is attached.

4. Modify the build file template to work with your current project. The only things you should need to change are the properties (i.e., variables) at the top of the file:

  • FLEX_HOME: points to the location of your Flex SDK. By default this location is C:Program FilesAdobeFlex Builder 2Flex SDK 2 for the standalone version of Flex Builder and C:Program FilesAdobeFlex Builder 2 Plug-inFlex SDK 2 for the plug-in.
  • DEPLOY_DIR: the folder that will contain your Flex executables (i.e., the swf and its corresponding html wrappers)
  • MAIN_APP_ROOT: the location of the project’s “master” code base
  • WORKING_APP_ROOT: the location of your working folder

5. Open the Eclipse Ant window: Window–>Other Views (select Ant from the Show View window).

6. Once the Ant window is open in your Eclipse workspace, add your build file (see screenshot below):
a. In the upper-right hand corner of the Ant window, click the Add Buildfiles button (i.e., the button with the picture of an ant).
b. From the Buildfile Selection window, choose your build file and click OK.
c. You should now see your build file displayed in the Ant window. You can expand the individual tasks (i.e., targets).
d. You should be able to execute the individual tasks in the script by double-clicking them. Output will appear on the console.

This is as far as I’ve gotten. I’ve been using the built-in Flex compiler when working in my sandbox and the Ant script to get the latest code updates from the main project folder. It seems like a lot of work just to copy files around, but once the initial setup is complete it’s a handy way to avoid manually pushing updates from SourceSafe and potentially overwriting changes. No doubt there’s much cooler things you can do with Ant–if anyone has any tricks, please share!

Other resources:

  • Official Ant Manual, which includes a complete list of available Ant tasks: http://ant.apache.org/manual/index.html
  • Defining the Flex Ant Tasks within your Eclipse environments means that you won’t have to put the taskdef resource=flexTasks.tasks line at the beginning of the build scripts–Eclipse will just know how to find the tasks: http://www.flex2ant.org/
  • To set up Ant configurations and run the build tasks in a specified order, search for “Ant support” in the Eclipse documentation: http://help.eclipse.org/help32/index.jsp
Comments are closed

Re-usable Flex 2 Item Renderer

flex item renderer

Note: this article was originally published to the Wharton Computing Developer’s Center.

While working on a Flex 2 application, I needed to render the contents of several datagrid columns as currency. I knew how to create an mxml item renderer to do the job, but the code required hard-coding the name of the datagrid column (i.e., each column would require its own renderer).

Ben Forta’s blog has an entry about using ActionScript to create a reusable item renderer for this situation. Using his code sample and tweaking it based on a commenter’s suggestion, I created a reusable currency renderer in a few lines of ActionScript. The renderer can be attached to any datagrid column that requires currency formatting–no hard-coding required.

Also, as someone new to Flex, ActionScript, and object-oriented programming, I found the simple renderer example to be a good way to start understanding how Flex 2 customization works.

Click here for the sample renderer and source code view.

Comments are closed

SQL error-handling snafu

Note:  this article was originally published to the Wharton Computing Developer’s Center

Recently I encountered a SQL Server error-handling trap that caused a transaction not to roll back as expected. At the risk of sounding like an amateur, here’s what happened. The code was issuing two insert statements that were grouped into a single transaction:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
BEGIN TRANSACTION
 
INSERT INTO dbo.Table1 (SOME COLUMNS)
VALUES (SOME VALUES)
 
SELECT @error = @@error, @rowcount = @@rowcount
 
IF @error <> 0
BEGIN ROLLBACK TRANSACTION RAISERROR('error on the first insert!', 16, 1) RETURN END
 
[DO STUFF]
 
INSERT INTO dbo.Table2 (SOME COLUMNS)
VALUES (SOME VALUES)
 
SELECT @error = @@error, @rowcount = @@rowcount
 
IF @error <> 0
BEGIN ROLLBACK TRANSACTION RAISERROR('error on the second insert!', 16, 1) RETURN END
 
COMMIT TRANSACTION


The above error-handling works most of the time. However, if there is a run-time T-SQL error (for example, a missing object or a divide by 0 error), the offending statement fails but the rest of the transaction executes. In my case, the second insert failed because Table2 had been renamed. The subsequent @error check was never invoked, so the first insert wasn’t rolled back.

This behavior can be overridden by setting SET XACT_ABORT to ON, which specifies that the current transaction will automatically roll back in the event of a T-SQL run-time error.

External Link: (SET XACT_ABORT)

Comments are closed