Wednesday, November 24, 2010

Adobe can have my lunch money

In response to an article thecrumb (Jim Priest) (read the article here) , I posted the following comment (awaiting moderation when I published this):
I used (and occasionally still use) cf eclipse, and have always been very happy with it. However, I honestly don’t agree that Adobe is in the wrong here to put out a whitepaper. They spent a considerable amount of time and money building a new IDE (cmon, Dreamweaver and Homesite+ had their day for CF devs, and even cf eclipse was created to fill the void). CF Builder really provides functionality that is drawing new users to CF. Adobe honestly couldn’t stay out of the market due to the fact that an OSS project existed. They saw the need, filled the need, and IIRC, conferred with certain members of the cf eclipse team. A standalone version was necessary to cater to a specific demographic in the community, as well as hooks to new cf9 features.
As ColdFusion continues to progress over the next few iterations, the IDE will be able to stay in lockstep since Adobe can perform parallel development to keep them in sync.While Adam’s post does read a little negative against cf eclipse, I think the point that should be made is that there are a few options out there, make sure you understand what they are, and that cfB is not a clone of cfE as is the common misconception.
All that being said, I am sure the community will continue to support cf eclipse, and I personally thank each and every member of the cf eclipse team for their dedication.
As an aside, I didn’t hear anything in your article that speaks to the future of cf eclipse, or the direction the project is moving. Perhaps you could bolster support by publishing your product roadmap (forgive me if it exists and I just haven’t seen it) so we could weigh options and the community could contribute if there was reason to do so.
I've ways seen cf eclipse as an awesome IDE, but with all open source projects supporting a commercial project, they always seem to be chasing their tail. Personally, I have no issue paying Adobe to ensure my ColdFusion IDE is up to date with the language, as well as is assured continuing development and improvement.  I'd like to add that the cf eclipse team has done a great job of supporting the CF community over the last few years, and I suspect they will continue.

So was Adobe wrong to put out the whitepaper comparing features?  I'd like to hear what you have to say.

Monday, November 22, 2010

Help me pick my Blackberry Playbook App

I'm vacillating around 3 application for Playbook development and just can't decide which I should focus on.  I've started developing all three (or have developed them in Flex already for demos). Would you use any of these three apps:

1. Twitter app that shows your network by value.  Ratings are given based on 10 or so indicators to help you trim who you follow, as well as find your most valuable followers.  Using this app you can also explore your network and their networks network ;)

2. Another Twitter application, but this one lets you find out what the buzz is about.  Enter some keywords, and see whats happening on Twitter around those keywords (also bound by location if you want, i.e. what are people saying right now in San Francisco).  The result is two fold.  First, a tag cloud of trending is drawn and allows you to drill deeper.  Second, you can select a few people and map their networks, overlap, etc.  this was originally developed to allow tracking persons of interest via Twitter, flag their account, link their accounts to other social networks (i.e. YouTube and Facebook) and learn about how messages travel around social circles.

3. The last application is for the open government initiative.  I think this one has legs as well and follows a social visualization pattern to allow the user to select data from data.gov and filter the data into a set.  The user is then presented with a few chart/graph options that make sense for the present set (i.e. if they have geodata, allow them to create a heatmap).  They can then style and annotate the chart/graph and export to an image or PDF for dissemination to their email or social network.

I'm interested in hearing your thoughts so I can clear my programming ADHD and focus on a single path.  Thanks!

Sunday, November 21, 2010

Blackberry Playbook Application Development - Get a Free Tablet!

Over the next few weeks I'll be posting tips and tidbits about Blackberry Playbook application development.  I'm pretty excited about Blackberry Playbook for a number of reasons.  First, it has Flash, as any tablet should have.  Not only does it support Flash, but really Adobe AIR is wired into the OS.  This opens up crazy possibilities.  Also, the Playbook offers true multitasking.  For me, whats most exciting is that its a "Blackberry".  While iPad is honestly a security quagmire, especially when running within a government environment, Blackberry is a trusted name with many organizations running BB messaging servers in -house.  Time will tell on the platform's security, but its definitely going to be a good starting point for conversations with clients.  Oh BTW, the 1GHz processor and 1GB RAM doesn't hurt either ;)

I've installed the Playbook SDK and emulator on both Windows and Mac.  It's pretty straightforward, and I  only had one blip on Windows (fix is here).

So I promised there is an offer for a free tablet - if you submit a Playbook app to AppWorld and it gets accepted before the official Playbook release, you qualify for a free tablet.  Simple!  Now, I may have screwed up the offer legalities and such so look for yourself for full details.

RIM also has a few resources to get you started:

1. Getting started guide for Mac
2. Getting started guide for Windows
3. BlackBerry Tablet OS Development Resources

In link #3, be sure to check out the webcast series near the top of the page.  Enjoy!!!

Friday, October 22, 2010

Flex Skins Demystified (for Developers)

As a developer, I can always appreciate when languages make it easy to provide a clear separation of model and view (think MVC).  In ColdFusion we utilize a framework to produce these results.  Flex also allows us to use frameworks or apply common design patterns to our code for a separation of concerns.  Flex 4 introduced a native way to separate model from view utilizing spark skins.  This is largely to improve separation of workflow between designers and developers, but for MVC nuts, it serves us well.

I've trodded through several examples online and am assembling this tutorial a as way for developers to get started utilizing skins.  There are two primary types of skinning to get started with.  The first is skinning a native Flex component.  This takes place when you want to skin an existing component such as the spark.components.Button class.

The second type of skinning is for Flex custom components.  Skinning a custom component is much the same as skinning a native Flex component.  Your custom component can extend any class that extends SkinnableComponent.  When using Spark components, this is pretty much any visual component (another great reason for you to deprecate using mx based components in your apps for their spark counterparts).  A recent example I needed to skin was a button with multiple images.  I was able to create a subclass of spark.components.Button and add my images easily, unlike the hoops Flex 3 imposed.

Spark introduced a few new base containers for our use.  spark.components.SkinnableContainer works like a Canvas, but it is a subclass of SkinnableComponent (note that Group is the spark counterpart to Canvas, but is not skinnable).  For our example we will be extending SkinnableContainer to create a custom 'mirror' component.  For kicks we are also skinning a Button. This example is easy so as not to delve to deeply at first, but should get you started to more in-depth topics like skin states.  The final product looks like this:


First, we are going to tackle the Button skin. Flash Builder's workflow for creating a skin is very straightforward.  Name your skin and pick what component (or component skin it models, and Flash Builder will copy the contents of the base skin into your new file.  To create our button skin in Flash Builder, we select New > MXML Skin.  After naming our skin we can select the host component.


The skin includes many sections, two of which we will focus on immediately:

32:  [HostComponent("spark.components.Button")]  

HostComponent tells the skin what component we are basing our skin on, and therefore gives us access to the properties of that class for use within the skin itself like style definitions.  You can technically refer to any property including data proerties, but since we are trying to separate our view layer, that seems counterintuitive ;)  The Button class itself defines SkinParts, which are a powerful way to separate all data from the design (more on SkinParts in our other example below).  For our button we want to add an image, which is very easy to do.  We could also change any SkinPart (like shadow) or state (like down or over), or even modify SkinParts only within a specific state (like what the shadow looks like when you hover over the button).

The second part we will look at is the MXML that defines the Button component view.  In a Skin we can add any markup.  Within a Skin each component has "includeIn" and "excludeFrom" attributes to determine when a component should be visible.  If the component should be visible at all times, do not use either attribute.  To add an image we use the spark.primitives.BitMapImage class:

209:  <s:BitmapImage source="@Embed('assets/nav_refresh_blue.png')" top="5" bottom="5" left="5" />  

Now that our button skin is ready to go, we need to create our ImageButton component. We are creating the ImageButton component as an MXML file in this instance, but could also create it in ActionScript (which is shown in the next example).

ImageButton.mxml
1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"   
3:       xmlns:s="library://ns.adobe.com/flex/spark"   
4:       xmlns:mx="library://ns.adobe.com/flex/mx" skinClass="com.nictunney.skindemo.view.skins.ImageButtonSkin">  
5:  </s:Button>  
6:    

Skins are bound to components using the "skinClass" attribute.  There is absolutely nothing else to note here now, but we could add any properties or functionality in this file. Implementation of this ImageButton class will be shown at the end of this post.

For the next example we will be skinning a custom Flex component named MirrorGroup. The component doesn't do much other than display text, and then mirror the text back on the same line, reversed. To show that the component does not have to be created in MXML, this example uses all ActionScript. Our custom component extends SkinnableComponent so we can inherit the skinnable actions and parts of that base class.  The component itself is simple, with caveats:

MirrorGroup.as
1:    
2:  package com.nictunney.skindemo.view  
3:  {  
4:    import com.nictunney.skindemo.view.skins.MirrorGroupSkin;  
5:      
6:    import spark.components.Label;  
7:    import spark.components.supportClasses.SkinnableComponent;  
8:      
9:    public class MirrorGroup extends SkinnableComponent  
10:    {  
11:      [SkinPart(required="true")]  
12:      public var plainText:Label;  
13:      [SkinPart(required="true")]  
14:      public var mirrorText:Label;  
15:        
16:      public var content:String;  
17:        
18:      override public function stylesInitialized():void {  
19:        super.stylesInitialized();  
20:        this.setStyle("skinClass",Class(com.nictunney.skindemo.view.skins.MirrorGroupSkin));  
21:      }  
22:        
23:      override protected function partAdded(partName:String, instance:Object):void  
24:      {  
25:        super.partAdded(partName, instance);  
26:          
27:        if( instance == plainText || instance == mirrorText )  
28:        {  
29:          instance.text = content;  
30:        }  
31:      }  
32:        
33:    }  
34:  }  

SkinParts are really cool (lines 11-14). What they define is a contract between the designer and the developer. The developer provides a list of SkinParts to the designer as IDs, Flex component type, and if they must implement the SkinPart. The designer then creates the skin with those matching IDs and types. The SkinPart metadata tag in the MirrorGroup component tells Flex to join them up, hence linking data to view at runtime. I know this workflow was completely developer focused and backwards, but you get the idea ;)

The caveats to using an AS3 class instead of MXML that just plain sucked (until I found the right blog posts):
  1. Since we are attaching the skin in ActionScript, we must override the public stylesInitialized() method (lines 18-21).  This code comes from SEFOL.  In ImageButton.mxml this was not necessary as we specified the skinClass attribute in the component definition.
  2. We need to override the protected partAdded() method and delay processing of any properties of a SkinPart until they are added to our component from the Skin (lines 23-31).  If you do not do this you will get errors complaining about null references.  This code comes from Ryan Stewart.
The next step is to create the Skin.  Selecting New > MXML Skin in Flash Builder allows us to provide two important pieces of info:

The differences from when we created the button example are that we can specify the custom component MirrorGroup as the HostComponent, and we specify that it should create our Skin file as a copy of SkinnableContainerSkin, which is the default skin for SkinnableContainer, which we extended to create MirrorGroup.  Using the base skin gets us light years ahead.  Here is the finished Skin:

MirrorGroupSkin.mxml (stripped out boilerplate comments and ActionScript for brevity)
1:  <?xml version="1.0" encoding="utf-8"?>  
2:    
3:  <s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"   
4:    xmlns:fb="http://ns.adobe.com/flashbuilder/2009" alpha.disabled="0.5">  
5:    <fx:Metadata>[HostComponent("com.nictunney.skindemo.view.MirrorGroup")]</fx:Metadata>  
6:    
7:    <s:states>  
8:      <s:State name="normal" />  
9:      <s:State name="disabled" />  
10:    </s:states>  
11:      
12:    <!--- Defines the appearance of the SkinnableContainer class's background. -->  
13:    <s:Rect id="background" left="0" right="0" top="0" bottom="0">  
14:      <s:fill>  
15:        <!--- @private -->  
16:        <s:SolidColor id="bgFill" color="#FFFFFF"/>  
17:      </s:fill>  
18:    </s:Rect>  
19:      
20:    <s:HGroup id="contentGroup" left="10" right="0" top="10" bottom="0" minWidth="0" minHeight="0">  
21:      <s:Label id="plainText" />  
22:      <s:Label id="mirrorText" layoutDirection="rtl" alpha="0.3" />  
23:    </s:HGroup>  
24:    
25:  </s:Skin>  
26:    

