Sunday, October 30, 2011

Flex4: Hide/Show AdvancedDatagrid Columns in Flex 4: a design pattern

In this post I will point out how a usually disliked programming technique (recursion) is going to help to write clean and manageable code. In my point of view, recursion is to prefer to iteration when we can estimate in advance the depth of the recursive calls, or we are reasonably sure about an upper bound. The following tutorial shows a general purpose drop-in routine that can be reused for any advancedDatagrid and provides the following benefits:
  1. Populate a menu based switcher with grid's headerText.
  2. Manage hiding/showing columns.
To better understand the code, let see the advancedDatagrid declaration in mxml:
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
<mx:AdvancedDataGrid id="grid"  selectionMode="singleRow" wordWrap="true" 
  headerWordWrap="true" 
  defaultLeafIcon="{null}" alternatingItemColors="[#ffc4c4, #FFFFFF]" 
  height="300" width="800" x="0" y="46">
  <mx:groupedColumns>
    <mx:AdvancedDataGridColumnGroup headerText="Equipo" >
      <mx:AdvancedDataGridColumn headerText="Descripcion" />
      <mx:AdvancedDataGridColumn headerText="Marca" />
      <mx:AdvancedDataGridColumn headerText="Modelo" />
      <mx:AdvancedDataGridColumn headerText="Serie" />
      <mx:AdvancedDataGridColumn headerText="Ubicacion" />
    </mx:AdvancedDataGridColumnGroup>
    <mx:AdvancedDataGridColumnGroup headerText="Empresa" >
      <mx:AdvancedDataGridColumn headerText="Nombre" />
    </mx:AdvancedDataGridColumnGroup>          
    <mx:AdvancedDataGridColumn headerText="Fecha" />
    <mx:AdvancedDataGridColumn headerText="Asignado"/>
    <mx:AdvancedDataGridColumn headerText="Terminado"/>
    <mx:AdvancedDataGridColumn headerText="Puntos"/>
    <mx:AdvancedDataGridColumn headerText="Monto"/>
    <mx:AdvancedDataGridColumn headerText="Factura"/>
    <mx:AdvancedDataGridColumn headerText="Monto Factura"/>
    <mx:AdvancedDataGridColumn headerText="Pagado"/>
  </mx:groupedColumns>
</mx:AdvancedDataGrid>


We are going to hide/show columns using headerText values instead of id's for the following reasons:
  1. It's easier to populate a menu based switcher with grid's headerTexts in actionscript than having to manually write the dataProvider content in mxml.
  2. We can write a general algorithm not requiring a support function acting as a dispatcher.
  3. We can reasonably assume that no two columns have the same headerText (Note that this is a mandatory requirement).
Let define a PopUpMenuButton and its dataProvider:
1
2
3
4
5
<fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
  <s:ArrayCollection id="arr"/>
</fx:Declarations>
<mx:PopUpMenuButton x="10" y="10" label="Hide/Show Columns" dataProvider="arr"/>
Basically, we want now to define a general purpose traversal function in actionscript which can be used for both menu population and event handling when hiding/showing columns. We will use some more or less advanced coding technique in OO programming leading to the implementation of a design patter (I'm sure it has a name but I don't known which one in this moment). First of all, we create a new Interface in as3 called "LeafHandler.as":
1
2
3
4
5
6
7
8
9
package
{
  import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
 
  public interface LeafHandler
  {
    function handleLeaf(leaf:AdvancedDataGridColumn):void;
  }
}
The function handleLeaf() must implement the logic of both variants: menu population and hiding/showing support. So, we can write the first implementation "MenuLeafHandler.as":
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
package
{
  import mx.collections.ArrayCollection;
  import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
 
  public class MenuLeafHandler implements LeafHandler
  {
 
    private var arr:ArrayCollection;
 
    public function MenuLeafHandler()
    {
      arr = new ArrayCollection();
    }
 
    public function handleLeaf(leaf:AdvancedDataGridColumn):void
    {
      var obj:Object = new Object();
      obj.label = leaf.headerText;
      obj.type = "check";
      obj.toggled = "true";
      arr.addItem(obj);
    }
 
    public function getArray():ArrayCollection {
      return arr;
    }
  }
}
For each leaf of the columns tree of the AdvancedDatagrid, we create a an Object containing the description of a CheckBox, and add it to the array. Next, we provide the implementation for columns hiding/showing logic in the file "HideShowHandler.as":
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
package
{
  import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
 
  public class HideShowHandler implements LeafHandler
  {
    private var item:AdvancedDataGridColumn = null;
    private var headerToLookFor:String;    
 
 
    public function HideShowHandler(headerToLookFor:String)
    {
      this.headerToLookFor = headerToLookFor;
    }
 
    public function handleLeaf(leaf:AdvancedDataGridColumn):void
    {
      if (item != null) return;
      if (leaf.headerText == headerToLookFor) item = leaf;
    }
 
    public function getLeaf():AdvancedDataGridColumn {
      return item;
    }
  }
}
 In this case, we just want to save in memory a reference to the AdvancedDatagridColumn having the headerText value equal to the label of the CheckBox generating the click event. Note that the constructor of this class takes a String as a parameter, which must be set to the label value of the MenuItem generating the click event.
