Author Archive: Mike Hodgson

Why HTML forms are [still] important

Web designers have access to countless rich media tools and social applications, why should they still care about the humble form?

How customers interact with you

Think about the last dozen web sites you visited. How many asked you for information? Whether it’s an account registration, a comment on a blog post, a web forum or a survey, chances are there was a form to gather your information.

HTML forms are important components of modern websites. It’s how your customers tell you who they are, sign up for services and purchase your products. They are the major way your users communicate with you.

If you are truly interacting with your web site’s users you will need to gather some information about them at some point and most of the time this is done through a form.

But people hate forms

So why haven’t HTML forms gotten the attention they deserve? I blame much of it on crappy design and inappropriate use. There are some of nice tools out there that make creating HTML forms easy, unfortunately the forms created with these tools is often not well thought out.

Badly designed or badly placed forms can cause user frustration, taking them out of the web sites experience. One of the worst examples of this is the popup survey. If I’m reading your site trying to find a recipe for the ten pounds of zucchini that are in my garden, I don’t want to fill in a survey about your new credit card cross promotion.

Regardless of your form there are some basic things that you should consider:

  • Context – ask for the right information at the right time. Sure you need the customer’s shipping address, but ask for it at the right time (and pre-fill it if it’s a returning customer).
  • Functionality – the form should work as users are expecting it to. I know it sounds silly, but there is no easier way to lose audience than to fill in a form and not have the submit button work (or worse have it reset the form).
    This also means you should follow the standard conventions for forms. For example; if you are providing an exclusive choice, use a radio button and not a check box. When users see a check box they assume that they can choose multiple items.
  • Security – Your gathering, potentially sensitive, customer information. It is extremely important to ensure that that data is handled appropriately.
  • Design – This is far too broad a subject for this one post, but needless to say you should give the same consideration to form design as you would any other aspect of the site.

Think small

The vast majority of web based forms are simple, with only a handful of fields. By no means are these insignificant, the data gathered here drives the customer experience for many web sites.

In fact, I would argue that these are more important as data gathering devices than the large complex forms, at least it terms of web design:

  • They are completed more often. People are more inclined to fill out a four field form than a four page one.
  • They are easier to build and update. Less complex forms are easier to put together and deploy, meaning that there is a better chance that they will see the light of day
  • The total amount of information gathered is several times that of complex forms. Think of all of the little bits of information you are asked for in the course of a day.

Your Thoughts

What are your thoughts?  Do you feel that HTML forms have a place in the modern web design toolkit?  Is your organization using HTML forms to interact with your audience? 

 

Completely unrelated side note:

A few of you may have noticed that I have changed the name of this blog from “Steampowered” to “Enterprise…I Think”.  There are a couple of reasons for this:  1 – To avoid confusion with another web site. 2 – My role at Adobe has recently changed and the change in the blog’s focus will reflect that change.   Cheers,  Mike.

Dispatching Events from an ActionScript Class

A little while ago I was working on a project that required data from an external source.  In trying to follow good development practices, I divided the interface code for the external source into a separate ActionScript class.  No problems there, but the external source may not respond to a request immediately.   This means that my ActionScript class is asynchronous, and will need to tell the calling object when the data is ready.

I’ve used Flex long enough to know that when I see anything asynchronous, I will be dealing with the event model.   “No problem.”, says I,  “I’ve used events in MXML components before.  Add a meta-data tag, dispatch the event using dispatchEvent, and add a listener in the calling object.  Bob’s your uncle, its done.  I can even create a small custom event to be really fancy.  The syntax is all in the help files.

Alas, it was not so easy.   When using MXML components, the dispatchEvent function is a property of the mx.core.UIComponent object, but pure ActionScript classes aren’t derived from the UIComponent and therefore don’t have access to the dispatchEvent function.  So how do I dispatch the event form an ActionScript class?

It took me quite a while to find the answer to this simple question.  If you search the internet, there are tons of examples of using the event dispatcher in MXML components.  There are not that many when it comes to using pure ActionScript classes.  The problem isn’t that its difficult to do, its just hard to find how to do it amongst the thousands of results returned in a search.

So in the interest of spreading the knowledge, here is how to dispatch a custom event from a pure ActionScript class.

Source code can be found here.

 

The parts list:

The solution consists for three parts:

  • The ActionScript class.  This is a pure ActionScript object (no MXML) that will perform an asynchronous task.  In this case it will make an external call to get data.
  • The custom event.  This is a custom build event object that will be thrown by the ActionScript class when the asynchronous task is complete.
  • The calling object (aka parent).  This is the MXML, class, etc.  that will use the ActionScript class to get data.

The order of operations is quite simple as well:

  1. The parent object will add an event listener to watch for the custom event
  2. The parent object will then call a function in the ActionScript class
  3. The ActionScript class’ function will perform an asynchronous task.   This may require the addition of its own event listener to know when the task is complete.
  4. The ActionScript class will dispatch a custom event that includes data from the asynchronous task.
  5. The parent object will get the data from the custom event and do something with it.

Here’s a simple diagram that shows what happens:

eventModel

 

The code:

To keep from having to jump around, lets start looking from the bottom up:

The Custom Event

I could have easily used the existing Event object, but a custom event allows me a bit more freedom.  I can create my own event types as well as having my own data objects passed back in the event.

  • The class is fairly simple, it extends the flash.events.Event object
  • There are three types of event that can be returned:
    • EXTERNALDATA_DATAREADY – everything is good and the data is ready to go
    • EXTERNALDATA_NODATAFOUND – there is no data found
    • EXTERNALDATA_ERROR – something went wrong
  • There is an attribute that holds the data called externalData, which uses the ActionScript convention around getters and setters.
  • The constructor has been modified to include the event type and the data itself.

Here is the source code:

package events

{

import flash.events.Event;

public class ExternalDataEvent extends Event {

public static const EXTERNALDATA_DATAREADY:String = ‘ExternalDataReady’;

public static const EXTERNALDATA_NODATAFOUND:String = ‘ExternalDataNoDataFound’;

public static const EXTERNALDATA_ERROR:String = ‘ExternalDataError’;

private var _externalData:XML;

public function ExternalDataEvent(type:String, exData:XML, bubbles:Boolean=false, cancelable:Boolean=false) {

super(type, bubbles, cancelable);

this.externalData = exData;

}

public function get externalData():XML {

return _externalData;

}

public function set externalData(value:XML):void {

_externalData = value;

}

}

}

The ActionScript Class

The ActionScript class serves as the model for this project.  It is called by the parent object, performs an asynchronous call, and returns the result in an ExternalDataEvent event.

In this case I’m just making a simple HTTP request to load an external XML file, but this could just as easily been an SQL call to a database, a web service request, a LiveCycle Data Services call or any other asynchronous request.

  • The class extends flash.events.EventDispatcher. This is very important.   Because the ActionScript class is not an MXML object, it does not have access to the mx.core.UIComponent object.  By extending the EventDispatcher class we can now dispatch our custom event using the dispatchEvent function.
  • The class has one public method readData
  • Since the data is loaded from an HTTPService (an asynchronous event), we need a listener for the returned data.  This is done by the loadData function.
  • The loadData function fires our custom event.  Which event depends on the data.  During the call the type and data are set into the event itself
  • There is also an error function, fault, as a basic error trap.

Here is the source code:

package model

{

import events.ExternalDataEvent;

import flash.events.EventDispatcher;

import flash.events.Event;

import mx.rpc.events.FaultEvent;

import mx.rpc.events.ResultEvent;

import mx.rpc.http.mxml.HTTPService;

public class ExternalData extends EventDispatcher {

private var HttpService:HTTPService = new HTTPService();

private var xmlURL:String = new String();

public function readData(dataUrl:String):void{

this.load(dataUrl);

}

private function load(dataUrl:String):void{

xmlURL = dataUrl;

HttpService.resultFormat = “e4x”;

HttpService.addEventListener(ResultEvent.RESULT,loadData);

HttpService.addEventListener(FaultEvent.FAULT,fault);

HttpService.url = xmlURL;

HttpService.send();

}

private function loadData(event:ResultEvent):void{

if (event.result != null){

dispatchEvent (new ExternalDataEvent (ExternalDataEvent.EXTERNALDATA_DATAREADY,event.result as XML));

}else {

dispatchEvent (new ExternalDataEvent (ExternalDataEvent.EXTERNALDATA_NODATAFOUND,null));

}

}

private function fault(event:FaultEvent):void{

trace (“ERROR: Problem loading XML data. Stack Trace follows:”);

trace(event.message);

dispatchEvent (new ExternalDataEvent (ExternalDataEvent.EXTERNALDATA_ERROR,null));

}

}

}

 