Line 5 shows the HostComponent has been properly referenced. The standard SkinnableContainerSkin that was copied for us comes loaded with a spark Group with a basic layout.  We have replaced this with a HGroup and two labels.  Notice all of our styling has been implemented in the skin, but our values are nowhere to be seen?  The SkinParts we defined in MirrorGroup are seen here (matching IDs are a must) as "plainText" and "mirrorText".

The final step is to create an application and use the custom components and skins.

1:    
2:  <?xml version="1.0" encoding="utf-8"?>  
3:  <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"   
4:          xmlns:s="library://ns.adobe.com/flex/spark"   
5:          xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"  
6:          xmlns:view="com.nictunney.skindemo.view.*">  
7:      
8:    <s:VGroup top="10" left="10">  
9:      <view:ImageButton label="Toggle Mirror Visibility" click="mirrorGroup.visible = !mirrorGroup.visible" />  
10:      <view:MirrorGroup id="mirrorGroup" content="This is my text to mirror" />  
11:    </s:VGroup>  
12:      
13:  </s:Application>  
14:    

That's it! We are telling the button what to do when it is clicked (toggle visibility of the MirrorGroup). The text is also being passed into the MirrorGroup as its content property. Flex handles the rest!

Full code here

Tuesday, October 19, 2010

Using ColdFusion ORM with Flash Remoting in Flex via DTOs and Assemblers

ColdFusion 9 brought us a native implementation of Hibernate. ColdFusion has always been a wicked service tier, and extending CF ORM objects to Flex via remoting makes it even easier to connect CF and Flex.

NOTE: This information was originally explained to me over a bunch of conversations by Brian Kotek. Everything correct in this post can be attributed to Brian, and everything incorrect can be blamed on me ;).

There are a few reasons why utilizing data transfer objects (DTO) are a good idea:
  1. Reduce network overhead by only returning the data you need (BlazeDS - under the hood of remoting - has some issues with remotingfetch and lazy loading)
  2. Massage data to match the needs of the flex application's architecture (ordering arrays of children, concatenating strings, etc)
  3. Smaller footprint for serialization
A DTO is an an object that stores data. It is limited in that it knows how to do nothing else, but store data. DTOs are loaded up by an assembler (read about the dto assembler pattern). An object might have more than one assembler class depending on the method of access (such as remoting) or even the amount of data that needs loaded into an object for the present flex call. For example, one flex call might need a parent object with all related children, whereas another call might just need the parent object itself. In the latter case we could be returning a hundred objects when all we really need is a single string from the parent.

The following diagram shows a simplified workflow for reading data from a CF service tier from a Flex application:


The sample workflow shows a simple remoting call from the Flex application. The CF side receives the request in a singleton remoting proxy and uses CF ORM to load the requested object. The object is passed off to the assembler. The assembler knows how to assemble the DTO for this object. The proxy doesn't know anything about how to load the object or DTO. That functionality is injected into the proxy at runtime. When the DTO is passed back from the assembler it is returned to Flex. On the Flex side the AS3 DTO equivalent is populated and an assembler disassembles the AS3 DTO into the appropriate AS3 class.

The sample code below handles the ColdFusion side of the equation (the Flex side is the the same, but opposite). For our example we are requesting a Parent object with the specified ID via Flash Remoting. The call is received by our remoting proxy. Note that the proxy does not know how to create the Parent object or Parent DTO, but it knows where to get them via dependency injection. Take note that all of this would be even easier using if you allow ColdSpring to handle your objects ;)

RemotingProxy.cfc

1:  <cfcomponent displayname="RemotingProxy" hint="I am the RemotingProxy class.">  
2:      
3:    <!--- remote methods --->  
4:    <cffunction name="getParent" access="remote" returntype="parentDTO" output="false" displayname="getParent" hint="">    
5:      <cfargument name="parentID" type="string" required="true" />  
6:        
7:      <cfscript>  
8:        var parent = application.parentService.get(arguments.parentID);  
9:          
10:        return application.parentAssembler.assemble(parent);  
11:      </cfscript>  
12:        
13:    </cffunction>  
14:      
15:  </cfcomponent>  
The parent assembler's assemble() method takes the Parent object from ORM and maps it to the Parent DTO. The assembler then loads the children objects into the composition. It doesn't know how to assemble the ChildDTOs, but it has an instance of ChildAssembler injected into it at runtime that provides this functionality. Also note that there is a reference to the ProjectService. This is used when dissassembling. This would occur during a write operation triggered from the Flex application.

ParentAssembler.cfc

1:  component accessors="true" {  
2:    property ParentService parentService;  
3:    property ChildAssembler childAssembler;  
4:      
5:    public any function init (ParentService parentService, ChildAssembler childAssembler) {  
6:      setParentService(parentService);  
7:      setChildAssembler(childAssembler);  
8:        
9:      return this;  
10:    }  
11:      
12:    public ParentDTO function assemble (Parent parent) {  
13:      var dto = createObject('component', 'ParentDTO').init();  
14:        
15:      dto.id = parent.getID();  
16:      dto.title = parent.getTitle();  
17:        
18:      // add the children  
19:      aChildren = parent.getChildren();  
20:      for ( var i=1;i<=arrayLen(aChildren);i++ ) {  
21:        arrayAppend(dto.children, getChildAssembler().assemble(aChildren[i]));  
22:      }  
23:        
24:      return dto;  
25:    }  
26:      
27:    public Parent function disassemble (ParentDTO parentDTO) {  
28:        
29:      return ;  
30:    }  
31:  }  
The DTO stores all properties of the Parent class in public variables. You may choose to keep these variables private and provide accessors and mutators for access. The use of cfproperty here is for the purpose of self-documentation.

ParentDTO.cfc

1:  component alias="com.nictunney.dto.ParentDTO" {  
2:    
3:    property string id;  
4:    property string title;  
5:    property array children;  
6:      
7:    public any function init () {  
8:      this.id = '';  
9:      this.title = '';  
10:    
11:      this.children = [];  
12:        
13:      return this;  
14:    }  
15:  }  