The last step is to define the actual traversing function. We will make use of the polymorphism nature of as3. The code for "Traversal.as" follows:
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
30
package
{
  import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
  import mx.controls.advancedDataGridClasses.AdvancedDataGridColumnGroup;
 
  public class Traversal
  {
    private var handler:LeafHandler;
 
    public function Traversal(handler:LeafHandler)
    {
      this.handler = handler;
    }
 
    public function traverseAndGetHandler(clms:Array):LeafHandler {
      traverse(clms);
      return handler;
    }
 
    private function traverse(clms:Array):void {
      for (var i:int = 0; i < clms.length; i++) {
        if (clms[i] is AdvancedDataGridColumnGroup) {
          traverse(AdvancedDataGridColumnGroup(clms[i]).children);
        } else {
          handler.handleLeaf(AdvancedDataGridColumn(clms[i]));
        }
      }
    }
  }
}

This is the function using recursion as anticipated before. Note that we actually wrote really few lines of code. I have another example where we achieve the same result defining the same elements of the UI but hardwiring the values. The result is obscene and you actually lose a considerable amount of time on changing everytime all the Strings references for a particular implementation. Note also that if you are creating the grid structure runtime, and you want to provide a columns hide/show functionality, you have no choice but to use the depicted method.
We can finish this tutorial by providing the source code of our main application. I don't explain all the event handling as you should know about that, the final result is a clean, reusable and understandable code. You can see the final result following this link.
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
         xmlns:s="library://ns.adobe.com/flex/spark" 
         xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="800" minHeight="400" 
         width="800" height="400"
         applicationComplete="init()">
  <fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
    <s:ArrayCollection id="arr"/>
  </fx:Declarations>
  <mx:AdvancedDataGrid id="grid"  selectionMode="singleRow" wordWrap="true" 
             headerWordWrap="true" 
             defaultLeafIcon="{null}" alternatingItemColors="[#ffc4c4, #FFFFFF]" 
             height="354" width="800" x="0" y="46" >
    <mx:groupedColumns>
      <mx:AdvancedDataGridColumnGroup headerText="Equipo" >
        <mx:AdvancedDataGridColumn headerText="Descripcion" />
        <mx:AdvancedDataGridColumn headerText="Marca" />
        <mx:AdvancedDataGridColumn headerText="Modelo" />
        <mx:AdvancedDataGridColumn headerText="Serie" />
        <mx:AdvancedDataGridColumn headerText="Ubicacion" />
      </mx:AdvancedDataGridColumnGroup>
      <mx:AdvancedDataGridColumnGroup headerText="Empresa" >
        <mx:AdvancedDataGridColumn headerText="Nombre" />
      </mx:AdvancedDataGridColumnGroup>          
      <mx:AdvancedDataGridColumn headerText="Fecha" />
      <mx:AdvancedDataGridColumn headerText="Asignado"/>
      <mx:AdvancedDataGridColumn headerText="Terminado"/>
      <mx:AdvancedDataGridColumn headerText="Puntos"/>
      <mx:AdvancedDataGridColumn headerText="Monto"/>
      <mx:AdvancedDataGridColumn headerText="Factura"/>
      <mx:AdvancedDataGridColumn headerText="Monto Factura"/>
      <mx:AdvancedDataGridColumn headerText="Pagado"/>
    </mx:groupedColumns>
  </mx:AdvancedDataGrid>
  <mx:PopUpMenuButton id="popupmenubutton1" x="10" y="10" label="Hide/Show Columns" 
                      dataProvider="{arr}" itemClick="menu_change(event)"/>
 
  <fx:Script>
    <![CDATA[
      import mx.events.MenuEvent;
 
      private function init():void {
        var lh:MenuLeafHandler = new MenuLeafHandler();
        var t:Traversal = new Traversal(lh);
        t.traverseAndGetHandler(grid.groupedColumns);
        arr = lh.getArray();
      }
 
      private function menu_change(evt:MenuEvent):void {
        var lh:HideShowHandler = new HideShowHandler(evt.item.label);
        var t:Traversal = new Traversal(lh);
        t.traverseAndGetHandler(grid.groupedColumns);
        lh.getLeaf().visible = popupmenubutton1.dataDescriptor.isToggled(evt.item);
      }
    ]]>
  </fx:Script>
 