The Parent Object

Finally we have the parent object.  In this case I built a simple MXML application that will call the ActionScript class and get the returned data from the custom event.

  • The application consists of a button and a text area.  When the button is clicked a click handler function is fired and the retrieved data is displayed in the text area.
  • The click handler adds three listeners.  One for each type of event that can come from the custom event object.
  • The click handler also sets some data and calls the public method in our ActionScript class.
  • The event listeners will be triggered by the ActionScript when it dispatches the custom event (with data).
  • The event listeners set the text of the text area field

Here is the source code:

<?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=”955” minHeight=”600” xmlns:model=”model.*>

<fx:Declarations>

<model:ExternalData id=”externalData/>

</fx:Declarations>

<fx:Script>

<![CDATA[

import events.ExternalDataEvent;

import model.ExternalData;

protected function getDataBtn_clickHandler(event:MouseEvent):void {

externalData.addEventListener(ExternalDataEvent.EXTERNALDATA_DATAREADY,dataReady);

externalData.addEventListener(ExternalDataEvent.EXTERNALDATA_NODATAFOUND,noDataFound);

externalData.addEventListener(ExternalDataEvent.EXTERNALDATA_ERROR,fault);

var dataURL:String = "\\assets\\testData.xml";

externalData.readData(dataURL);

}

private function dataReady(event:ExternalDataEvent):void{

dataResults.text = event.externalData.toXMLString();

}

private function noDataFound(event:ExternalDataEvent):void{

dataResults.text = "No Data Found";

}

private function fault(event:ExternalDataEvent):void{

dataResults.text = "Data Fault";

}

]]>

</fx:Script>

<s:Button id=”getDataBtn” x=”31” y=”40” label=”Get Data” click=”getDataBtn_clickHandler(event)”/>

<s:TextArea id=”dataResults” x=”88” y=”86/>

</s:Application>

Results

When the user clicks on the Get Data button the ActionScript class is called.  Data is loaded and the custom event is dispatched.  The parent application is watching for the custom event and it populates the text area with the data from that event.

If all goes well, here’s what you should see once you click on the button:

image

 

Like I said earlier, its not terribly difficult.  At least its no more difficult than doing custom events using MXML components.   There just doesn’t seem to be too many sample using pure ActionScript classes rather than visual based components.

Source code can be found here.

Mosaic 9.5 Content Authorization

Mosaic 9.5 has allows control of content based on authorization rules stored in a policy file.  This means we can control access to an application, catalog, tile or other resource by setting permissions in the policy file.  We can also combine the permissions in different ways to control the user experience.

This is a very powerful feature that allows the developer or administrator to control resource access at a very fine grained level.  It also can be an incredibly maddening feature when it is not configured properly.  In this post I’ll try to demystify some of the magic behind authorization.  Hopefully this will make your configuration a bit less stressful.

The rules for the authorization of Mosaic content is stored in a policy file which is deployed to Mosaic as you would other resources.  The application and catalog descriptors will have a Policy Reference  that indicates what policy file(s) contain the rules for the resource.  The policy reference is optional, and if it is absent it means that there are no specific rules for that resource. There may be more than one policy file deployed to your server.

The policy file uses the OASIS eXtensible Access Control Markup Language (XACML) notation to define the authorization rules for each resource.  This allows you to set up some incredibly complex rules for authorization, but it also allows you to get a little too creative with the rules.  Its like juggling chainsaws.  Its really cool when it works, but if something goes wrong there will be a big mess to clean up.

The rules of authorization:

These are some general rules of thumb that will help you keep the authorization functionality from driving you crazy:

  1. Mosaic evaluates the authorization at runtime.
    When a user accesses an application, Mosaic reads the application descriptor and assembles the application before sending it to the client.  While this allows you to update rules with out recompiling code, it also means that large, complex policy files can cause performance issues.
  2. The evaluation of permissions for each resource is independent of that for other resources.
    When Mosaic determines that a resource is needed, it checks the policy file to see if the user has access (assuming there is a policy reference).  Then the next resource is similarly checked.  Mosaic  does not maintain state information between the calls, so  each resource  request is judged on its own merits.  For example, say a tile is used by two different applications. The tile  rules are evaluated separately from the evaluation of the applications.  In other words; If you can read a tile, you can read that tile regardless of what application it is in.
  3. If a resource is inside of another resource, you need access to the parent resource as well.
    Although each resource is evaluated on its own, for practical purposes, there is a evaluation order.  You can consider the evaluation order as application, catalog, view template, panel template and tile (or other catalog resource) and that these can be treated as an AND operation.
    What that means is that if you have access to the tiles and not access to the app, you won’t see anything.  Although the tile rules may say you have read access, the tiles have no container into which they can be put.
    For example; to see a tile the user must have access to the application AND the catalog AND the tile (1&1&1=1).  If any of these are denied, you will not see the tile.

In addition, there are two corollaries to the rules:

  1. What happens if there is no policy?
    This can happen if the resource (application, catalog, tile, etc.) has no policy file reference.  Since there is no rule, Mosaic assumes access is granted.
  2. What happens if there is a policy, but no rule applies?
    This can happen if there is no specific rule in the policy that applies to the resource for that user.  According to the XACML standard, this results in an indeterminate result.  In this case Mosaic falls back to the overall Mosaic authorization setting (also known as the base setting). This is set in the mosaic-context.xml file using the denyWhenIndeterminate property.  If the value is set to true then any indeterminate requests will be denied.
    One thing to watch for is an error in your XACML policy file.  If there is a mistake or typo that is still legal XACML, an indeterminate state can be returned.  For example, if you make a mistake in an attribute entry then the rule may not execute and an indeterminate result will be returned.  If the denyWhenIndeterminate property is set then no user will be able to access the resource.
    For these reasons I recommend adding a “catch all” rule that will apply when no others do.  It will make debugging your policy file much easier.

An Example

Lets take a look at a simple sample to see how this works.  The source for this example can be downloaded here.

The test consists of the following:

· Two user roles were added to Mosaic. Each role has one unique user:

o <security:user name=”r1″ password=”password” authorities=”ROLE_MOSAIC_R1″/>

o <security:user name=”r2″ password=”password” authorities=”ROLE_MOSAIC_R2″/>

· Two applications – App1 and App2

· One catalog – AppCatalog

· Two tiles – Tile1 and Tile2

· AppCatalog has entries for Tile1 and Tile2

· App1 uses Tile1 and Tile2 from the AppCatalog

· App2 uses Tile1 and Tile2 from the AppCatalog

· There is one policy file – ControlPolicy

· App1 and App2 contain a reference to ControlPolicy

· AppCatalog contains a reference to ControlPolicy at its root

· The Tile1 and Tile2 entries in the AppCatalog each contain a reference to ControlPolicy

When the applications are accessed using the owner’s account (a super user with all access granted) they look like the following:

App1 with no authorization rules:

image

 

App2 with no authorization rules:

image

 

Policy Rules:

Rules for R1:

· Read access for App1

· Read access for AppCatalog

· Read access for Tile1

Rules for R2:

· Read access for App2

· Read access for AppCatalog

· Read access for Tile2

Rules for resource owner:

· All actions to all resources

In addition there is a “catch all” rule to catch anything that does not apply to the above. This rule is set to deny.

Results

The following are the results when the two users attempt to access the two applications with the above listed rules:

For user R1:

· When accessing App1, user R1 sees the app and Tile1. He does not see Tile2

o The user has access to the app, the catalog and Tile1 (1&1&1=1) so he sees Tile1

o The user has no access to Tile2 (1&1&0=0) so he does not see Tile2

image

· When accessing App2, user R1 is denied access.

o The user has no access to the app, but does have access to the catalog and Tile1. Since he can’t see the app, access to the catalog and tile are not relevant (0&1&0=0)

image

For user R2:

· When accessing App1, user R1 is denied access

image

· When accessing App2, user R2 sees only Tile2. He does not see Tile1

image

 

Compound Rules

What happens if you want to do more complex rules on combinations of resources?  As I said earlier, Mosaic requests authorization on individual resources and does not pass the state information during the request.  If you want a combo – say only show Tile 2 if Tile 1 is present – can you do it?  You can, but you need to be a bit creative.

You need to find a way to combine the two tiles into a single resource on which Mosaic can check the authorization.  Fortunately, this can be easily done using view and panel templates.   In the catalog you can combine the tiles you need into a single view/panel.  The application will reference the view/panel template and not the tiles individually.  The policy file will include a resource entry for the view/panel as well as the tiles, catalog and application.

Of course the rules must be setup so the user has access to the tiles as well as the view/panel.