The full code is available here. Hope this gets you started utilizing ColdFusion 9 ORM with your Flex applications.

Saturday, October 16, 2010

User Experience for Developers

User experience (UX) is an enigma to many developers, but is something I think developers should have a firm grasp on to excel as well as create apps that not only impress, but also work for (as well as with) the end user. Many developers do not understand the difference between UX and UI (user interface). UX defines how a user interacts with your application, whereas UI is the actual implementation of the patterns selected for the interaction. If UX is not considered in detail up front, I always expect several iterations of extra development resulting from user acceptance testing (UAT).

I had the unique opportunity to work with Will Evans and watch a master in action which really sparked my interest in user experience design. I don't have the opportunity to apply his overarching tenet that 'You are not the user' in full, I always keep it in mind when speaking with clients and while developing the UX for any app I architect.

A few important assets to understand in getting you started in UX are listed below.

User Personas
User personas were something that were uncomfortable to me at first. I was used to defining different types of users while architecting systems and agile user stories, but adding information like salary, education and age seemed uncomfortable at first. Properly defining descriptors like this help to develop usage scenarios. The user persona allows us to understand how a specific user will access the system, where they will access the system from, their technical proficiency and even if they need adaptive technology to overcome a disability. Also, being able to identify deeply with users really helps when creating stories and process flows. Performing user interviews really helps! So does observation of users performing their tasks or interacting with an existing application (if one exists).

User Stories
Much like standard application development, UX involves the creation of user stories. In software dev we generally build these stories by working with the product owner and their understanding of the system. During UX discovery it is a great idea to look beyond standard requirements and involve additional stakeholders, and EVEN MORE IMPORTANTLY: a sampling of end users. These user stories define not only a user's interactions with your application but also the process flows identified by the stories. Unlike Agile development stories, UX stories can be much more verbose, and also define personas within the context of the system.

Information Architecture (IA) and Content Inventory
For developers, this is a very familiar deliverable. Consider this a sitemap, but even more importantly, the hierarchy of how information is organized within your application. This defines how users will find information or services. IA is a huge topic in itself, and we won't be going into it in detail in this post.

Process Flows
Another familiar asset for developers, these flow diagrams are perfect for demonstrating user interactions for common system tasks. I like to create these as UML activity diagrams. Being able to walk a user or stakeholder through a workflow is very helpful and saves time in the longrun, especially considering how visual users are.

Wireframes
I'm pretty sure every developer has been in a client meeting at some point explaining some complex method of attacking a problem using a image, and the client turns to you and says, 'You know what, I think that shade of blue should be slightly darker, and perhaps the logo should be larger, and maybe we need a san-serif font here that blinks and ....'. Somehow they've entirely missed the decision they were supposed to be concentrating on and got caught up on ancillary topics. Wireframes are an awesome solution to this problem for a few reasons. Aside from just allowing you to focus on process and function over form, they are also simple to create and take much less time than full visuals. Wireframes allow you to develop experience and interaction first, managing visual design at the appropriate time once the processes have been clearly defined. Wireframes generally do not stand on their own and require annotations that call out specific details.

UX Design Patterns
I could dedicate an entire series of posts to UX patterns. Just like in software development, user experience designers have also identified common problems and sets of solutions that address said problem. By understanding the needs of your users by observation and interviews, you can apply the correct pattern (or work from a pattern) to provide a good experience. Yahoo! has a list of pattern libraries to get you started. I also highly recommend Martijn van Welie's pattern library.

Visuals
When creating high fidelity visuals (also referred to as comps) it is important to remember that you don't need to create visuals for the entire site. Generally you will have a few variations of pages that will need created. I still find lorem ipsum text important during this stage with some clients to allow to to focus on the proper items. Make sure the visuals tell enough of the story you are attempting to convey within the application flow. Many times this step is handed off to a visual designer, but ti is imperative that the UX designer remain engaged during this stage. Not always necessary, but important nonetheless, sometimes mood boards help define the artistic direction (especially when developing an entire brand experience). Mood boards can also be used to demonstrate design concepts and themes to a client before creating fully fledged visual designs.

Style Guide
A style guide is an important asset to deliver with your UX design. This allows developers to easily recreate your vision utilizing the correct hexadecimal colors and fonts. Creating a cascading style sheet is simple utilizing a style guide, and prevents developers from taking too many creative liberties with the design.

These are just a few assets to get you started. I have quite a few good examples of UX in action that I'll post depending on interest. If anyone wants additional information or examples on a single asset above, let me know and I'll wire them up.

Thursday, September 2, 2010

jQuery: Simple Ajax Loading Screen

So another thing jQuery made easy for me this week was a loading screen. What I wanted was a loading screen to be displayed for all Ajax calls. I started preparing for this by thinking of the states I'd need to watch and then the search and replace that wouldn't work quite right to ensure all of my Ajax would kick off the loading screen, and then turn it off again when the call was successful.

Well, it seems in jQuery this is pretty easy. Check the code below, as it is all it took.

busyDialog = {
 
 init: function () {
  var el = $(document.createElement('div')).attr('id', 'busyDialog')
   .css({
    'width': '100%',
    'height': '100%',
    'background-image': 'url(lib/images/ajax-loader.gif)',
    'background-position': 'center',
    'background-repeat': 'no-repeat',
    'position': 'fixed',
    'z-index': '9999',
    'display': 'none',
    'cursor': 'progress'
   });
  
  $(el).ajaxStart(function(){
      $(this).show();
   });
  $(el).ajaxStop(function(){
      $(this).hide();
   });
  $('body').prepend(el);
 }
}

Personally, I have this thing loaded into a widget class.  When the app instantiates I call the init method and I'm set.  This would be sickeningly easy to prototype into jQuery as a plugin.