</s:Application>

Monday, October 17, 2011

ADF: Get social security numbers right


A common development use case is to guide users when working with input fields that require a specific input format. For example, credit card and social security number fields use character delimiters that you may want to enforce on a field. The following sample uses JavaScript to add a defined delimiter character according to a defined character.
The American social security pattern is defined as xxx-xx-xxxx. Users that type 123456789 should have the input automatically corrected to 123-45-6789 while they type. Also, the field should be protected from character input and input length larger than the provided pattern.
<af:inputText label="Social Security Number" id="it1"
              rendered="true">
  <af:clientListener
        method="handleNumberFormatConversion('xxx-xx-xxxx','-')"
        type="keyDown"/>
</af:inputText>
With the above configuration, the handleNumberFormatConversion method is called for each key stroke in the input field. Additional arguments provided to the function are the input pattern and the character delimiter.
The JavaScript code that is addressed by the clientListener on the InputText is shown below:
// JavaScript function that applies a specific format
// to numeric input. The pattern argument defines the
// input mask, e.g. xxx-xx-xxxx. The delimiter defines
// the delimiter character to add to the user input based
// on the pattern
function handleNumberFormatConversion(pattern, delimiter){
  return function(evt){
       var inputField  = evt.getCurrentTarget();
       var keyPressed = evt.getKeyCode();
       var oldValue   = inputField.getSubmittedValue();             
       //keycode 48-57  are keys 0-9
       //keycode 96-105 are numbpad keys 0-9
      
       var validKeys = new Array(48,49,50,51,52,53,54,55,
                                 56,57,96,97,98,99,100,
                                 101,102,103,104,105,
                                 AdfKeyStroke.ARROWRIGHT_KEY,
                                 AdfKeyStroke.ARROWLEFT_KEY,
                                 AdfKeyStroke.BACKSPACE_KEY,
                                 AdfKeyStroke.DELETE_KEY,
                                 AdfKeyStroke.END_KEY,
                                 AdfKeyStroke.ESC_KEY,
                                 AdfKeyStroke.TAB_KEY);
         var numberKeys = new Array(48,49,50,51,52,53,54,55,
                                    56,57,96,97,98,99,100,
                                    101,102,103,104,105); 
       var isValidKey = false;
       for (var i=0; i < validKeys.length; ++i){
          if (validKeys[i] == keyPressed) {
               isValidKey = true;
               break;
          }
       }      
       if(isValidKey){
         //key is valid, ensure formatting is correct
         var isNumberKey = false;
         for (var n=0; n < numberKeys.length; ++n){
           if(numberKeys[n] == keyPressed){
             isNumberKey = true;
             break;
           }
         }        
         if(isNumberKey){
           //if the user provided enough data, cancel
           //the input
           var formatLength = pattern.length;
           if(formatLength == oldValue.length){
           inputField.setValue(oldValue);
             evt.cancel();
           }
           //more values allowed. Check if delimiter needs to
           //be set          
           else{
             //if the date format has a delimiter as the next
             //character, add it
             if(pattern.charAt(oldValue.length)== delimiter){
               oldValue = oldValue+delimiter;     
               inputField.setValue(oldValue);
             }
           }
         }          
       }
       else{
         //key is not valid, so undo entry
         inputField.setValue(oldValue);
         evt.cancel();
       }
    }
}
The sample is for number only input. However, changing it for character or mixed input is not difficult to do. Note however that you can't use this with af:inputDate component because this component doesn't work well when setting String formatted values as the value property. (At least my debugging showed this)

ADF: Partially restricting user entry in the ADF input text - using Java Script

Here is an example. Let us assume the input text contains the following text. "You can edit the content inside { this }". In this, users should be able to edit only the content inside { }. I.e Only "this" should be editable.
To achieve this, we can use a java script method, that tracks the cursor position and ignore the user edits if the cursor position is not between the curly braces. After which, the method would be used in the client listener for the input text.
Example code snippet.