Updating Mosaic 9.5 Tooling

If you are developing Mosaic applications or tiles then you have probably looked at the LCM plugin for Flash Builder 4*.  This plugin was developed for use with Mosaic 9.0, but what if you are developing on Mosaic 9.5.0.1 or 9.5.0.2?   You need to update a coupe of things in the tooling so the SDK and the deployment client are compatible with later versions of Mosaic. 

In this discussion the following conventions are used:

{fb_install} – refers to the installation location of your FlashBuilder 4.  For example:  C:\Program Files (x86)\Adobe\Adobe Flash Builder 4

{Mosaic_install}  – refers to the installation location of your Mosaic server.  For example: C:\Adobe\Mosaic 9.5.0.2

{plugin SDK} – refers to the location of the plug in’s version of the Mosaic SDK files.  In my case it is:  C:\Adobe\Mosaic\Mosaic 9.5.0.1\sdk\com.adobe.livecyle.ria.mosaic\9.5-gm.

To  Find what the plugin is using for an SDK folder:

    • Launch FlashBuilder 4
    • Choose Window –> Preferences
    • Choose General -> Workspace -> Linked Resources
    • Look for the MOSAIC_9_5_GM_SDK entry

 

I strongly advise you to backup any files you will change.

1.  Update the deployment client:

  • If FlashBuilder 4 is running, stop it.
  • Locate the deployment client that comes with the plugin and rename it so it will no longer be referenced:
    • Go to:  {fb_install} \configuration\org.eclipse.osgi\bundles\116\1\.cp\lib
    • Find the mosaic-ant-tasks.jar file
    • Rename it to mosaic-ant-tasks.jar.dontUseMe
  • Find the updated deployment client and copy it to the plugin folder:
    • Copy {Mosaic_install} \bin\mosaicTasks.jar to {fb_install} \configuration\org.eclipse.osgi\bundles\116\1\.cp\lib
    • Rename the mosaicTasks.jar file to mosaic-ant-tasks.jar

2.  Update the plugin SDK:

  • Back up the plugin SDK:
    • Go to {plugin SDK}
    • Move the css, flex and javascript folders to somewhere safe.  Leave the sdkinstall.properties file alone
  • Update the plugin SDK
    • Copy the {Mosaic_install} \sdk\css folder to {plugin SDK}
    • Copy the {Mosaic_install} \sdk\flex folder to {plugin SDK}
    • Copy the {Mosaic_install} \sdk\javascript folder to {plugin SDK}
  • Start FlashBuilder 4
  • Recompile any projects that were created with the old Mosaic SDK:
    • Choose Project –> Clean
    • Choose Clean all projects
    • Click OK.  Wait while the swfs are regenerated.

 

* Please note:  The LCM plugin was developed is provided as unsupported software.  Adobe hopes that you find it useful, but as the terms of use state: …PROVIDED BY ADOBE UNDER THESE ADOBE LABS TERMS OF USE “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,…

View Master

LiveCycle Mosaic ES2.5 has some very useful features for allowing users to customize their environment.  Some of the most useful revolve around the view object and its related view context.  With a bit of creative programming we can take advantage of the view object and allow users to create their own, customized design.

In this post I’ll look at a fairly common request for a customizable Mosaic app and see how it can be done while using many of the view features.

The source code used in this post can be found here.

Scenario

I’ll start with a short description of what we want from the app:

  1. An IT Request application with four tiles to begin (more may be added later):
    • Request List – has a list of currently active requests
    • Request Details – contains details about a single request
    • Customer Details – contains details about the customer to which the request applies
    • Customer History – contains information about a customer’s previous requests
  2. When a user selects an item from the request list the other tiles will update with relevant request/customer information
  3. User’s can customize their app to include any or all of the tiles.
  4. User’s can open multiple copies of the work space to work on different requests. 
  5. User’s can save their customized work space
  6. If a user has a customized work space, then it should come up when they login.
  7. If a user does not have a customized work space then a default will be presented.  The default will include the Request List and the Request Details.
  8. When a user’s customized work space is opened then the last request they were working on should be selected

Okay, that should do for now.

The Tiles

First we need to build the four tiles that make up the bulk of the application.  I won’t go too much into the general tile development, but instead I’ll concentrate on the “special” things I need to do to make the other requirements work.

Basically these are small Flex apps that happen to use the Mosaic API.  In my case I built them as ModuleTile files since they are all built on the same version of the Flex SDK.   Since this is a sample, I’m just going to read the data from a couple of local XML files using an HTTP Service.  No need to get too fancy here.

  • The Request List (RequestList.mxml) will be a simple data grid that shows the list of requests from the XML file. 
  • The Request Details (RequestDetails.mxml) is a screen that shows details about a single request.  Its pretty much a form.
  • The Customer Details (CustomerDetails.mxml) is a simple display screen that shows information about a single customer.
  • The Customer History (CustomerHistory.mxml) is a list of a single customer’s previous requests.

The construction of these tiles is pretty strait forward MXML development.

Inter-tile Communication

Requirement: When a user selects an item from the request list the other tiles will update with relevant request/customer information.

Mosaic has several methods to exchange data between tiles (see video for more), but there are a few requirements that lend themselves to using the view context for inter-tile communication:

  • User’s can open multiple copies of the work space to work on different requests.  –  This means that tiles in the same work space need to share data, but they shouldn’t interfere with tiles in another work space.  We can equate a work space with a Mosaic view. Then we can read that as the data needs to be exchanged between tiles in the same view and not tiles in another view.  Coincidentally, this is exactly how view attribute data works.
  • When a user’s customized work space is opened then the last request they were working on should be selected. – This means that the data the user is looking at needs to be saved and reloaded when the view is opened.  Fortunately the view context data is saved when the view is saved.  The tile just needs to be built to make use of that data. The one restriction is that the view data must be a primitive type – complex data types cannot be saved.

Let’s look at how the use of the view context data attributes are coded to meet these requirements.

Sending Data

The Request List tile will be broadcasting data to the other tiles.  When a user clicks on an item from the data grid (id=”grid”) two data attributes will be set – the caseNumber and the customerName.  These will be picked up by the other tiles. 

To send view data to the other tiles in the current view you would use the parentView.context.setAttribute method.  The first parameter is the attribute name, the second is its value.  Here is the code from the Request List tile:

private function selectRecord():void{
    var caseNumber:String = grid.selectedItem.caseNumber;
    var customerName:String = grid.selectedItem.customer;
    parentView.context.setAttribute(“caseNumber”,caseNumber);
    parentView.context.setAttribute(“customerName”,customerName);               
}

Receiving Data

The other three tiles need to receive the data and then do something with it.  In this case they will get related XML data and put it on the screen.

To meet the requirements the tile must check for the data when it loads (thus meeting the requirement to open the last request).  It must also watch for changes to the data so the tile is updated when the user selects a different request.

To get the value of a view data attribute I will use the parentView.context.getAttribute method.  The only parameter is the attribute name and the result is the contents of the data.

Mosaic also has a listener that can watch for changes in a view context attribute. The  parentView.context.addAttributeWatcher function works using the standard Flex event model in that it will fire a function when the attribute data changes.  You can then use the getAttribute function to get the data.

The following code is from the Request Details tile, but the other two tiles use similar techniques for getting the view context data.  The init function is called on the creationComplete event of the tile:

import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.events.PropertyChangeEvent;
           
[Bindable] private var currentRequest:XML;           
[Bindable] private var caseNum:String;
           

private function init():void{   
    parentView.context.addAttributeWatcher(“caseNumber”,onChange);  //watch for changes to the data
    onChange();                                                     //check for data on load
}
           
private function onChange(event:PropertyChangeEvent=null):void{
    caseNum = parentView.context.getAttribute(“caseNumber”);   //get the data
    if (caseNum != null)                                       //if there is data, then do something with it
         HttpService.send();
}      

Adding Tiles to a View

Requirements: User’s can customize their app to include any or all of the tiles
                             User’s can open multiple copies of the work space to work on different requests.

This requirement implies that the application needs a way to allow the user to create a new view and to add available tile to that view as they want.  Creating a new view is easy, as Mosaic has a built in button on the view skin to add a new view (the “+” button in the default skin). 

Adding tiles to the view takes a bit more effort.  Mosaic 9.5 doesn’t have an out of the box way to do this, but it does provide the APIs so it can be coded.  I need somewhere to put this code and the user controls.  It doesn’t make much sense to put it in any of the four tiles, as the user may not have add that tile to their view.  For this example I’ll add another tile called Header (Header.mxml).