What happens in the code above is that we create a new div and place a loading animated gif in the center of it.  You can get an animated gif over at AjaxLoad.  The div is created at 100% width and height so that the use cannot interact with the screen while the loading dialog is active.  The loading div is initially invisible.  Two event handlers (ajaxStart and ajaxStop) are employed, which is where the real helpfulness of jQuery comes in.  jQuery allows us to specify global handlers (here showing and hiding the loading div) for all Ajax requests.  We are still able to have our custom success handlers for each individual Ajax call.  Wicked.

The final step is to throw the div into the DOM.  We do this as the first child of 'body'.

Friday, August 27, 2010

jQuery Validate and Checkboxes

As I start this post, a quick aside.. I've had some discussions with a few devs lately on the use of the id attribute versus the name attribute on HTML input elements.  IMO, id is a unique identifier, whereas name is used to tie fields such as checkboxes together, which today's post deals with.  The result looks like this:


For what it's worth, I never use the name attribute on input elements except when it is of type checkbox, but I digress... ;)

I had the need to require two or more checkboxes to be checked on a form recently.  I am using jQuery Validate for the form validation logic.  This is the first time I've had to roll my own validator since starting with jQuery Validate as it's defaults are pretty inclusive.  Creating a custom validator is simple.  The code looks like this:
$.validator.addMethod(
 'multiplecheckboxchecked',
 function (value, element) {
  var aChecked = $('input[name='+$(element).attr('name')+']:checked');
  return ( aChecked.length > 1 ) ? true : false;
 }
);
Breaking it down,  use the addMethod() function to define a new rule in the form addMethod(name, callback, message).  In my validation logic I change the color of the container div so I do not need the message attribute.  The name attribute specifies the rule name when we assign it to an element when creating the validator.  The callback is the function we will use to validate the form field.  The callback method gets two parameters by default: value and element.  Value is the value of the form field being validated.  In the case of a checkbox this is a bit weird.  We get only one element passed through which has the name value we specify in our rules definition.  The element is the actual form element, and for a checkbox we can use this to our advantage by grabbing the name attribute to get all of the checkboxes bound by the same name.  Line 4 shows our selector: 'input[name='+$(element).attr('name')+']:checked'.  This tells jQuery to get all input controls with a name matching our checkbox group name that are also checked.  This selector returns an array of elements, and we use the length of that array to tell how many boxes have been checked.  In my case I needed at least two, so I return true if two or more are checked, false if one or less are checked.

Using the rule then looks like this:
rules: {
 frictiontypeid: 'required',
 checkboxgroupname: 'multiplecheckboxchecked'
}
I also had to use a custom highlighter which is simple to override for checkboxes:
highlight: function(element, errorClass, validclass) {
 // if the element is a checkbox, highlight the entire group
 if ( element.type == 'checkbox' ) {
     $(element).parents('.ctrlHolder').addClass('error');
 } else {
  $(element).parent().addClass('error');
 }
},

Monday, August 23, 2010

More ORM Weirdness

NOTE: the first part here addresses CF 9.0.0.  9.0.1 does not fix this, but expands the weirdness.  9.0.1 behavior is the second half of this post.

In my last post I learned via @brian428 that the behavior was correct since the collections need to be loaded or else ORM doesn't know if they should be deleted from the collection or not.  EntityMerge() did not work, but loading based on length of the passed ID did (again, thanks Brian).

The new weirdness is when I return the loaded object back via JSON.  There are two child collections: Entities and FocusAreas.  Entities are null and lazy loaded.  FocusAreas contains one record, and is also lazy loaded.  Note the JSON:
{"obj":{"entities":[],"id":"8ab2932d2a8529d6012a856916c40002","focusareas":,"errors":[]}
See that focusareas returns nothing, whereas entities returns an empty array. The error comes on the client since when I eval() in JavaScript it tries to set focusarea to ',"errors":[]}' and then sees no proper closing for the JSON string. Setting lazy="false" on the focusareas relation fixes the issue, but then I have to return the focusareas, which I do not need. What I would expect to see is:
{"obj":{"entities":[],"id":"8ab2932d2a8529d6012a856916c40002","focusareas":[],"errors":[]}
The error would be fixed by setting the value of getFocusAreas() to an empty array upon initialization.

So here is where Brian suggested I install the CF 9.0.1 updater.  At first I was pleased.  When I returned the value after an entitySave(), it did not return entities or focusareas.  w00t!  To be sure, I then loaded the focusareas with getFocusAreas().  They still were not returned!  Setting lazy="false" also had no bearing.  There was nothing I could do to get them to return.  For a sanity check I dumped the parent object right before the return and got this:


I've cleared my cache and restarted CF.  The returned JSON is still:
{"obj":{"id":"8ab2932d2a8529d6012a856916c40002","title":"Test Project"},"errors":[]}

ColdFusion entitySave() Issue

I'm trying to use entitySave() and am finding a weird behavior.  My parent object links to the child object as such:
<cfproperty name="focusareas" singularname="focusarea"
          fieldtype="one-to-many" type="array" cfc="FocusArea"
          fkcolumn="parentid" cascade="delete" />
When I save the parent, I am using an Ajax call and the service proxy uses an entityNew() to create the child, sets its id and other variables and then calls entitySave().
var parent = entityLoadByPK('Parent', arguments.id);
  parent.setID(arguments.id);
  parent.setTitle(arguments.title);
  entitySave(parent);
The logical behavior is that entitySave() determines if the record should be inserted or updated. What happens is pretty strange though. Check out the Hibernate log:
Hibernate:
    update
        Parent
    set
        title=?
    where
        id=?
Hibernate:
    update
        FocusArea
    set
        parentid=null
    where
        parentid=?
The wackiness is that entitySave() does indeed perform an update as opposed to an insert as expected, but then disconnects itself from the child record. If I instead do an entityLoadByPK() and then set all values, everything works as expected. The issue with this is I should not have to check and see if the parent is new and perform an entityNew() or entityLoadByPK() explicitly. This is what ORM does for you. Bug? Thoughts?

Thursday, August 12, 2010

Custom Ajax Callback Arguments for jQuery

I had the need to pass a custom argument to a callback function upon a successful Ajax call today.  Using jQuery for my current project I needed to find the standard way to pass custom arguments.  The API didn't list anything so I turned to Google.  Google 'suggested' using closures.  The solution would look like this:
function myCallback(o, arg) {
  // do stuff with the custom argument
  alert(arg);
}

$.ajax({
  url: 'myproxy.html',
  success: function (o) {
    myCallback(o, 'myvalue');
  }
});

What occurs above is that when the success callback function is called it passes the object returned from the asynchronous call, as well as the custom value which is explicitly defined to the inner function.  It works, but I'm not entirely happy with it.

After reviewing the jQuery API docs I decided to use the context attribute instead.  Seems slightly less kludgy to me.  It looks like this:
function myCallback(o) {
  // do stuff with the custom argument
  alert(this.myVar);
}

$.ajax({
  url: 'myproxy.html',
  success: myCallback,
  context: {myVar: 'my value'}
  }
});

Whatever is passed into 'context' becomes the context of the callback function.  This is meant to be used to pass an actual context, such as the entire document or an element within the document.  This is still pretty hacky.  What I would prefer is the type of behavior YUI has, which allows an additional attribute to be passed with the asynchronous object, which is then passed through to the callback automatically:
function myCallback(o) {
  alert(o.argument.myVar);
}

var callback = {
  success: myCallback,
  argument: {myVar: 'my value')}
}