ADF: How to programmatically set focus on an input component

The af:document component has a property InitialFocusId that allows you to define the Id of an input component that should take focus when a page initially loads. But how do you set the component focus for pages that are already rendered? A use case for this is a partial submit that executes logic on the server, after which the cursor focus in the UI needs to be set to a specific input component of a page or page fragment. The solution to this use case is JavaScript that is generated on the server and executed on the client.
The simplified sample I wrote contains of three input text fields and three command buttons. Initially, using theaf:document InitialFocusId property, the cursor focus is set to the first input text field.
The command button send a partial submit to a managed bean on the server. The managed bean reads the component Id of the input text field to put the focus to from a client attribute that is defined on each command button. Using the MyFaces Trinidad ExtendedRenderKitService class, the managed bean sends a JavaScript call to the client to change the current component focus.
Important: By default, ADF Faces does not render all its user interface components as JavaScript objects. It only renders those components as JavaScript objects that have behavior, like a table that can have its columns moved. Input text components, for example, are rendered in HTML only, which means that the ADF client side JavaScript framework will not find a handle to the component unless you tell ADF Faces to create one. For this, you set theClientComponent property of the input text fields to true. This also is required for the af:document InitialFocusIdproperty to work.
Below is the managed bean code that handles the command button action and that composes and executes the JavaScript to set the client side UI focus.

 As mentioned, the command buttons in the sample have a client attribute attached that I use to determine which input component should receive focus. The managed bean calls the client attribute here:
RichCommandButton rcb = (RichCommandButton)event.getSource();
String focusOn = (String)rcb.getAttributes().get("focusField");
 In the page definition, the client attribute is defined as
<af:commandButton text="Focus Field 2" id="commandButton1"
                   partialSubmit="true"
                   actionListener="#{FocusBean.onSetFocus}">
  <af:clientAttribute name="focusField" value="it2"/>
</af:commandButton>
<af:commandButton text="Focus Field 3" id="cb1"
                  partialSubmit="true"
 actionListener="#{FocusBean.onSetFocus}">
  <af:clientAttribute name="focusField" value="it3"/>
</af:commandButton>
In your custom implementation of this use case, you for sure will have your own way of determining the next focus target. The server side code however doesn't change much.

Thursday, October 13, 2011

iOS: Official release of the new Apple iOS 5 software



Today Apple has officially released the new iOS 5 software update. The iOS 5 download links are below.  iOS 5 has over 200 new features including, messaging, notifications, and over the air updates. You can either update through iTunes or download iOS 5 IPSW and update.

Download iOS 5 Links

The download links for iOS 5 are below. After downloading you can open iTunes, shift-click on Update and select the iOS 5 IPSW file to update.
The iOS 5 update includes over 200 new features, including the following:

Notifications
§ Swipe from top of any screen to view notifications in one place with Notification Center
§ View notifications briefly at top of screen
§ View notifications from lock screen
§ Slide notification app icon to right on lockscreen to go directly to the app
iMessage
§ Send and receive unlimited text, photo, and video messages with other iOS 5 users
§ Track messages with delivery & read receitps
§ Group messaging and secure encryption
§ Works over cellular network and Wi-Fi
Note: Your browser may download it as a .zip file, if that happens just rename the .zip to .ipsw.

§ iOS 5 Download – iPad 2 (Wi-Fi) - iPad2,1_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPad 2 Wi-Fi + 3G (GSM) - iPad2,2_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPad 2 Wi-Fi + 3G (CDMA) - iPad2,3_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPad (Wi-Fi and Wi-Fi + 3G) - iPad1,1_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPhone 4 (GSM) - iPhone3,1_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPhone 4 (CDMA) - iPhone3,3_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPhone 4S - iPhone4,1_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPhone 3GS - iPhone2,1_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPod touch (4th generation) - iPod4,1_5.0_9A334_Restore.ipsw
§ iOS 5 Download – iPod touch (3rd generation) - iPod3,1_5.0_9A334_Restore.ipsw

Steps to install iOS 5 Download

1. Download iTunes 10.5 from here.
2. Download the iOS 5 firmware.
3. Install through iTunes by shift/option-clicking Update and selecting the IPSW file you downloaded.

Jailbreak iOS 5 Download Information

You can currently jailbreak iOS 5 (tethered only, which means you’ll need to jailbreak each time you reboot your device), but no untethered  jailbreak for iOS 5 has been released yet. You should wait for an untethered jailbreak to be released.