I’ll need something to hold a list of the available tiles.  To be more flexible, I will also add the catalog name to that list as well.  That will allow me to add tiles from other catalogs into the view later on.    I created a simple class TileInfo to hold the tile and catalog name for each tile.  Then I created an array collection of the TileInfo objects and I populate that array collection when the Header tile is initialized (creation complete):

private function init():void{               
    //set the list of tiles (and their catalogs) that a user can add
    tileCollection.addItem(new TileInfo(“RequestList”,”ViewDemo_Catalog”));
    tileMenuCollection.addItem(“Request List”);
               
    tileCollection.addItem(new TileInfo(“RequestDetails”,”ViewDemo_Catalog”));
    tileMenuCollection.addItem(“Request Details” );
               
    tileCollection.addItem(new TileInfo(“CustomerDetails”,”ViewDemo_Catalog”));
    tileMenuCollection.addItem(“Customer Details”);
               
    tileCollection.addItem(new TileInfo( “CustomerHistory”,”ViewDemo_Catalog”));
    tileMenuCollection.addItem(“Customer History”)

}   

One of Header’s jobs will be to have a control that a user can use to add tiles.  I used a simple drop down (bound to the array collection) with the tile names and a button for the user to add the selected tile.

headerControls

When the user clicks on the Add Tile button a function executes that will add the tile.  When the function fires the code must first do the following:

  1. Locate the proper catalog
  2. Locate the proper tile in the catalog
  3. Find the view and panel that the user is looking at
  4. Add the tile to the view

As part of step 3 we should make sure that there is both a view and panel into which we can put the tile.  If either of these are missing, we can pull a pre-configured one out of the catalog.  By creating a pre-configured view and panel template, the layout can be defined ahead of time.  This will save a bit of coding.  In this case I created a view template called addView and a panel template called addPanel in the catalog.

The button handler in the Header tile looks like:

protected function addTile_clickHandler(event:MouseEvent):void            {
                if (tileDropDown.selectedIndex != -1){
                    var tileInfo:TileInfo = tileCollection.getItemAt(tileDropDown.selectedIndex) as TileInfo ;
                   
                    //get the tile
                    var cat:ICatalog = mosaicApp.getCatalog(tileInfo.catalogNm);
                    var tileToAdd:ITile = cat.getTile(tileInfo.tileNm);
                   
                    var view:IView = this.currentView();
                    var panel:IPanel = this.currentPanel(view);                       
                   
                    panel.addTile(tileToAdd);
                }
            }

This calls two functions to find (or add) the current view (currentView) and panel (currentPanel).  To determine if a view or panel is the one that the user is using, I check each view/panel for the displayed flag (true means that it is the current one).

The following is the function for determining the current view.  The panel function is similar (you can see it in the source code).

                   /**
             * find the current view.  If not found, then load one from the catalog
             **/
            protected function currentView():IView{               
                var currentView:IView;
               
                //find the current view by looking at the displayed flag in each view
                var viewArray:Array = mosaicApp.views;
                for each (var searchView:IView in viewArray){
                    if (searchView.displayed){
                        //found view
                        currentView = searchView;
                        break;
                    }
                }   
               
                //not found, so go into the catalog and get a default view
                if (currentView == null){
                    var catalog:ICatalog = mosaicApp.getCatalog(“ViewDemo_Catalog”);
                    currentView = catalog.getView(“addView”);
                    mosaicApp.addView(currentView);
                    currentView.display();
                }
               
                return currentView;
            }
           
           

Saving and Loading Views

Requirements:   User’s can save their customized work space
                                  If a user has a customized work space, then it should come up when they login. 
                                  If a user does not have a customized work space then a default will be presented.  The default will include the Request List and the Request Details.

The view skin has a control that allows users to save a view at any time:  clip_image002. Views can also be saved using the IView.save API.  Views are saved on the server and are tagged to the user’s account.  In this case I’ll let the user save the view using the built in controls.

Views can be loaded into an application either by using the organizer (added to the application’s xml file using the organizer element), or by using the API.  The organizer is an element added to the application’s xml definition.  It shows a list of the user’s saved Views and allows a user to add the view to the application at any time.

The requirement, however, state that the app should load the user’s view and if that does not exist, load the default view.   This will require loading the correct view using the API.  To add a view using the API you first have to find the view in the mosaicApp.userViews array, then add it to the application using the mosaicApp.addView method.   I could put the default view, with its panels and tiles, directly into the application’s XML file.  The problem with that is the default view will always load because Mosaic loads the application contents when the user accesses the app.    There will be no way to intercept it and show the user’s saved view.  In this case its better to open the view (default or saved) using the API. 

This means that the application’s XML file will not have any of the four tiles.  It will have the Header tile, which will contain the API calls to load the proper view. 

The application xml file looks like:

<?xml version=”1.0″ encoding=”UTF-8″?>
<app:Application name=”ITRequests” label=”IT Requests”
xmlns:view=”http://ns.adobe.com/Mosaic/View/1.0/”
xmlns:catalog=”http://ns.adobe.com/Mosaic/Catalog/1.0/”
xmlns:tile=”http://ns.adobe.com/Mosaic/Tile/1.0/”
xmlns:crx=”http://ns.adobe.com/Mosaic/CRXTypes/1.0/”
xmlns:app=”http://ns.adobe.com/Mosaic/Application/1.0/”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://ns.adobe.com/Mosaic/Application/1.0/ file:///C:/Adobe/Mosaic/Mosaic%209.5.0.1/docs/schemas/application.xsd”>

    <crx:Metadata>
        <crx:Description>ITRequests</crx:Description>
    </crx:Metadata>
    <app:Shell name=”ITRequests” label=”IT Requests”>
        <catalog:CatalogReference name=”cat” uri=”ViewDemo_Catalog”/>
        <view:Organizer visible=”false”/>
        <tile:TileReference catalog=”cat” name=”Header” label=”Header” width=”100%” height=”80″/>
        <view:ViewManager width=”100%” height=”100%”>
        </view:ViewManager>
    </app:Shell>
</app:Application>

Notice that I did add a ViewManager, this is necessary because Mosaic needs something to control the views that I will add later.

Now I need to add some code to the Header tile so it can load the proper view.  I’ll need to check to see if there are any saved views for the user.  If there are, then I add them to the application.  If not; then I’ll call another function to load the default view.  

           /**
             * check to see if the user has any saved views.  If so
             * bring them up.  If not, bring up the default
             */
            protected function getUserViews():void{               
                var userViews:Array = mosaicApp.userViews;
                for each (var view:IView in userViews ){
                    mosaicApp.addView(view);   
                    showDefaultBtn.visible = true;
                }
                if (userViews.length == 0){
                    showDefaultView();
                }
            }
            /**
             *  show the default view
             */
            protected function showDefaultView():void{
                var catalog:ICatalog = mosaicApp.getCatalog(“ViewDemo_Catalog”);
                var defaultView:IView = catalog.getView(“defaultView”);   //load a view template called defaultView from the catalog
                mosaicApp.addView(defaultView);
                showDefaultBtn.visible = false;
            }

To make sure this happens when the app first gets loaded, I’ll add a call to the getUserViews(); function to the Header’s init function.

I could have easily done this in one function, but I wanted user’s that have a saved view to “reload” the default one.  To do that I added a button (showDefaultBtn) that will fire the showDefaultView function.  If the default view is there, I want the button to be invisible.

Conclusion

By taking advantage of the Mosaic view features – inter-tile communication, view layout saving, view data saving and view related APIs – you can build a highly customizable application.  This will allow your users to have the freedom to set the system up the way they want.

The source code used in this post can be found here.

Server Side PDF Flattening*

This blog entry is based on an internal document I wrote some time ago.  I’ve updated it for the current release of LiveCycle ES2.5 and cleaned it up a bit so it is more accessible to an external audience.

*Please note that the title contains a purposeful anachronism. Although the term “Flattening” has entered the vernacular, most PDFs are not really transformed into a flat PDF. Except in limited special cases, the Form is re-rendered as a flat PDF.

 

There has been much confusion around the ability of LiveCycle ES/ES2/ES2.5 to create flat PDFs from various types of interactive PDF forms. This has been exacerbated by functions added to LiveCycle ES Assembler which includes the ability to remove XFA (NoXFA) and form (NoForm) capabilities from a PDF. Specifically, there have been many questions, rumors and theories as to how flat PDFs can be created with and without LiveCycle ES Output.

Despite the ability of various LC components to create flat documents in certain cases, the most comprehensive application for creating flat PDFs is LiveCycle ES Output. As you will see there are certain circumstances where Output is not required to create a flat PDF.  However; these are specific circumstances.  The decision to propose a non LC Output solution must be taken carefully with understanding of the limitations that will be imposed being understood by the development team and customer. This will avoid the trap of what worked in a simple proof is not working when the customer proceeds with the actual application.