YUI.util.Connect.asyncRequest('GET', 'myproxy.html', callback);
In perusing the jQuery source, it seems pretty easy to add this functionality.  I'm new to jQuery so I'm not sure how forks and such occur.  Is there an easier method?

Tuesday, August 10, 2010

Cascading deletes in ColdFusion ORM

I started the delete functionality of my application today, for which I am using ColdFusion ORM, and I noticed puzzling behavior when deleting a parent object.  This example will use the following database design:


The relationship between a Story and its Tasks is one to many.  Task.storyid is a foreign key that cannot be NULL, as a Task cannot exist without its associated parent Story.  The ColdFusion classes would look like this:

Story.cfc
<cfcomponent displayname="Story" hint="I am the Story class." persistent="true">
  
  <!--- properties --->
  <cfproperty name="id" fieldtype="id" type="string" generator="uuid" unsavedvalue="-1" length="32" />
  <cfproperty name="name" type="string" />
  <cfproperty name="tasks" singularname="task"
          fieldtype="one-to-many" type="array" cfc="Task"
          fkcolumn="storyid" cascade="delete-orphan" />
  <!--- constructor --->
  <cffunction name="init" returntype="Story" access="public" output="false" hint="Constructor">
    
    <cfscript>
      setID(-1);
    </cfscript>
    
    <cfreturn this />
  </cffunction>
  
</cfcomponent>
Task.cfc
<cfcomponent displayname="Task" hint="I am the Task class." persistent="true">
  
  <!--- properties --->
  <cfproperty name="id" fieldtype="id" type="string" generator="uuid" unsavedvalue="-1" length="32" />
  <cfproperty name="storyid" type="string" />
        <cfproperty name="summary" type="string" />
  <!--- constructor --->
  <cffunction name="init" returntype="Task" access="public" output="false" hint="Constructor">
    
    <cfscript>
      setID(-1);
    </cfscript>
    
    <cfreturn this />
  </cffunction>
  
</cfcomponent>
Story.cfc defines the one-to-many relationship to it's children on line 6 by defining the relationship type, specifying the cfc that defines the child object, and by providing the foreign key column.  The other important bit here is the cascade attribute.  All cascade options may be found here.  (Note: I also tried 'delete' for the cascade attribute, but it had the same effect.)

When we perform an entityDelete() on the parent Story, I expected the child to delete.  Instead, I received the following error:
Error 1048: Column 'storyid' cannot be null. Root cause :java.sql.BatchUpdateException: Column 'projectid' cannot be null
By looking at the hibernate logging I could see that the following was attempting to occur:
  1. Load all objects in the relationship
  2. Set the storyid to NULL
  3. Delete the parent object
  4. Delete the child object
This order of events doesn't make sense, since in a one-to-many relationship as we defined above, storyid could never be NULL as it would break our model (Tasks only exist within the context of a Story).

To get the delete to cascade properly, I had to remove the required attribute of the FK column constraint. Why is this bad?  Well, without the requiring a NOT NULL storyid in the Task table, we allow a developer to persist an orphaned Task (one that never belongs to a Story).  While application code should prevent this from happening, the database should also enforce this policy by defining a proper schema.

The question is do the ends justify the means?  It was easy to get the cascade to function properly by breaking the database design, but now the schema does not properly enforce model constraints (in the real project I actually had 9 FK constraints across 7 tables).  The alternative is to create a delete() method in the Story object which deletes the Task before deleting the Story.  I don't like that since it does not override entityDelete() and goes around ORM as it should be implemented.  Thoughts?

Thursday, August 5, 2010

jQuery Validation Plugin and Uni-Form

I'm using Uni-form on my current project and it is pretty structured in the way elements are nested and classed (and rightly so).  One thing we are taking advantage of is the error notification.  As opposed to giving a small error message, the field div is colored a light shade of red.  Seems like a positive user experience to me as there is no question which fields are in error.
I also usually perform validation via a javascript class I've been using for awhile, but it is clunky and time consuming.  Since I'm embracing jQuery on this project I knew there had to be a good validation plugin.  The one I am using is named simply jQuery plugin: Validation. The docs are decent and the plugin has been around for a few years.  It also validates most of the types a web application would need.  Another cool thing is that it allows field grouping for validation which I could see being handy.

The default behavior is pretty standard in that it will add an error class to the field and append a label with the error message.  Each error message may be overwritten by validation type across the entire validator, or right down to the element level.  9 times out of 10 this would be awesome.  Since I was using Uni-form's error schema, this didn't work for my application.  In Uni-form, a single form element is grouped together with its label and a metadata hint like the following:
<div class="ctrlHolder">
      <label for="">Text input</label>
      <input id="txt" name="txt" value="" size="35" class="textInput" type="text">
      <p class="formHint">This is a form hint.</p>
    </div>
What I needed was to add an error class to the parent div that contains the text input control.  I tried several different methods of achieving this, but the one that worked for me was to use the 'highlight' and 'unhighlight' configuration properties of the validator.  The setup for the validator looks like this:
// load the validator when the DOM is ready
  $(function () {
    $.validator.messages.required = '';
    var validator = $('form').validate({
      // disable checking on every event except submit      
      onkeyup: false,
      onfocusout: false,
      onclick: false,
      debug: true,
      // define the rule for our text field to be required
      rules: {
        txt: 'required'
      },
      // function to call when the form has passed validation and ready to be submitted
      submitHandler: function () {alert('form submit!');},
      errorPlacement: function () {},
      highlight: function(element, errorClass, validclass) {
        $(element).parent().addClass('error');
      },
      unhighlight: function(element, errorClass, validclass) {
        $(element).parent().removeClass('error');
      }
    });
  }) 
Getting the parent div was easy enough using jQuery and the element passed back into the hightlight and unhighlight methods. We just had to add a class when the error is caught, and remove the class when the error has been cleared.

You'll also note that I needed to disable the default behavior which appends a label containing the error message after the form control.  This was achieved by passing an empty function to the errorPlacement configuration property as seen on line 16 above.

One caveat to using the Validate plugin is that you have to have a name attribute on all form fields (at least those you want to validate, all if you don't want to see any errors in debug mode). I generally only include an 'id' attribute, so this hung me up for a bit (thanks @boyzoid)

The complete example can be downloaded here.

Wednesday, August 4, 2010

Kool-Aid - now available in ORM flavor!

A few years ago I had the opportunity to play a part in the great ColdFusion OOP debate.  Apparently it still rages on in the form of OO Architecture, and most recently ColdFusion ORM.  So today, while learning CF ORM, I came upon the issue of a lookup table.  You know the sort, one that contains n values that populate a dropdown control.  To create a simple example, lets use a Developer class with a many-to-one relationship of beer preference.  The ERD would look like this:


So the question is, if I wanted to populate a dropdown control, what do we do?  I knew what made sense in my mind but I want to make an attempt embrace CF ORM, so again today I decided to use a lifeline and reach out.  The answer I received was CF ORM 'logic' (air quotes added by the writer ;) ) would say we create a Beer class and use entityLoad('Beer') to create an array of all possible instances of beer, then loop over that array of objects and call getID() and getName() on each instance to populate the dropdown.  Before you say, "But we can lazy load them", sure we can.  But we need each and every class to get all of the beer varieties.  Knowing the CF community's affinity towards a multitude of fine microbrews this list could get pretty long.  I guess a factory reusing object instances could help here but its a dropdown, and this becomes architecture for the sake of architecture (but see how your mind started to wander there - heh).

My logic dictated that I should create a gateway and write a line of SQL, instantiate the gateway as a singleton and we can even cache the query. This means we create one object, do one database read, and sit there and listen for requests.  To that end I created a SelectorGateway class, created a method to select all beer varieties from the selector table, ordered them by name and returned them to the caller as a query.  The singleton was instantiated with the datasource passed in from this.ormsettings.datasource for maintainability.

What I am attempting to illustrate via this simple example is the continued 'architecture for the sake of architecture' mindset that exists within our community.  Keep in mind to always use the best tool for the job, and if something just doesn't make sense to you, it probably doesn't make sense period!  Also, following an agile development philosophy make smart architectural decisions, but don't plan for 10 steps down the road when 99% of the time those steps will never be necessary, but your client still has to pay for them.

All this being said, there may be a better way to perform the above.  I'd love to hear other suggestions!

Tuesday, August 3, 2010

ColdFusion 9 ORM and the unsavedvalue Attribute

I was working on a project today that I decided to use with CF 9 ORM and ran into an issue while saving a new record. The database I am using is MySQL 5.1. The error I was getting:
Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
Google had some stuff to say, primarily about unrelated solutions, so I decided to use a lifeline and phone a friend. Marc Esher apparently has seen this (amongst some of the other less than helpful Hibernate errors CF causes) and suggested using the 'unsavedvalue' attribute. Worked like a charm so I decided to post here...

The class in question:
<cfcomponent displayname="Project" hint="I am the Project class." persistent="true">

<!--- properties --->
<cfproperty name="id" fieldtype="id" type="string" generator="uuid" length="32" />
<cfproperty name="title" type="string" length="75" />
...

<!--- constructor --->
<cffunction name="init" returntype="Project" access="public" output="false" hint="Constructor">

<cfreturn this />
</cffunction>
</cfcomponent>
I'm using a uuid PK and the MySQL database table does not autogenerate the PK so CF ORM needs to handle this, hence the 'generator' attribute on the id tag. What seems to be occurring is CF tries to commit the instance when I call entitySave(), but sees it as a update as opposed to a create. Marc's suggestion to use the 'unsavedvalue' attribute lets CF know that it has not saved the record yet, forcing it to create a new record. The updated CFC:

<cfcomponent displayname="Project" hint="I am the Project class." persistent="true">

<!--- properties --->
<cfproperty name="id" fieldtype="id" type="string" generator="uuid" unsavedvalue="-1" length="32" />
<cfproperty name="title" type="string" length="75" />
...

<!--- constructor --->
<cffunction name="init" returntype="Project" access="public" output="false" hint="Constructor">

<cfscript>
setID(-1);
</cfscript>

<cfreturn this />
</cffunction>
</cfcomponent>
The 'unsavedvalue' attribute is being set to -1 (which is safe even if you are using a numeric PK). When CF ORM creates an instance of the Project class it automatically calls the init() method for us, which in turn sets the starting ID value to -1. When entitySave() is called, CF ORM checks the value of the id field before committing the object and correctly creates a new method.

Monday, August 2, 2010

My first Swiz Application

So I'll be doing more Flex development in my new position (and will also be touching CF a bunch more as an aside), and I decided to take another look at Swiz. I'm not a big frameworks guy, but in Flex there is a definite need to mediate events which I know Swiz does well, so I decided to take a peek.

I decided to hit a few things at once with my first Swiz application, a sort of technical spike for the project work I will be doing. For this example I needed to map relationships between entities. I found Mark Shepherd's SpringGraph component which sounded like what I needed. It
"displays a graph of objects that are linked to each other, using a force-directed layout algorithm".
Perfect.