This post lays out these limitations and provides some guidance as to when Output is required.

Common Definitions

The following terms are used throughout this document. You shouldn’t consider these to be tremendously technically accurate, but they will work for the purposes of this discussion. 

Interactive Form – A form that can be filled in and potentially signed with a definition of the form in XFA and the data stream in XML.

Non-interactive Form – This is an interactive form with fields locked. It still has all of the XFA and XML in it, but the fields are all locked to be read-only.

Flat PDF – A PDF with no XFA stream and no non-signature elements. Basically there are no fields in the document.  It is important to note that a “Flat” PDF may still have some layers, such as the comment layer.  In this case the flatness refers to the lack of data fields.

Static PDF – A PDF which contains an XFA stream and the form layout does not change. Static forms may be interactive (a user can still fill in fields). If a dynamic XDP is rendered with LiveCycle Forms with the Render At Client option set to “No” then the resulting PDF is no longer dynamic – it is now static and behaves like any other static PDF.

Dynamic PDF – Dynamic PDFs allow the layout of the form to be altered either through user interaction or through script. An example is a form that adds subforms based on a user input. If a static XDP is rendered with LiveCycle Forms with the Render At Client option set to “Yes” then the resulting PDF is no longer static – it is now dynamic and behaves like any other dynamic PDF.

Acroform – A non-XFA based PDF form, usually created directly in Adobe Acrobat (as opposed to using LiveCycle Designer).

Artwork or XFAF – A PDF form created with from a flat PDF document using the “Create an Interactive Form with Fixed Pages” option in designer. For the purpose of this document Artwork PDFs operate the same as static PDFs.

Different Methods

There are a variety of ways to create a non-interactive form out of an interactive form using Adobe LiveCycle ES/ES2/ES2.5. The use of these different methods depends on the customer process:

  • Assembler – Assembler can invoke a DDX operation that can have either a noXFA or noForms tag. The result of both of these operations is to turn an interactive PDF into a flat PDF
  • DocConverter – DocConverter includes a feature (Convert to PDF/A) that will convert PDFs to a PDF/A format. PDF/A documents are flat PDFs with additional archival restrictions
  • Output – LiveCycle Output includes a transformPDF feature that, amongst other things, can create flat PDFs.

What works and what doesn’t

The following matrix lists what works (Y) and what does not work (N) when you try to convert interactive PDF documents to flat PDFs.

whatWorks

Notes:

  • [2] With LiveCycle ES, if a PDF (XFA or Acroform based) is merged with data using LiveCycle Forms (or Form Data Integration), the resulting document is not fully rendered. If the resulting PDF is processed with Assembler and the NoXFA or NoForms tags are used then the resulting PDF will have no data. The reason the PDF is not re-rendered is to increase server performance. The solution is to use LiveCycle Output to render the flat PDF directly instead of using a combination of Forms and Assembler.  I understand that this was changed with LiveCycle ES2, so it should not be a problem if you are using a more recent version of the product.
  • Artwork based PDFs work in the same way as other static PDFs.
  • Some developers have attempted to use the toPS operation to convert an interactive PDF into a PostScript file with the intention of converting the PS file back to a flat PDF using LiveCycle Generator. This will not work as toPS only works with flat PDFs.

Explanation

Dynamic PDFs require regeneration of the layout because they contain dynamic XFA. Only LiveCycle Output ES and LiveCycle Forms ES (Forms can only generate interactive PDFs so is not applicable in this case) include the XFAForm.exe application.  XFAForm.exe is called behind the scenes through the use of the LiveCycle services and is used in the layout creation. So any scenario that requires rendering XFA, such as merging data or displaying dynamic XFA, will ultimately require Output to do the rendering. Static XFA is already rendered, so unless there is new data being merged, Output is not required.

AcroForms can be rendered by the Gibson libraries (within the limitations of the Assembler and PDF Generator implementations), and therefore do not require Output.

The key message is that, in general, LiveCycle Output ES is the product for documents of record (flat PDF) from XFA and forms.

Customer Experience Management for the Pragmatist

As you may be aware, the term Customer Experience Management (CEM) has become one of the latest buzzwords in the enterprise software industry.  Many large companies have formed CEM groups and a few have even created “C” level positions that are dedicated to improving the customer experience.  Adobe has embraced CEM in a big way (you can see the Experience Delivers blog  or Steven Webster’s blog for just a couple of examples), so I felt I needed to understand more about it.

In my search for answers I came across tons of white papers, research notes, videos and other content on CEM and its related topics (such as Rich Internet Applications (RIA), User Experience (UX), Experience Oriented Architecture (XOA), etc.).  There were web pages that call out “bad” design and praise “good” design.  Some sites had some best practices (although these were mostly based on specific examples).  I found a plethora of other phrases that seemed to float around the subject – customer oriented design, put the customer first, contextual design, etc.

I also spoke with some of Adobe’s CEM proponents.  Unfortunately these conversations tended to bend towards rather philosophical discussions.  One time someone actually said “the Medium is the Message”.    At this point my the part of my brain that performs cognitive reasoning ran down the hallway and hid in a quiet corner.  I can’t help it; McLuhan has that effect on me.

Nothing really hit home with me.  I might be able to recognize a CEM application if I saw one, but I still couldn’t describe to you why it was CEM.

It started to feel like when I played baseball as a kid.  Both my little league coach and my dad kept telling me to “keep your eye on the ball”.  Repeating the phrase over and over made it essentially meaningless.  One day someone (probably a frustrated first baseman) said something like – “look, just watch the ball as it leaves my hand.  Keep watching it as it goes through the air and then put your glove in front of it.”  All of a sudden it made sense.  I still suck at baseball, but at least I don’t get beaned as often.

One day, while searching for cheap vacation flights, things started to congeal.  Navigating through several sites that essentially did the same thing, I started to understand what was meant by customer experience.  More importantly I started to get why it was so important.

When you get right down to it, what does CEM mean in a practical sense?  Its simple really – build software that helps the user accomplish their goal.  At the very least it should not actively make the user mad.

Like so many simple statements, that has some rather complex consequences.  For one thing, as a designer/developer you really need to understand what the user is trying to do as well as how they feel confortable doing it.  This includes not only understanding the direct path to the goal, but how to assist them.  Also allow people to get back when they go down a different path.

If I look at my own recent experience with online ticket retailers, there were precious few who designed their applications in this way.  For the most part the sites were designed for people to book flights; but I, for one, wasn’t using it that way.  I was shopping for flights – changing dates/times, departure location (I’m Canadian, so it sometimes pays to drive to a US airport), airlines, etc.  One site made me re-enter all of the information each time I changed one thing.  Others would only give me one flight choice and would not suggest others.  Some would require me to know things that are industry specific (such as airport codes).  The sites I really appreciated, and therefor spent more time on, made my life easier.

Here are some general things that I observed:

  • Cut down on the clicking
    • If you’re going to require me to read something then just show it to me.  Don’t make me click on a button that brings it up.  If its that important than gimme it.  This really goes to presenting the right information at the right time.
  • Get on with it! (or where’s the “f@*ck off” button)
    • Of course the flip side is presenting too much information.  If I don’t need it right now, get rid of it.
  • Just do what I tell you to do
    • Software is a tool.  As developers we often think that the software itself is the most important thing.  We must keep in mind that the user is trying to get something done (like shop for a flight) and the software is just a means to an end.
  • I don’t care about your process
    • Remember that the user is not concerned with what is going on behind the scenes.  Your product codes, industry regulations, inter-departmental routing, etc. does not matter to the user.  While you do want to tell the user what is going on, they don’t need to know what’s going on in the sausage factory.
  • Customize when necessary, but but not necessarily customize
    • There is a trend to allow the user to customize every aspect an application.  In some circumstances this is a really nice thing (iGoogle is a prime example), but it has a dark side.  I’ve used too many applications that require lengthy configuration to provide a personalized experience.  I know they theory is that by customizing the interface the user takes ownership, but Its not always necessary or even wanted.  Sometimes I just want to do a quick search and get on with my life (google.com is a prime example).

As I said, it all boils down to designing software that helps the user do something.

Mosaic and LiveCycle Data Services

Adobe’s two RIA products – LiveCycle Mosaic and LiveCycle Data Services (LCDS) – go together like peanut butter and jelly.  One provides a framework for intuitive, user focused applications, the other provides efficient access to real time back end data.  Between the two of them they can provide up-to-date data in an engaging user experience.

There are a couple of different ways to combine the two products, however.  What one you will choose will depend on your particular setup and how your back end data is organized.  So, do you prefer your jelly on top, or on the bottom?