Next, I needed a persistence layer. I've gotten to play around with CouchDB a bit for prototyping, so I decided it would be great for this proof of concept. Why?
  1. Dynamic model
  2. Static queries (views)
  3. Restful interface
The latter is the most important to me here since, while the first two are important in the long run, a restful interface means I do not need a service layer to proxy my db requests. I've enjoyed prototyping in CouchDB previously and this got me up and running quickly. If you don't already have CouchDB installed and are on Windows, there is a windows binary installer that works nicely. I named my database 'swizsample'. After you create the database you can copy this file into your data directory to load the data for this example (Linux: /usr/local/var/lib/couchdb/ or Windows: %couch%\var\lib\couchdb\).

After installing Flash Builder 4 (with the Flex 4.1 SDK) as a plugin to eclipse, I grabbed my necessary libraries (included in the attached sample project):

3. as3corelib 0.93 (for deserializing JSON)

After reviewing the Swiz sample applications and reading the documentation (not a ton of documentation is by design here) I created the following directory structure, simplistic since the app is a POC:



I then needed to tell Swiz where my application resources are located. In my Main.mxml file I added a few namespaces to my Application tag:
  1. xmlns:view="com.nictunney.view.*" - So I can import my base view
  2. xmlns:config="com.nictunney.config.*" - So I can tell Swiz where my config file is located
  3. xmlns:swiz="http://swiz.swizframework.org" - namespace for the Swiz framework
I then declared my Swiz configuration in Main.mxml using the swiz component tags beanProviders and config:
<fx:Declarations>
<swiz:Swiz>

<!-- BeanProviders simply contain the non-display objects that Swiz should process. -->
<swiz:beanProviders>
<config:Beans />
</swiz:beanProviders>

<swiz:config>
<!-- The eventPackages value tells Swiz the path to your Event classes,
and viewPackages is an optional value that speeds up the processing of display classes. -->
<swiz:SwizConfig
eventPackages="com.nictunney.event.*"
viewPackages="com.nictunney.view.*" />
</swiz:config>

</swiz:Swiz>
As you can see from the comments, I point beanProviders to my Beans.mxml configuration file. In this simple example I can put all of my bean configuration data in a single file, but you may have more depending on your architecture.
<swiz:BeanProvider
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:swiz="http://swiz.swizframework.org"
xmlns:model="com.nictunney.model.*"
xmlns:control="com.nictunney.control.*"
xmlns:service="com.nictunney.service.*">

<service:MapService id="mapService" />
<control:MapController id="mapController" />

</swiz:BeanProvider>
As you can see above, I included my service and controller components for my map object (named map since we will be drawing a relationship map). Take a peek in the MapService.as class and you will see loadItems(), which makes an HTTP call to the CouchDB restful interface to retrieve a view (no queries, only document views in CouchDB). The successful result will call the httpResult method in the same class (more on that logic later).

The aptly named MapController.as class serves as a controller interface for the map service. Note that it makes use of the Swiz [Inject] metadata tag. This is clutch as the [Inject] metadata tag is performing a dependency injection by type here (as recommended by the Swiz docs) based on the definition in the Beans.mxml file. We can now reference the current state of the MapService using the mapService pointer (as seen on line 17).

I defined a single custom event for the application. Nothing to note here except that when calling the constructor on the Event superclass, you need to set the 'bubbles' property to 'true' (see line 13 in MapEvent.as). To hold the data there is a single GenericItem class defined. No real magic going on here either.

So, aside from the dependency injection, where else does Swiz get involved in the app? Glad you asked. Again, I feel that event mediation is the primary reason to use a framework in Flex. Code in Flex is pretty self organizing, but events can be a bear across a complex model with multiple views. Swiz handles event mediation well. If you take a peek at Map.mxml (the only view defined for this sample application), aside from the view and function to handle the SpringGrpah itself, there are two things of note handled by Swiz.

First, event mediation really is as simple as the following code:
[Mediate( event="MapEvent.PLACE_ITEM_REQUESTED", properties="item" )]
public function newItem(item:GenericItem): void {
trace('[Swiz] Mediating MapEvent.PLACE_ITEM_REQUESTED for item.' + item.id + '.');
var i: Item = new Item(item.id);
i.data = item;
g.add(i);
if(prevItem != null)
g.link(i, prevItem);
prevItem = i;
s.dataProvider = g;
}
The [Mediate] metadata tag tells Swiz to call the newItem() function when the MapEvent.PLACE_ITEM_REQUESTED event is fired anywhere in our example application. Note that we can use MapEvent directly (and not the package name) since we defined the eventPackages attribute in our swiz config in Main.mxml. Another important point here is the properties property. By telling Swiz to pass in the item property from our event, newItem() can now be called explicitly from elsewhere in our code (see that no event is being passed into the function itself?

The original event is fired from the MapService class when the HTTP call is completed. Two things to note in MapService.as. Since it is not a UI component we need to create an instance of IEventDispatcher and let Swiz know to monitor events passed from it by specifying the [Dispatcher] metadata tag:

[Dispatcher]   public var dispatcher : IEventDispatcher;

This dispatcher is then used to send the events from our service. If we were dispatching an event from a UI component, Swiz would monitor it by default.

The last thing Swiz needs to know is where to start processing our application. For our needs we are telling Swiz to call the main() function in Map.mxml by using the [PostConstruct] metadata tag. [PostConstruct] is called after a display object is placed on the stage. Be sure to check out the Swiz Bean lifecycle management page for more information.

If you run the application in debug mode (make sure you have the debug Flash player) you'll see Flex load the SpringGraph instance onto the stage, Swiz call the main() function, triggering the MapEvent to fire, and newItems() receive the GenericItem objects and add them into the SpringGraph. Pretty sweet!

Source code for this example can be found here

Saturday, January 30, 2010

C++ IDE Installed

I decided to install CDT tonight and begin playing around with C++. I haven't touched the language since my second year of college. Back in my day we used it as our base during Discrete Structures. I think now they use Java. Anyways, why do I want to pick up a new language? Well, cause I'm a geek. Not sure what my first project will be, but I imagine it will be something video related since that is what my focus is at work. Any ideas?