In this post I’ll present both methods of Mosaic/LCDS integration using an overly simple example.  Hopefully this will give you some ideas for your projects.

In the end I built a simple Mosaic application that demonstrated both methods.

image

A Simple Service

For this example, I’m going to create a very simple LCDS RPC service that accesses a Java object.  This is based on the Adobe documentation that can be found at: http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/lcds/help.html?content=lcoverview_4.html

First I created a trivially simple POJO that echoes back a single String:

package remoting;
public class EchoService
{
    public String echo(String text) {
        return "Server says: I received '" + text + "' from you";
    }
}

Once that was compiled I moved the class file to the  WEB-INF/classes/remoting directory.  Then I added the following entry into the WEB-INF/flex/remoting-config.xml file:

<destination id="echoServiceDestination" channels="my-amf">
    <properties>
        <source>remoting.EchoService</source>
    </properties>
</destination>

The source entry points to my Java class and it uses the existing my-amf channel.

The last thing that I needed to do was to add a crossdomain.xml file to my LCDS server.  This is because my Mosaic server is running on a different box.

Jelly on top; Calling LCDS directly from a tile

The first method I’ll show is also the most direct.  This involves making a direct call from the Mosaic tile to the LCDS service. This is a useful method when there is a direct relationship between the tile’s visual elements and the data. What it has in simplicity, it lacks in power.  This method does not lend itself to decoupling the data from the tile.

<?xml version=”1.0″ encoding=”utf-8″?>
<mc:Tile xmlns:fx=”
http://ns.adobe.com/mxml/2009″

xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”
xmlns:mc=”com.adobe.mosaic.core.*”
layout=”absolute” width=”100%” height=”100%”
creationComplete=”init()”>

<fx:Declarations>
<mx:RemoteObject id=”remoteObject”
destination=”echoServiceDestination”
result=”resultHandler(event);”
fault=”faultHandler(event);”/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.messaging.Channel;
import mx.messaging.ChannelSet;
import mx.messaging.channels.AMFChannel;
import mx.messaging.config.ConfigMap;
import mx.messaging.events.*;
import mx.messaging.messages.*;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectProxy;


private function init():void{
register();
var cs:ChannelSet = new ChannelSet();
var customChannel:Channel = new AMFChannel("my-amf","
http://myserver/lcds/messagebroker/amf");
cs.addChannel(customChannel);
remoteObject.channelSet = cs;
}

private function register():void{
registerClassAlias("flex.messaging.messages.CommandMessage",CommandMessage);
registerClassAlias("flex.messaging.messages.RemotingMessage",RemotingMessage);
registerClassAlias("flex.messaging.messages.AcknowledgeMessage", AcknowledgeMessage);
registerClassAlias("flex.messaging.messages.ErrorMessage",ErrorMessage);
registerClassAlias("DSC", CommandMessageExt);
registerClassAlias("DSK", AcknowledgeMessageExt);
registerClassAlias("flex.messaging.io.ArrayList", ArrayList);
registerClassAlias("flex.messaging.config.ConfigMap",ConfigMap);
registerClassAlias("flex.messaging.io.ArrayCollection",ArrayCollection);
registerClassAlias("flex.messaging.io.ObjectProxy",ObjectProxy);
registerClassAlias("flex.messaging.messages.HTTPMessage",HTTPRequestMessage);
registerClassAlias("flex.messaging.messages.SOAPMessage",SOAPMessage);
registerClassAlias("flex.messaging.messages.AsyncMessage",AsyncMessage);
registerClassAlias("DSA", AsyncMessageExt);
registerClassAlias("flex.messaging.messages.MessagePerformanceInfo", MessagePerformanceInfo);
}

// Send the message in response to a Button click.
private function echo():void {
var text:String = ti.text;
remoteObject.echo(text);
}

// Handle the recevied message.
private function resultHandler(event:ResultEvent):void {
ta.text += "Server responded: "+ event.result + "\n";
}

// Handle a message fault.
private function faultHandler(event:FaultEvent):void {
ta.text += "Received fault: " + event.fault + "\n";
}
]]>
</fx:Script>

<s:Label x=”11″ y=”5″ text=”Direct LCDS Call”/>
<s:TextInput x=”11″ y=”24″ id=”ti” text=”Hello World!”/>
<s:Button x=”147″ y=”25″ label=”Send” click=”echo();”/>
<s:TextArea id=”ta” width=”100%” height=”628″ y=”68″/>
</mc:Tile>

Again this is based on the LCDS documentation.  There are some concessions to the Mosaic framework however.  First, an AMF channel needs to be setup, also several classes need to be registered.  I know I’ve registered more than I need, but I will probably expand this tile later on.

As you can see, when the user clicks on the Send button, a function is called that makes use of the remote object.  The remote object then uses the AMF channel to make a LCDS call to the POJO.  The results are then shown on the screen.

Jelly on bottom; Using a Mosaic service to make the LCDS call

Another way to make an LCDS call from a Mosaic tile would be to use a Mosaic service as an intermediary.  In this case the tile wouldn’t be aware of the LCDS service at all, any interactions would be made through the Mosaic service.  This is very useful if multiple tiles need to access the same LCDS service as it only needs to be accessed once.  It also allows easy decoupling of the tiles and the data as the Mosaic service can be changed without affecting the inner workings of the tiles.  The draw back is that it does require a bit more coding and more for thought when planning out the Mosaic service.  For more info on creating Mosaic services, see my earlier blog entry

The interface

Let’s look at the code to do something similar to the simple example.  First the Interface object:

package com.adobe.etech{

public interface IHelloWorld    {
function setEcho(msg:String):void;
function getEcho():String;
function echoReady():Boolean;
function setLoaderURL(url:String):void;
}
}

Since the LCDS call is asynchronous, I needed a getter and setter function to make the request and get the response. I also need a method to determine when the asynchronous call is complete (so I can go get the data). The echoReady function is a bit of a cheat to allow this.  As I mentioned in an earlier post, there is no easy way to send a message from the Mosaic service to the tile because the service is not context aware.  You can push the context into the service, but for this example it would be overkill.  So I built a cheap and cheesy Boolean function that I can ping from the tile.

The final function setLoaderURL is very important to the application and requires a bit of explanation.  When I was working on this project, I set everything up as I did with the direct LCDS call.    I kept getting an error that the URL was null.  I knew I had set the URI for the amf channel, so what was the URL it needed?  After discussing it with several of my colleagues I was able to narrow it down to  the fact that the LoaderConfig.mx_internal::_url  object needs to have a URL to a MXML element.  Passing the tile’s loaderInfo.url value to the Mosaic service seems to do the trick.

The Mosaic Service

The service implementation is below:

package com.adobe.etech.impl
{
import com.adobe.etech.IHelloWorld;

import flash.display.Sprite;
import flash.net.registerClassAlias;

import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.core.mx_internal;
import mx.logging.targets.TraceTarget;
import mx.messaging.Channel;
import mx.messaging.ChannelSet;
import mx.messaging.channels.AMFChannel;
import mx.messaging.config.ConfigMap;
import mx.messaging.config.LoaderConfig;
import mx.messaging.events.*;
import mx.messaging.messages.*;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.remoting.RemoteObject;
import mx.utils.ObjectProxy;


public class HelloWorldLCDSService implements IHelloWorld
{

private var remoteObject:RemoteObject;
private var _echoMsg:String = “”;
private var _echoComplete:Boolean = false;

public function HelloWorldLCDSService()    {
register();

var amfChannel:AMFChannel  = new AMFChannel(“my-amf”,http://server/lcds/messagebroker/amf);
amfChannel.requestTimeout = 3;
amfChannel.connectTimeout = 3;
var channelSet:ChannelSet = new ChannelSet();
channelSet.addChannel( amfChannel );

amfChannel.addEventListener(ChannelFaultEvent.FAULT, handleChannelFault);
amfChannel.addEventListener(ChannelEvent.CONNECT, handleChannelConnect);
amfChannel.addEventListener(ChannelEvent.DISCONNECT, handleChannelDisconnect);

remoteObject = new RemoteObject();
remoteObject.destination =”echoServiceDestination”;
remoteObject.channelSet = channelSet;

remoteObject.addEventListener(ResultEvent.RESULT,resultHandler);
remoteObject.addEventListener(FaultEvent.FAULT,faultHandler);
}

private function handleChannelFault(e:ChannelFaultEvent):void {
_echoComplete = true;
_echoMsg +=”Channel Fault” + “\n”
trace(“Channel Fault”);
trace(e);
}

private function handleChannelConnect(e:ChannelEvent):void {
_echoComplete = true;
_echoMsg +=”Channel Connect” + “\n”
trace(“Channel Connect”);
trace(e);
}

private function handleChannelDisconnect(e:ChannelEvent):void {
_echoComplete = true;
_echoMsg +=”Channel Disconnect” + “\n”
trace(“Channel Disconnect”);
trace(e);
}


public function setEcho(msg:String):void    {
_echoComplete = false;
remoteObject.echo(msg);
}

public function getEcho():String{
return _echoMsg;
}

public function echoReady():Boolean{
return _echoComplete;
}

private function register():void{
registerClassAlias(“flex.messaging.messages.CommandMessage”,CommandMessage);
registerClassAlias(“flex.messaging.messages.RemotingMessage”,RemotingMessage);
registerClassAlias(“flex.messaging.messages.AcknowledgeMessage”, AcknowledgeMessage);
registerClassAlias(“flex.messaging.messages.ErrorMessage”,ErrorMessage);
registerClassAlias(“DSC”, CommandMessageExt);
registerClassAlias(“DSK”, AcknowledgeMessageExt);
registerClassAlias(“flex.messaging.io.ArrayList”, ArrayList);
registerClassAlias(“flex.messaging.config.ConfigMap”,ConfigMap);
registerClassAlias(“flex.messaging.io.ArrayCollection”,ArrayCollection);
registerClassAlias(“flex.messaging.io.ObjectProxy”,ObjectProxy);
registerClassAlias(“flex.messaging.messages.HTTPMessage”,HTTPRequestMessage);
registerClassAlias(“flex.messaging.messages.SOAPMessage”,SOAPMessage);
registerClassAlias(“flex.messaging.messages.AsyncMessage”,AsyncMessage);
registerClassAlias(“DSA”, AsyncMessageExt);
registerClassAlias(“flex.messaging.messages.MessagePerformanceInfo”, MessagePerformanceInfo);

}

public function setLoaderURL(url:String):void{
LoaderConfig.mx_internal::_url = url;

}

// Handle the recevied message.
private function resultHandler(event:ResultEvent):void {
_echoComplete = true;
_echoMsg += “Server responded: “+ event.result + “\n”;
}

// Handle a message fault.
private function faultHandler(event:FaultEvent):void {
_echoComplete = true;
_echoMsg += “Received fault: ” + event.fault + “\n”;
}
}
}

This is very similar to the direct LCDS call, except it has getters/setters so the calling tile can go and get the resulting data.   The amf channel listeners are there as a result of me trying to debug the setLoaderURL issue mentioned above.

The Tile

The tile that uses the service is quite simple. It uses the IHelloWorld interface to make the call and relies on Mosaic to inject the service instance at runtime (see my previous entry for more on how this works):

<?xml version=”1.0″ encoding=”utf-8″?>
<mc:Tile xmlns:fx=”
http://ns.adobe.com/mxml/2009″

xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”
xmlns:mc=”com.adobe.mosaic.core.*”
layout=”absolute” width=”100%” height=”100%”>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>

<fx:Script>
<![CDATA[
import com.adobe.etech.IHelloWorld;

[Bindable] public var helloService:IHelloWorld;
private var myTimer:Timer = new Timer(1000,1);  //1 second
private var timeoutID:uint;

// Send the message in response to a Button click.
private function echo():void {
var text:String = ti.text;
//remoteObject.echo(text);
helloService.setLoaderURL(this.loaderInfo.url);
helloService.setEcho(text);
if (helloService.echoReady()){
this.getEcho();
}else{
myTimer.addEventListener(TimerEvent.TIMER,checkEcho);
myTimer.start();
}
}

private function checkEcho(event:TimerEvent):void{
if (helloService.echoReady()){
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER,checkEcho);
this.getEcho();
} else{
//try again
myTimer.reset();
myTimer.start();
}
}

private function getEcho():void{
ta.text = helloService.getEcho();
}

]]>
</fx:Script>

<s:Label x=”11″ y=”5″ text=”LCDS Using Service” width=”195″/>
<s:TextInput x=”11″ y=”24″ id=”ti” text=”Hello World!”/>
<s:Button x=”147″ y=”25″ label=”Send” click=”echo();”/>
<s:TextArea id=”ta” width=”100%” height=”628″ y=”68″/>
</mc:Tile>

You may notice that I have a timer that checks to see if the data is returned.  This is because the service has no built in way of sending a message to the tile. The timer was a bit of a cheat and I wouldn’t recommend using this method in production code. Instead I would recommend passing the tile context to the service so it can send a proper Mosaic message (see this post for more info)

Conclusion

As you can see from this simple example, there are a couple of different options for combining LCDS and Mosaic.  Each has its advantages and weaknesses and it will depend on your situation as to which one to use:

Direct LCDS Call:

Pros:

  • Simple to code
  • Direct tie from data to visual elements

Cons:

  • visual elements not decoupled from tile
  • each tile makes its own connection – no connection sharing

Mosaic Service LCDS Call:

Pros:

  • LCDS call abstracted from tile
  • multiple tiles use same call

Cons:

  • more complex code
  • need to implement your own checker for returned data, or pass the tile context to the service

Special thanks to Leo Schuman and Marcel Boucher for their assistance and patience with LCDS. If you are interested, the source code can be found here.

Service Interruptus

While working on a recent LiveCycle Mosaic demo, I discovered some interesting consequences of using Mosaic services with large amounts of data and memory heavy tiles.  Since the cause of the issues was not immediately apparent, and the solution is quite simple, I thought I’d share my findings.

The Conditions

The demo I was constructing consists of quite a few Mosaic tiles that rely on common data.  Basically each tile shows a different aspect of the data, so the user gets a graphical breakdown of a current situation.  Since much of the data is shared across several tiles, I figured it would be a good use of a common Mosaic service.  Then each tile can access the same service and the data only needs to be loaded once.  The service will read an XML file from the Mosaic catalog, process it and will have functions that will present aspects of the data to the Tiles.

arch2

In the service implementation class, I have a standard Flex HTTPService object that I use to load the data into an XML object.  After the data is loaded into the service there are several functions that can be called by the tiles.

The Symptoms

For early testing I created a simple XML file and a couple of quickie tiles. By watching the Flash Builder 4 console, I could see that the service was loading, then the tiles.  The tiles could access the data via the service with no problems. As I continued adding more complex tiles, and increasing the size of the XML file, strange things started happening.

Every once in a while a tile would give a null pointer error.  Upon further inspection, this happened only in tiles that called the service functions on creation complete.  It looked as if the service had not loaded the data, but when I put break points in my code I could see that the data was loaded.  To aggravate the issue, it wasn’t consistent as to when the problem would happen.  I could load the application a dozen times and it would work fine, then it would fail once or twice and then be fine again.

WTF???

Somebody tell Schrodinger his cat is dead

If all else fails, procrastinate. I ignored the problem and continued working on the rest of the demo – hey it worked most of the time.  As I continued to add additional tiles and functionality to the service things steadily got worse.  Eventually it got to a point where it would fail more often than it would not.  To be fair to myself (and who else will), it really was a good thing to delay looking for the root of the problem.  At least now I could take a serious look at what was going wrong and have a reasonable chance of looking at a failed case.

I’ll save you the tribulation of my debugging efforts, needless to say I learned a lot about working with a non-linear multi-faceted environment such as Mosaic.  Not the least of which was – just observe, don’t participate.  Trying to find intermittent problems with multiple tiles, services, asynchronous events and a black box framework takes a level of patience for which I am not well equipped.  I tried to be Zen about it but The Norse part of my genetics just wanted to smash it with a big axe and go burn a village (ah, simpler times…)

After stepping through the code multiple times, and adding more trace statements than I’d like to admit, I was able to figure out that there were actually two separate problems.  One was fairly obvious, the other not so much.

Problems and Solutions

The first problem was in the service itself.   The tiles depended on the data provided by the service.  The service implementation uses an HTTPService to read the data from an XML file.  Since the HTTPService load operation is asynchronous (waits for a ResultEvent), a tile may try to access the service before the data is loaded.  When the tile makes the call to the service, the XML data is empty and an exception is thrown when the service tries to perform an operation on the data object.  When there wasn’t much data it loaded quickly enough not to present a problem.  As the test data became larger it took more time to load and the problem started to show itself.

If this was a “normal” Flex app, I’d just have the service dispatch an event when the data was loaded.  Flex components that depended on that service would have event listeners that would wait for the service to say it is ready.  This won’t work in the Mosaic framework however, because of the decoupled nature of services and tiles.  The tile does not have direct knowledge of the service context and therefore cannot pickup events thrown by the service.  The solution is to have the service send a message to the Mosaic framework, and have the tiles listen to the framework for a message.  Unfortunately, Mosaic service implementations don’t directly inherit the Mosaic context.  Yes, I can import the IContext class, but there is no way to initialize it directly with the Mosaic framework’s information.

The solution was a bit of a cheat.  I can get the Mosaic context information from a tile, it’s a property of the inherited mosaicApp object.  So what I did was to add an IContext variable to the service, with a setter function.  Then I had one of the tiles pass its context to the service using the setter.  Now when the service decides that both the data and context are set, it can set a Mosaic attribute saying that its ready.  Tiles will check the attribute before attempting to access the service.  As a bonus, tiles can watch for the attribute to change which will tell them the data has been updated.

I implemented the fix, and tested it out.  Everything worked fine … for a while.

Every once and a while the tile that passed its context to the service would throw an exception.  The exception stated that the service itself was null.  From what I understood about the way Mosaic handled the services, this should not be possible.  Mosaic is supposed to load the services before the tiles, guaranteeing that they would exist. Another round of step through and trace statements ensued.  From what I was able to deduce, Mosaic was indeed loading the service before the tiles, however the tiles could be created before the reference to the service was injected.  In other words, because I was setting the context on the tile’s creationComplete event, the service implementation’s reference may not be fully realized – resulting in a null pointer error.

The solution to this problem was less pleasant.  The only way I could figure to make sure the service reference was complete was to put a timer into the tile that set the service context.  Basically I check to see if the service object is null.  If it is then I set a timer’s event listener and start the timer.  The event listener checks again to see if the service is null.  If it is then it resets the timer.  If it is not then I set the context object and we move on.

I’m not a fan of these kind of timed wait loops. However; without being able to get an event from the service, I can’t see any other way of doing it.  The problem is that I can’t get an event without the context being set and I can’t set the context until I know the service is not null.

I also added a check in the other tiles to not only look for the service’s data loaded attribute, but they also check to see that the service object is not null.  Belt and suspenders programming at its best.

Conclusion

Here is the short version of what happened:

Issue 1

  1. Services that perform asynchronous operations need to tell their dependent tiles when these operations are complete
  2. Service have no direct way of notifying tiles as they don’t have access to the Mosaic context
  3. A tile can pass that context to the service if the service exposes a context object setter function

Issue 2

  1. Service load before tiles, however tiles can reach creation complete before the service injection has happened.  This means that the tile’s service object may be null.
  2. The only thing to do is to have the tile wait (using a timer loop) for the injection to be complete.

Creating an Organized Mosaic Project Structure

Lately, I’ve been working a lot with people that are new to LiveCycle ES2 Mosaic.  One thing always seems to come up is the question of the best way to organize Mosaic projects.    There aren’t any hard and fast rules (with the exception of the Catalog folder layout), but I’ve seen enough similarities in unrelated projects to suggest that there are some unofficial conventions that are forming.  I won’t go as far as to call the following “best practices”, rather consider them suggestions based on experience.  When combined with standard Flex best practices, these suggestions may make developing your Mosaic applications a bit easier.

Folder Structure

Organization will set you free – Alton Brown

Mosaic applications consist of quite a few moving parts.  There are the application descriptors, tile code, services and interfaces, authentication policies, shell skins, etc.  Keeping these sorted out will definitely make your life easier, especially when it comes to deploying and debugging.  Whenever possible, I prefer to keep all of the files/folders for a single Mosaic undertaking under a single folder.  That may mean having more than one application in the same folder, but at least the related code will be close by.

Under that parent folder I usually create one folder for each major Mosaic component.  The folder names are in lower case to differentiate them from the Catalog’s folders (more on that later).  For example:  I have a project called the Sales Dashboard, which will contain an application, catalog, several tiles, a service, a custom style sheet, etc.  To keep from going insane, I created the following folder structure:

topLevel

  • applications – this folder contains the application descriptor xml file(s)
  • catalogs – this folder contains the deployable contents for the project’s catalog.  If I was to have multiple catalogs, then they would each go in a separate subfolder.  A catalog’s structure is one of the few things that must have a specific structure.  This is because the catalog folder gets zipped and then deployed to the Mosaic server.  For more on the catalog folder’s structure, see the section below.
  • interfaces – this project uses a Mosaic Service component that is used by several tiles.  Each service component consists of two parts – the interface library and the service class.  This folder contains sub folders for each of the interface library projects.  Those subfolders contain a Flex Builder project that includes the source code for the interface.  In this example I have a single interface library called the “SalesDashboardInterfaceLibrary”, so the interface folder has a single subfolder with that name.  In the subfolder is a Flex Builder project for the interface:
    interfaces
  • policies – if you are using the Mosaic fine grained authorization, then this folder contains the XACML files that provide authorization information for the elements.
  • services – this folder is related to the interfaces folder.  It contains subfolders for each of the service class files.  Inside those subfolders is a Flex Builder project used to develop the service code.  For example, this application includes a “SalesDashboardService”. That subfolder contains a Flex Builder project for that service library:
    service
  • stylesheets – this project contains a custom skin for the Mosaic application.  The Flex Builder project for this skin is in a subfolder under the stylesheets folder.  If I had more than one skin, then each would get its own subfolder.  For example, my skin project is called “GlobalCorpSkins”:
    stylesheet
  • tiles – this folder contains sub folders for each of the Flex Builder tile projects.  Usually I try to keep related tiles in the same Flex Builder project (it makes debugging a bit easier), so a single sub folder may contain many tiles.  There are some cases, however, where a particular tile needs  its own project.  For example, if it uses a different Flex SDK or comes from a legacy application.  How fine grained you want to make the tile projects is really up to you, but keeping them all under this one tiles folder will make them easier to find.  In this example I have two tile projects – Flex 4 tiles (which contains several tiles) and Map (which contains a single, very complex tile):
    tiles

Catalog Structure

As I said earlier, the catalog structure is the one thing that must be in a specific format.  The catalog contains the deploy objects (compiled code, resources, etc.) and it will be zipped, then sent to the Mosaic server.  The server is expecting specific things to be in specific folders.  And yes, those folders are case sensitive.

catalog

  • descriptor.xml – this is the catalog’s definition file.  It must be named descriptor.xml and it must be at the root of the catalog zip file
  • Interfaces – contains the compiled swf for the interface libraries.
  • Resources – this is where the miscellaneous stuff needed for tiles and services is stored.  Things like images, XML files, videos, etc. are put here.
  • Services – contains the compiled swf for the service classes
  • Stylesheets – contains the skin classes complied into a swf
  • Tiles – contains subfolders for each of the tiles in the catalog.  The subfolder names is the same name as the tile, and they contain the tile swf files.

Flex Builder Linked Resources

Since tiles, services and skin projects rely on the Mosaic SDK, you’ll need to include the appropriate SDK swc in each of your projects.  Rather than hard coding the path, it is a good idea to create a pointer to the SDK folder and let Flash Builder sort out the location.  This makes your code more portable, if you give it to someone else, they don’t have to have the SDK in exactly the same location as you do.

To set up a linked resource to the Mosaic SDK:

  • Open Flex Builder
  • Choose Window –> Preferences
  • Choose General –> Workspace –> Linked Resources
  • Click the New button
  • Give it a name of MOSAIC_SDK
  • Click the Folder button and browse to your Mosaic SDK folder.  Don’t go any lower than the “sdk” folder.
  • Click OK to close the dialogs

When you create a new Mosaic project you can use the linked resource in your Flex Build Path.  Then if someone else opens your project and has the SDK in a different location, Flash Builder will sort out the reference (assuming they have a MOSAIC_SDK resource).

ANT Scripts

It may seem that I’ve gone a little berserk with the organization of the project.  I mean, how anal retentive can you get?  Why not just lump everything together in one or two folders and be done with it?

The answer lies in the application deployment through ANT scripts.  Having a highly organized structure like this allow you to build the deployment code as a few, small ANT files.  These can be combined together to quickly deploy code changes in an efficient manner.  There are few things more annoying than testing against the wrong code.

For example; At the root of the project I have an ANT script that deploys the catalog, application and policies.  Before that section executes, it calls ANT scripts in the sub folders that re-compile the interface, service, style sheet and tile classes, and move them to the appropriate location in the catalog structure.  Using this, I can make changes to a tile, run the root ANT script and ensure that everything is the current version.

True, it takes a bit more effort to set up, but the time and frustration savings are well worth it.  Here’s what my final folder structure looks like:

folderStructure

Request for Comments

For what its worth, most of the above is my opinion based on my own experiences.  If you have any additional suggestions, I’d love to hear them.