Search Flex Components Free

Custom Search

December 15, 2007

Flex Data Services - CRM Sample using Hibernate

I've played around a great deal with the sample applications that shipped with Flex Data Services. In particular I was intrigued in getting the CRM example to work with Hibernate. I'm not going to get too deep into the particulars. Here's just a good overview of what needed to be done or what purpose was served, by file.

samples\web-inf\web.xml
In this file there's a section of code that needs to be uncommented. This enables a servlet that runs when jrun boots up, which creates a file called hibernate.cfg.xml and puts it in the samples\web-inf\classes\samples folder.

samples\web-inf\classes\samples\hibernate.cfg.xml
Once you uncomment the web.xml and start up FDS once, this file should exist. In here you will see some basic configuration stuff that basically creates a jdbc connection to an hsqldb database (a java sql engine that runs within the context of the app server). Also you will not two mapping files, explained next.

samples\web-inf\classes\samples\crm\employee.hbm.xml
samples\web-inf\classes\samples\crm\company.hbm.xml
These two files serve to map sql tables & columns to java classes and properties, found in samples.crm.Employee and samples.crm.Company, respectively. You can find the source code for these files (if you're new to the java world like me) in samples\web-inf\src\(...)

samples\web-inf\flex\data-management-config.xml
In this file there are 2 sections that need to be uncommented out. You can leave the other destinations in place and just uncomment the destinations crm.employee.hibernate and crm.company.hibernate. Once you've saved these changes it's a good idea to restart FDS.

samples\dataservice\crm\companyapp.mxml
First go ahead and launch this in a browser, make sure FDS is running. The default address would be http://localhost:8700/samples/dataservice/crm/companyapp.mxml and make sure everything is still working fine. At this point the application is still using the custom company and employee assembler classes, not hibernate. If everything works fine, go ahead and edit the file. You'll need to find all the comments that pertain to Hibernate and then comment out the line preceding it, while uncommenting the line the line that follows, as per the comment instructions. Save your changes.

Now go ahead and reload the companyapp.mxml page in the browser. Keep the FDS console open and if everything went well, you can watch as hibernate generates and logs query statements.

asp.net C# data webservice for Flex

This is kinda the next evolutionary step from my previous blog. In this example I demonstrate how to get an array of records from .net to flex. Again, I have simplified this for the purpose of this blog. In the asp.net webservice, I would normally retrieve records from the database and then iterate thru the dataset to build my array, while here in this example I have just populated the array manually.

C# Webservice:


using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.Web;using System.Web.Services;using System.Xml.Serialization;namespace Director{ public class MemberService : System.Web.Services.WebService { public MemberService() { InitializeComponent(); } private IContainer components = null; private void InitializeComponent() {} protected override void Dispose( bool disposing ) { if(disposing && components != null) { components.Dispose();} base.Dispose(disposing); } [WebMethod] [XmlInclude(typeof(Member))] public Member[] getMembers() { ArrayList al = new ArrayList(); Member mem = new Member(0,"bob","bsmith","password1", "bob@abc.com","Initiate",false,DateTime.Now); al.Add(mem); Member mem1 = new Member(0,"jim","jsmith","password2", "jim@abc.com","Member",false,DateTime.Now); al.Add(mem1); Member mem2 = new Member(0,"ed","esmith","password3", "ed@abc.com","Officer",false,DateTime.Now); al.Add(mem2); Member mem3 = new Member(0,"neil","nsmith","password4", "neil@abc.com","Guest",false,DateTime.Now); al.Add(mem3); Member[] outArray = (Member[])al.ToArray(typeof(Member)); return outArray; } } [Serializable] public class Member { public int memberid; public String name; public string username; public string password; public string email; public string comments; public bool disabled; public DateTime created; public Member(int _memberid, string _name, string _username, string _password, string _email, string _comments, bool _disabled, DateTime _created) { memberid = _memberid; name = _name; username = _username; password = _password; email = _email; comments = _comments; disabled = _disabled; created = _created; } public Member(){} }}
In Flex, the Member.as file:
package com.abc.ws{ [Managed] [RemoteClass(alias="com.abc.ws.Member")] public class Member { public var memberid:int; public var name:String; public var username:String; public var email:String; public var password:String; public var comments:String; public var disabled:Boolean; public var created:Date; public function Member(obj:Object = null) { if (obj != null) { this.memberid = obj.memberid; this.name = obj.name; this.comments = obj.comments; this.username = obj.username; this.email = obj.email; this.disabled = obj.disabled; this.created = obj.created; this.password = obj.password; } } }}In Flex, the application:

Passing Objects on a dataservice fill()

A couple of weeks ago I ran into an interesting issue regarding the passing of a value object as one of the elements in my FillParameters array. Something like this:


dataservice.fill(employees, CompanyVO)The fill worked fine everytime, however, if I went and added a new employee using:
dataservice.createItem(employee);dataservice.commit();the collection on my client would not update to show the new employee. Sure I could add the employee by doing an employees.add(employee), and yes, my collection would be updated. However, another employees collection on another client viewing the same records would not.

I turned up the logging level to debug and watched how Flex Data Services was handling the request. It seemed, after a bit of extensive testing, that it did not recognize the CompanyVO object as being the same one across multiple calls. The debugger would even state that no client collections existed with this fill configuration, and therefore none would receive a refresh.

I thought perhaps my CompanyVO.as was perhaps not mapping thru to my CompanyVO.class, so I put my own toString() method in with a quick little output line. Sure enough, FDS was recognizing the object passed as a CompanyVO.class object.

Eventually I gave up. I had played with my java class, trying to override various methods, implementing icomparable, etc. Nothing.

Then Jeff Vroom posted a suggestion on flexcoders. To override the (built-in) in uid property on the Object. First I added some code to have uid equal the companyid, saved my flex project and ran it again:

Company.aspublic var uid:String = "";...company.uid = company.companyid;
No luck. Then I added the uid property to my java class as well:

private String uid;public void setUid(String uid){ this.uid = uid;}public String getUid(){ return this.uid;}
Restarted FDS and ran my flex project again. Problem solved. Here's the steps to reproduce this problem using the crm sample that comes with FDS(as posted by me in the Adobe FDS Forum):

1) in companyapp.mxml, change the fill line in the companyChange function to read:
dsEmployee.fill(employees, company) //change from companyId int to company VO

2) in the crm sample application, addEmployee function, replace this line:
employees.addItem(employee);
with this:
dsEmployee.createItem(employee);
(you don't have to do this if you keep 2 instances of the app running)

3) in the crm.samples.EmployeeAssembler fill method, change the fill by commenting out everything after the line that says return dao.GetEmployees(); and replace them with these lines:
Company cp = (Company) fillParameters.get(0);
return dao.findEmployeesByCompany(cp.getCompanyId());

4) in the crm.samples.EmployeeAssembler createItem method, replace the second dtx.refreshFill with the following line:
dtx.refreshFill("crm.employee", Arrays.asList( new Object[] {newEmployee.getCompany()}));

Posted by Victor Rubba at 1:18 PM 1 comments



Wednesday, October 04, 2006
Blog Facelift
As much as like a black background with neon writing, I was getting headaches reading my own material. So I upgraded to the new blogger beta and replaced my template with something a little more conventional. Enjoy.

Asynchronicity Blues - managing multiple dataservice calls

A while ago I once again came up face to face with the mean and hungry asynchronicity beast that lives within Flex. All I was trying to do was create and save a Contact record programmaticly. The problem was, however, that a Contact has references to ContactType, Country and Division. Simplified, I was trying do the following:

countryService.fill(countries);contactTypeService.fill(contactTypes);divisionService.fill(divisions);contact.country = countries.getItemAt(0); //defaultcontact.contactType = contactTypes.getItemAt(0); //defaultcontact.division = divisions.getItemAt(0); //defaultcontactService.createItem(contact);
Of course, most of the time this would fail because the collections would not yet be filled, being asynchronous in nature. So I had to find a workaround. I created a dataTasks collection and then added a dataTask prior to each fill to the collection. On the result event of each fill I would find my dataTask and remove it from the collection. I added an EventListener to the CHANGE event of my dataTasks collection and when the collection length was back to 0, I would remove the EventListener and create my Contact. This worked fine, however it required alot more coding. Here's what it looked like:
//prior to fillif(contactTypes.length == 0){dataTask = new DataTask("ContactTypes",false);model.dataTasks.addItem(dataTask);}contactTypeService.fill(contactTypes, "flex:hql", "from ContactType");//onResult Eventif(dataTask){ model.dataTasks.removeItemAt(model.dataTasks.getItemIndex(dataTask));dataTask = null;}//add Eventlistener to dataTasks model.dataTasks.addEventListener(CollectionEvent.COLLECTION_CHANGE,completeContact);...private function completeContact(evt:CollectionEvent = null):void{if(model.dataTasks.length == 0) {model.dataTasks.removeEventListener(CollectionEvent.COLLECTION_CHANGE,completeContact);var contact:Contact = new Contact();...Again, I posted on Flexcoders as to whether or not this was the BEST way to do this, and again Mr. Vroom responded. He wrote that even though the calls on the client are made ASYNCHRONOUSLY, the server handles the requests in SYNCHRONOUS order. In other words I only have to listen for the result event of the LAST fill called. When that result is returned to the client, barring any faults from the previous fills, we can assume that all collections have been filled. Yay! Less Code!

Using FDS with Java 5

I found this little tidbit of information tucked away in my documents folder and I figured I might as well share it.

While attending the flex data services course, we were told that both Flex Builder and FDS2 are 100% compatible with Java 5, even though they both ship with the 1.4.xx JRE. Now I'm still looking to wildly expand my Java knowledge, and every book out there is Java 1.5, not to mention certain tools like the Hibernate code generators for Eclipse, optimize their code for Java 5... so I went home that night and decided I was going to make it happen.

First off, I like my Java folder to be close at hand, so I installed the Java 5 jdk first, disabling the automatic installation of the JRE, because the install seemingly won't let me change the install folder of the JRE. Then I installed the JRE seperately. In the end they were located in C:\Java\JDK.. and C:\Java\JRE... respectively.

Then moving on to Flex Data Services (integrated with JRUN edition). In FDS2 I opened the jvm.config file in C:\fds2\jrun4\bin and changed the line java.home=C:/fds2/UninstallerData/jre to java.home=C:/Java/jdk1.5.0_07. I also moved the JRE in uninstallerdata to my desktop to make sure it wasn't being used. I then started FDS2 and it started up fine. (NOTE: originally I pointed it to the JRE, but loading my test .JSP page would fail because it couldn't find com/sun/tools/javac/Main).

Incidentally I also added the JAVA_HOME environment variable to my XP machine and pointed it to the JDK. This takes care of Flex Builder and the Flex SDK as well. (I tested this further in fds and it appears that the jvm.config setting overrides the java_home variable - so if you want to use the java_home for fds2, blank out the value in the jvm.config).

Finally, when you start up the Adobe Flex 2 Command Prompt, it tells you what version of Java it's using. I haven't had any issues at all since upgrading to Java 5. Looks like the instructor was right after all.

My Max Experience in a Nutshell

Overall it was a worthwhile trip. I had a chance to put faces to a lot of the names I've come across in my Flex related web travels, forums and blogs. I was lucky enough to talk Cairngorm with Stephen Brewster, Flex Data Services with Jeff Vroom, ArrayCollections with Matt Chotin, Flex Builder with Mike Morearty, Flex Compiler with Roger Gonsalez. And many more. I was invited by the Adobe flex team to share my experiences and opinions with Flex 2.0

I got wowed by Alex Uhlman's cinematic effects seminar... truly cool stuff. I got a glimpse into the up and coming ModuleManager, now in 2.01 beta, while attending Roger Gonzales' seminar. I met several bigtime Flexcoder forum posters, and chatted on several occasions with Dimitri, getting his take on some of my application architectures. I got to meet the entire Flex team while scarfing down free cookies and I got to talk Framework with the Adobe Consulting guys out of Scotland (Iteration Two folks).

The venue itself was OK. The Venetian is just too big. There were folks staying at the Imperial Palace that could make it from their room to the conference faster than I could from my room at the Venetian. Plus they use this sickly sweet smelling air freshener that starts to permeate through all your clothing and doesn't get any better. The food at the conference was OK as well, however the stupid xylophone they started banging away on at 7:35am to let people know breakfast was ending at 8:00 is something I could have done without. Plus closing it down at 8am was particularly cruel, considering the open bar function at the Palms on Wednesday night. I think that the Palms venue was enjoyed by many but I'm getting old, so the music inside was too loud to talk and the temperature outside dropped quickly.

The content of the sessions and the people that we came to hear speak are what made this conference worthwhile. The vastness of the conference center, the long escalators, the bizarre schedules, the extremely brief exposure to food and drinks during the day, the questionnable venues were all a huge overkill. My advice for next year? Drop the blue man group 15 minute show and take that money to subsidize the ticket price of bringing my wife to the Palms.

Flash 8, Flex 2, LocalConnection

Well today wasn't fun. I'm not huge into graphics or Flash for that matter. Sure I've done the occasional Flash movie but generally I stay away from things that are not code heavy. The challenge today was to create a clickable imagemap. Now from what I've been able to gather there's really no simple way to insert an Image in Flex and then draw different clickable regions on it. A good example of this would be a clickable interactive map, something we see very often. This little tutorial is directed at those of you that are as flash clueless as I am.

Ok let's get to it. The quickest way to do this is to create a clickable button in Flash 8 and then add some code to it:

1. Create a new Flash Document.
2. Choose File > Import to Library. This will import an image that will become a button. Locate the image and click Open. The image will be saved in the Library.
3. Find the image in the right Column list. Select the image with the Arrow tool. Drag it to your stage.
4. Right click on image, Choose Convert to Symbol from the popup menu. Name the symbol "button", choose Button from the Behavior list and click OK.
5. Right click on the image. Choose Actions from the pop-up menu.
6. This opens up the action pane. Now this next step is important, MAKE SURE you have Script Assist ON!
7. Paste in this code:


outgoing_lc = new LocalConnection(); outgoing_lc.send("lc_name", "helloFlex") delete outgoing_lc;8. If Script Assist is on you should see it wrap the code into a nice on (release) {}function.
9. File Export - Export Movie .. at bottom of properties dialog box make sure you change it to Access Network Only (this is default for Flex apps and both swf's must be the same or you get a nasty error). Call it test.swf.

That pretty much sums up the Flash part of this little exercise. Once you have your test.swf file, drag that into your Flex project. Then embed it in your mxml application as so:
Then in the script section add the following code:
private var fromSWF:LocalConnection; private function initApp() : void{ fromSWF = new LocalConnection(); fromSWF.client = this; fromSWF.connect("lc_name");} public function helloFlex() : void{ mx.controls.Alert.show("hello from flash");}Save and Run. It should work. There's a few far more complex examples of this out there on the web like http://weblogs.macromedia.com/pent/archives/flex_2/index.cfm - scan down the page for "Using ActionScript 2 SWFs with Flex 2", which ultimately helped me figure this out. Again I like to break it down to its simplest form, and build everything else up from there.

ListCollectionView: Different perspectives on data

In a recent project one of the challenges was to display data to the user in a variety of different ways with little overhead. In the .net world we used DataViews to create multiple perspectives on the same DataSet. This included sorting and filtering the data without needing multiple copies of the data in memory. When I first started snooping around in Flex I figured there had to be a way to get the same functionality, and soon I found the ListCollectionView.

As a side note, I'll soon start putting running samples up here with source code, just been too lazy to ftp them up to my server. Anyway let's dig in to the code. First we have a handy dandy xml data file:

Then we have to load the xml into an arraycollection, however several of the boolean properties will need to be reworked during the data load. Here's what that looks like:
...private function resultItemHandler(event:ResultEvent):void { var source:ArrayCollection = itemConn.lastResult.items.item as ArrayCollection; var cursor:IViewCursor = source.createCursor(); var result:ArrayCollection = new ArrayCollection(); while (!cursor.afterLast){ var currentObj:Object = cursor.current; var cv:String = currentObj["rebate"]; cv = cv.toUpperCase(); var newValue:Boolean = false; if (cv == "YES" ){ newValue = true;} currentObj["rebate"] = newValue; cv = currentObj["discontinued"]; cv = cv.toUpperCase(); newValue = false; if (cv == "YES" ){ newValue = true;} currentObj["discontinued"] = newValue; result.addItem(currentObj); cursor.moveNext();}itemsIS = result;}So now we have an ArrayCollection of itemsIS, let's add a DataGrid and set the dataprovider to this collection:
The next step requires a filtered view that will only show discontinued items, so we're going to add a LinkButton
and then add the following code to our script section:
[Bindable]private var itemsDiscontinued:ListCollectionView;public function handleDisc():void{itemsDiscontinued = new ListCollectionView(itemsIS);itemsDiscontinued.filterFunction = function ( item:Object):Boolean {return item.discontinued};itemsDiscontinued.refresh();itemDG.dataProvider = itemsDiscontinued;}In this function we are creating a ListCollectionView that wraps our itemsIS collection. Then we create and set the filter function inline, and call a refresh(). Then we set the dataProvider of the datagrid to our ListCollectionView. You could add any number of "views" on the data in this way, and then let the user switch quickly between them.
Here's the code in action

Channel.Connect.Failed in locally compiled FB App

Just a quick post today. Recently I've had to switch over to building FDS Flex Projects in Flexbuilder that are set to "compile application locally in Flexbuilder". This is just in case the next update to Flex only covers Flex and not FDS - upgrading my fds projects will be so much easier.

Now for the most part things work fine but the other day a fellow coder asked for my help getting a remote object call () working. The call worked fine if he opened the .mxml file but would fail if he opened either the .html wrapper or the .swf directly. Since the only real difference between those two scenarios is where the compilation occurs, I figured it had to be a compile line argument missing from the Flexbuilder project configuration.

In case anyone else runs into this, just make sure your compiler arguments include the -context-root /contextroot parameter... for example this would be -context-root /flex in http://localhost:8700/flex/myApp/main.html

Channel.Connect.Failed in locally compiled FB App

Just a quick post today. Recently I've had to switch over to building FDS Flex Projects in Flexbuilder that are set to "compile application locally in Flexbuilder". This is just in case the next update to Flex only covers Flex and not FDS - upgrading my fds projects will be so much easier.

Now for the most part things work fine but the other day a fellow coder asked for my help getting a remote object call () working. The call worked fine if he opened the .mxml file but would fail if he opened either the .html wrapper or the .swf directly. Since the only real difference between those two scenarios is where the compilation occurs, I figured it had to be a compile line argument missing from the Flexbuilder project configuration.

In case anyone else runs into this, just make sure your compiler arguments include the -context-root /contextroot parameter... for example this would be -context-root /flex in http://localhost:8700/flex/myApp/main.html

Sizing Blues - Using Canvas to keep it under Control

I find a spend a great deal of time trying to get all the components of my application to play nice with one another. But every now and then, I'll get that nasty vertical or horizontal scroll bar on my application, when I'm quite sure that I've been using percentages for widths and heights throughout.

So then the search begins, from the top layer, the application, I start to give different background colors to different containers, and each time I color a container I assign it a fixed size. Step by step, layer by layer, I will eventually find the component that isn't playing along. Most of the time it's either some form controls where the sum of their sizes is causing the percentage amounts to be ignored, or it's an image that's too big.

One of the more common pitfalls is adding a form container to an HBox or VBox. In this case, if the controls are too wide or too tall, the form will simply push out the rest of the containers in the app. Of course I could constrain the size of the form or the container of the form, however then I risk losing the cool auto-grow features of flex. Yet if the screen size is too small, I'd like the scrollbars to be restricted to the container closest to the source of the error.

What seems to work best, I find, is wrapping controls that risk causing this distortion inside a Canvas control. So, in other words, instead of:

I would suggest using:

The Canvas will popup scroll bars and contain the distortion, but will also autogrow with the app.

You can find an example of a little app I wrote that demonstrates this concept here. Right click on the app to get the source code.

DataGrid Search with Highlighted Matches

Today's challenge: Give the user the ability to search a Datagrid and then simply highlight the matching rows in the Datagrid. The first problem was figuring out how to programmatically highlight specific rows in a datagrid, and after some googling I stumbled upon Mike Nimer's blog entry CustomRowColorDataGrid Component. He has basically extended the DataGrid to allow for a way to manipulate row appearance based on data, and he's taken it one step further than other examples by externalizing the function from the custom class. Very cool.

The second part is homegrown. I basically have a Hits Array and I use a cursor to search the DataProvider for matches. Any matched record is added to my Hits array. Then when the CustomRowColorDataGrid calls my rowColorFunction, it checks to see whether the item of the current row is contained within my Hits Array, and passes back the highlighted color.

Here's a link to the sample code. Right click the app to get the source!

Flex to .Net via Flex Data Services - Part One

This article, promised a long time ago, half done, has been lying in my documents folder for some time now, just collecting dust. I decided to get back at it and get this badboy blogged. Because of time constraints I'm just going to briefly skim over this first part. Those of you that are familiar with .Net webservices should find most of the code self explanatory.

A few things worthy of mention. I had a heck of time getting the .net webservice to work properly with Java Axis - it took a lot of tweaking the method attributes before it worked. My primary goal was to make sure my webservice was not passing back simply a collection of generic Objects, but rather a collection of say Employee Objects. Employee objects would also then be recognized as such by the Java client, which makes coding on the Java side somewhat easier.

You can find the code HERE. It's a zip file containing the webservice I will be using thoughout this series of articles. I've kept most of the default namespaces and left the code fairly simple. For this project I am using the Employees table in the Northwind databaes and am connecting using a trusted connection.

Please download the code and get the webservice up and running. In the next part I'll show you how to consume the webservice using a Java client.

Flex to .Net via Flex Data Services - Part Two

In part two of this series I will focus on creating java classes that consume .net webservices. Again, I just want to warn the java savvy folks out there that some of the things I cover are just common sense, and that this is geared more towards folks who have never touched java.

To complete this exercise you will need to download and install the following:


The Java JDK into C:\java\jdk1.5.0_09

Apache Axis 1.4 into c:\java\axis-1_4

Apache Ant into c:\java\ant


Create a working directory. In this directory create a batch file called run.bat and paste the following text in and save (be sure to remove any linebreaks from the last 3 lines).

set AXIS_HOME=C:\Java\axis-1_4
set ANT_HOME=C:\Java\ant
set JAVA_HOME=C:\java\jdk1.5.0_09\
path = %path%;c:\java\ant\bin;c\java\jkd1.5.0_09\bin;
set CLASSPATH=.;%AXIS_HOME%\lib\axis.jar;%AXIS_HOME%\lib\commons-discovery-0.2.jar;%AXIS_HOME%\lib\commons-logging-1.0.4.jar;%AXIS_HOME%\lib\jaxrpc.jar;%AXIS_HOME%\lib\saaj.jar;%AXIS_HOME%\lib\wsdl4j-1.5.1.jar


This batch file will need to be run each time you open a command prompt. Alternatively, if you are going to be doing this alot, you can add these variables and paths to your Environment Variables.

Next you will need to create another file called build.xml in the same folder, with the following text:








I'm not going to spend a great deal of time explaining the structure of this file or on how Ant works... my brother, a java guru, was kind enough to help out with this. Because I'm not using any Java IDE yet, I have to use Ant to compile my classes for me. This is the simplest build file I could muster, and it basically tells Ant to compile all my java source code into .class files, and put them in the same folder.

Finally we're ready to start playing with the webservice. Open a command prompt window and navigate to your working folder. You will need to have completed and successfully tested thet .net Webservice in Part One before you can continue here. Type in:
java org.apache.axis.wsdl.WSDL2Java http://localhost/WebService1/Service1.asmx?WSDL
and hit enter. You might see some warnings but no errors. Please ensure the URL of the webservice coincides with your own configuration!

If the command worked... you should now see a new folder structure in your working folder, called org/tempuri. Using Explorer, take a look inside the folder and you will see a bunch of .java files. These build the core classes for accessing your .net webservice. The next step is to build a java console application that will use these classes to call a webservice method. Create a text file in the org\tempuri\ folder called GetEmployees.java and paste in the following code:

package org.tempuri;import java.util.*;public class GetEmployees{ public static void main(String [] args){ try{ Employee[] employees; Service1Locator sloc = new Service1Locator(); Service1Soap sport = sloc.getService1Soap(); employees = sport.getEmployees(); System.out.println("Number of Records: " + employees.length); List list = Arrays.asList(employees); for (int i=0; i employees.length; i++ ){ System.out.println(employees[i].getLastName()); } } catch(Exception e){ System.out.println(e.getMessage());} }} Save this file, then go back to your command prompt window and type in Ant, hit Enter. Hopefully you will see the words "BUILD SUCCESSFUL". Finally let's test out our little java application. Type in java org.tempuri.GetEmployees. You should see a list of lastnames. If so, then you have successfully completed part 2.

I would like to mention that even doing this a 3rd time myself I still encountered a multitude of errors. If you do have problems, just post it here and I'll help as best I can.

The deal with embedded fonts, buttons and Rotate

Tonight I struggled with a problem I've faced before, only last time I didn't blog or write down my solution anywhere. I'm on a quest to create a vertical Accordion. Now the fastest way to do this would be to simply apply a rotate effect to it. Here's the code:

private function setAccordion():void{ var rot:Rotate = new Rotate(); rot.angleTo = 270; rot.duration = 1; rot.originX = acc.width/2; //need it to rotate around it's center rot.originY = acc.height/2; // -- " -- rot.target = acc; //acc is my Accordion control rot.play();}
I figured this part out a while ago. Without the originX and originY properties set, your control can disappear completely, especially if it's x and y are set to 0. I am currently calling this function from Initialize and have not encountered any issues. What I was having a problem with is that my Accordion header text would disappear during the rotation. Now I know that if I embed a font:
@font-face { src:url("lucidaGrande.swf"); fontFamily: "Lucida Grande";} Application{ fontFamily: "Lucida Grande"; }then the text of my controls should remain intact thoughout the rotation. But this didn't work. I could clearly see that the font in my Accordion Header was not the embedded font, nor was it the default system font. I dropped a button on my application and saw the same behaviour. It wasn't till I added a label that I saw the embedded font appear.

I tried quite a few things... but in the end it turned out that the above Styles only applied to controls that display text with a default fontWeight of Normal. This would explain why the AccordionHeader, which I believe extends Button, and the Button controls didn't render the embedded font. I modified my css:
@font-face { src:url("lucidaGrande.swf"); fontFamily: "Lucida Grande"; fontWeight: bold;} @font-face { src:url("lucidaGrande.swf"); fontFamily: "Lucida Grande"; fontWeight: normal;} javascript:void(0)PublishApplication{ fontFamily: "Lucida Grande";}and everything worked just beautifully. Of course, now I need to figure out how to rotate the canvas' within the Accordion back to their original position. And figure out how to keep the Accordion in the same place, and why there's a vertical scroll bar now... ack. It never ends...

On a side note, I also stumbled upon a property called
rotation. This is a nice shortcut alternative to the rotate.play, however without the benefit of being able to set originX and originY.

Getting Effects to play when transitioning back

Simple little task. Click a button [State:Login], have it fade out, change viewstate, have new panel fade in [State:Register]. Works like a charm. Now, click button on panel, have panel fade out, change viewstate, have button fade back in. Also do the same thing with the WipeUp and WipeDown effect.

Problem. Transitions to the Register state work fine, but transitions back to the original Login State don't. The panel just disappears, no fade, and then the button [State:Login] fades back in nicely. It appears that the controls in the Register State are removed by default before any effects can play visually on them. Using a Sequence and setting the duration of the Panel fade to 10 seconds proves that the effect does play, since it delays the fade in of the button [State:Login], however the control is no longer visible because we're no longer in the Register State.

I realize this is probably confusing... but those of you that have come across this same problem will recognize it. I poured over the LiveDocs but it took just alot of troubleshooting different ideas before I got it working. I've posted a working demo in my Flex Projects column to the right. As usual, right click on the demo to get at the source.

Installing FDS with JBoss and IIS

Here's the initial steps.



Download Jboss and run locally on my dev box. Install Flex Data Services. Unzip the FDS Admin, Flex and Samples files into folders of the same name with a .war extension, and drop these into the C:\Java\Jboss4\server\default\deploy folder - I find unzipping them first let's me work on the files more easily.

Configure mySql support. Drop a copy of the mysql-connector.jar in the C:\Java\Jboss4\server\default\lib folder. Create a datasource xml file called mysql-ds.xml in the C:\Java\Jboss4\server\default\deploy folder, looks like this:
crm jdbc:mysql://localhost:3306/crm com.mysql.jdbc.Driver user password

Test the sample apps locally. This included Hibernate apps and all the sample apps. Also, a little flex app I wrote that uses remote calls and javamail to send email notifications.

Once I was confident that Jboss was running all the flex apps flawlessly, the next challenge was figuring out how to get jboss to run as a windows service. I downloaded the zip from this website, ensured that my JAVA_HOME and JBOSS_HOME system variables were set properly, namely without a trailing backslash, then ran "install default" from a command line. It successfully created a JBoss service, which worked great. I was now ready to move my stuff to my IIS Server.

I basically zipped up the jboss and javaservice folders and ftp'ed them up to the server. While it was uploading I installed the Java SDK, mySql, mySqltools and FDS on the server, in the same folders as on my local dev box. I setup my system variables JAVA_HOME and JBOSS_HOME, copied my data over to the mySQL data folder on the server. When the upload was done I unzipped my jboss and javaservice folders into my java folder, again keeping it exactly like my local install configuration. I ran jboss manually and tested all the sample apps. Then I installed it as a service, ran it and tested again.

The next test was hitting the sample applications from the web, outside my firewall. I could get the apps to launch however I was not getting any kind of connection... probably because my ISP blocks most ports by default (/sigh), including the default rtmp ports defined in the services-config.xml. So I went into the configuration files and added my-http to all the channels as the failover second channel. I restarted jboss just to be safe ( I find that hotdeployment on jboss seems to randomly end in out of memory errors!) and the apps did start working.

Now all the samples apps are setup by default to compile on the server - but my goal was to host the flex apps in IIS and not the app server. To test this, I had written another flex application that was set to compile locally in Flexbuilder. The advantage of this approach was that technically the swf files generated should be hostable on any webserver. On my local machine the app ran fine, but copying it up to the server gave me a channel connect error. The culprit here was the services-config.xml. By default the port used by any flex app is the same port the app is being served up on uri="http://{server.name}:{server.port}/{/{context.root}/messagebroker/http". On my machine IIS is running on 80, and jboss is configured to listen on 8800. I hardcoded the config by replacing {server.port} with 8800, recompiled my app and then uploaded it to my IIS folder. And that did the trick!

How to keep db connections alive in FDS/Hibernate

Struggled with a good title on that one. Anyway... here's the deal. I noticed a while back that if i left my fds server running over night, and in the morning tried to open the sample CRM application, well, it would fail. Fail so badly in fact I'd have to restart or redeploy to get it working again. I'd get an error in the fds log that looked something like this
SEVERE: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Software caused connection abort: socket write error
Communications link failure due to underlying exception:
...
So yesterday I decided to see if I could fix this. It turned out to be a very very long day. Here are the lessons I learned.

Lesson 1: By default, mySQL terminates db connections after 8 hours of inactivity
Here are the default mySQL settings:

#The number of seconds the server waits for activity on a connection before closing itwait_timeout=28800#The number of seconds the server waits for activity on an interactive connection before closing it.interactive_timeout=28800For the remainder of my testing I changed these values to 300 in the my.ini file so that my connections would close after only 5 minutes of activity. A much shorter timeframe for testing! So the initial problem is that once mySql closes down the connection, Hibernate does not natively manage this connection and reopen it. If you connect directly with a jdbc connection you may run into the same issue. The trick is to use some kind of connection pool manager to keep the connections alive... the question remains, how can we achieve this?

Lesson 2: Using App Server JNDI datasources gives you connection pooling
In jrun or jboss, it is possible to create jndi datasources. These will then be managed by the application server. I created a jndi datasource for the crm database that comes with FDS which I recreated a while back in mySQL. Creating this datasource involved adding the following configuration to my jrun-resources.xml in the \fds2\JRun4\servers\default\SERVER-INF folder:
crm com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1:3306/crm username password false jrun.security.JRunCrypterForTwofish true true true 1 1200 30 20 false 5 30 crm Pool 0 2147483647 20 420 5 true false false READ_COMMITTEDThe key thing to note here is the jndi-name I've given this datasource. In Jboss I added a file called mysql-ds.xml to my deploy folder which looks like this:
crm jdbc:mysql://localhost:3306/crm com.mysql.jdbc.Driver user password 5 20 4 I've kept the jndi names the same in both jrun and jboss so that it's easy for me to deploy my apps from one to the other. I ran some tests after I did this. Hibernate - still using it's own connection - would still fail permanently after the connection timed out. Yet the crm app that was configured to use jdbc/jndi directly (ConnectionHelper.java):
javax.naming.Context context = new javax.naming.InitialContext();return ((DataSource) context.lookup("java:crm")).getConnection();would fail once and then reconnect successfully. It looked like I was on the right track, now it was time to reconfigure Hibernate.

Lesson 3: Hibernate is not recommended for connection pooling
I had to configure Hibernate to take advantage of my jndi datasources. Here's what the hibernate.cfg.xml looks like for both jrun and jboss:
java:crm org.hibernate.dialect.MySQLDialect[...] I saved my changes, restarted the server, ran my app, waited for the timeout, ran the app again, and even though it hiccupped on the first try, the connection was reestablished on the second try. But why this initial hiccup? Shouldn't there be some way to configure it so that even this initial error can be avoided? I still had much work to do!

Lesson 4: Make sure to have the latest mysql jdbc drivers installed
It turns out that Jboss jndi datasources can be configured to actively ping db connections and keep them alive. Yet I kept getting errors after configuring my datasource to do this 'pinging', and it turned out I was running older jdbc drivers. I upgraded to the latest ones and the errors went away. Here's the jboss datasource file with the ping features enabled:
crm jdbc:mysql://localhost:3306/crm com.mysql.jdbc.Driver user password 5 20 4 com.mysql.jdbc.integration.jboss.ExtendedMysqlExceptionSorter com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker Since my production environment is Jboss, and it had already been a long day, I decided to not worry about figuring out how to do the same in JRun. If anyone out there knows this, please leave a comment!

Lesson 5: Hibernate must be told that it's connection is now being managed
At this point i was able to retrieve data without error, despite connection time outs. When I went to update a record, however, I got a cool new error:
java.sql.SQLException: You cannot commit during a managed transaction!
So, I did some digging and changed my hibernate.cfg.xml to this:
java:crm org.hibernate.dialect.MySQLDialect org.hibernate.transaction.JTATransactionFactory org.hibernate.transaction.JBossTransactionManagerLookup [...] As you can see this is specific to Jboss. There are several other TransactionManagerLookups available that you can read about here

Summary
I spent alot of time on this yesterday, so this blog might seem a bit scarce and a bit rushed. Basically all the configuration files are here for you to use and customize. If you have questions, please ask. Again, this is blogged here for my benefit as well as yours. I would not want to have to redo this from scratch 6 months from now!

Many-to-Many using FDS & Hibernate

Douglas McCarroll recently sent me an email asking if I'd had any luck getting Hibernate, Hibernate Tools for Eclipse and FDS to work with many to many relationships. I quickly threw together an example that I had built for a client a couple weeks ago, but in that particular case it wasn't a true many-to-many... I had a student, course and registration table but my registration table had it's own unique ID so really, it was just a combination of 2 one-to-many relationships. For most situations this would probably work however, as he pointed out, some clients might already have a db in place and would be unwilling to make a change just to accommodate the poor starving flex programmer.

Now back in the summer I did attempt to get a true many-to-many relationship to work using Hibernate Tools. What I didn't realize at the time is that the tools didn't yet support this feature. Then i saw this link and decided to give it another go.

I will be using mysql for this example. It is based loosely off the crm db that ships with FDS. Here's the scripts for the 3 tables in play:

CREATE TABLE `crm`.`employee` ( `id` int(10) unsigned NOT NULL auto_increment, `First_Name` varchar(45) NOT NULL default '', `Last_Name` varchar(45) NOT NULL default '', `Email` varchar(45) NOT NULL default '', `Phone` varchar(45) NOT NULL default '', `Title` varchar(45) NOT NULL default '', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `crm`.`event` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(200) NOT NULL default '', `eventDate` datetime NOT NULL default '0000-00-00 00:00:00', `eventTime` varchar(45) NOT NULL default '', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `crm`.`eventemployee` ( `eventID` int(10) unsigned NOT NULL default '0', `employeeID` int(10) unsigned NOT NULL default '0', PRIMARY KEY (`eventID`,`employeeID`), KEY `FK_eventemployee_1` (`employeeID`), CONSTRAINT `FK_eventemployee_1` FOREIGN KEY (`employeeID`) REFERENCES `employee` (`id`), CONSTRAINT `FK_eventemployee_2` FOREIGN KEY (`eventID`) REFERENCES `event` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;As you can see I have 3 tables, an Employee table, an Event table and an EventEmployee table. The EventEmployee table only has 2 fields, each a foreign key to the corresponding table.

The next step was to ensure I had the right version of the Hibernate Tools installed in Eclipse (3.2.0.beta7 or greater). I'm not going to spend any time on explaining how to configure the Hibernate Tools.. needless to say I got the Tool configured to reverse-engineer my db and it created these .hbm.xml files:
I also configured the Tools to create my domain code. What I found encouraging is that it only created the Employee.java and the Event.java classes, no EventEmployee.java class. Things were looking up! Ok, now it was time to configure the corresponding destinations in my data-management-config.xml file. I took a bit of an educated guess here, since the fds documentation surrounding the metadata tags is pretty weak... lucky for me I got it first try - I guess I spend way too much time here :)
true flex.data.assemblers.HibernateAssembler application 20 samples.crm.Employee false true true flex.data.assemblers.HibernateAssembler application 20 samples.crm.Event false true Finally in my flex application I built my correponding .as classes:
package samples.crm{ import mx.collections.ArrayCollection; [Managed] [RemoteClass(alias="samples.crm.Event")] public class Event{ public function Event() {} public var id:int; public var name:String; public var eventDate:Date; public var eventTime:String; public var employees:ArrayCollection; }}package samples.crm{ import mx.collections.ArrayCollection; [Managed] [RemoteClass(alias="samples.crm.Employee")] public class Employee { public function Employee() {} public var id:int; public var firstName:String; public var lastName:String; public var title:String; public var phone:String; public var email:String; public var events:ArrayCollection; }}Then I just created a quick application with 2 datagrids: one id="dg" with a dataProvider="{employees}" and the other id="childDg" with a dataProvider="{dg.selectedItem.events}" - by setting lazy to false on my many-to-many relationship in the destination, it's guaranteed that the child records will load automatically. You could also turn this around... create a datagrid that points to {events} and have the other point to {dg.selectedItem.employees}. By the time you get to this point you can do pretty much anything anyway. The real trick was getting here!

Autosizing Datagrid with Horizontal Scrolling

Today I was tasked with creating a spreadsheet like datagrid, one with more columns than what the available real estate would be able to show. The datagrid was to always use the maximum screen space available so that for those users with huge budgets and subsequently huge monitors would not need to scroll. For all other, more mortal users, the datagrid should simply scroll off to the right, with a nice horizontal scroll bar.

I figured this would be easy. Turns out it's a bit tricky. If I set the maxWidth of my datagrid to something smaller than the sum of my column widths, the desired behaviour would occur. I'd get a nice horizontal scroll bar and the columns would span out to the right. The problem with maxWidth is that it does not accept percentage values. So if I want the datagrid to use up 100% of the width of the parent container, I can't use maxWidth.

I tried sticking the datagrid in a canvas, thinking i'd be able to use the scrolling of the canvas to quasi hover/move over the datagrid rendered in its entirety underneath, but the vertical scrolling didn't really work out well. Perhaps someone else might have more luck with this approach. I kinda wanted to get back to using the scrollbars in the datagrid, as it seemed that this HAD to be possible!

I figured the solution had to lie in maxWidth. I put the datagrid inside a canvas and made the canvas size percentage based. I then, in a resize() function triggered by creationComplete of the app, assigned the value of the width of the canvas to the maxWidth property of my datagrid. This seemed to work. I also tried to have the resize event of the app call this function instead but I'd get null errors. Turned out I needed to assign the event listener on creationComplete.

Everything looked good, the datagrid was resizing with the canvas. At certain times however the datagrid seemed to lag behind and not fill the canvas properly. Using callLater fixed this. Here's the Demo. Right click on the demo to get the source.

DoubleClickEnabled & other little Flex tips

Want to code against double clicks in Flex? Don't forget to set this property to true!

Adding child objects to a canvas or some other container and need to keep the scroll moving down so users can see the new objects? Put this in a function:
canvas.verticalScrollPosition = canvas.maxVerticalScrollPosition + 45;
And remember to CallLater, this gives Flex a chance to lay the new object out and get you the right maxVerticalScrollPosition!

Are those child objects some kind of data entry control? Attach an event listener to the event
FocusEvent.FOCUS_IN for the object and point it to a function that does this:
private function test(event:FocusEvent):void{
canvas.verticalScrollPosition = event.currentTarget.y - canvas.height + 45;
}

Having issues with the custom Item Renderer in your TileList not updating when the underlying data changes? Make sure you're not using an ArrayCollection, it doesn't quite work every time.

Pulling data from a .Net webservice and having to parse out the date from the xml with your own Date Utility? Just remember that in AS3 months, hours, minutes and seconds are 0 based... in other words, October is month 09, not 10. That took me a while to clue in to.

Want to display hierarchical data relationships in a tree view? Stick the child objects in an arraycollection and assign it to a property called children in the parent object. This can be repeated down the chain as often as you like but remember it can get a bit slow quickly. Then point the Tree dataProvider property at the topmost object of the hierarchy.

Sometimes building a Flex front end on a .Net webservice back end can get complicated, especially when the developer (me) doesn't have access to the webservice. If the .Net webservice is designed right, simply taking the resulting xml of the webservice calls and using HttpService calls to load the xml works. When it comes time to use the webservice directly, simply replace the HttpService calls with WebService calls. Works like a charm!

Here's something silly. I stuck aTabNavigator in my view, and tried to capture the click event on the tabs. I tried pretty much every event I could find but not a single one would trigger when clicking on the tab. I replaced the tabNavigator with a TabBar and a ViewStack, and then was able to trap the tabIndexChange event to get the desired result.

Not my usual blog style but things are pretty busy these days. I hope to blog more again in the new year.

Setting up Db2 v9 as a Coldfusion Datasource

In the last few weeks I've had the opportunity to get to know Coldfusion just a little bit better. One of the first challenges I faced is getting CF talking to Db2, so I could take advantage of the CF Extensions for Flexbuilder and that funky Wizard. To be precise I used ColdFusion MX 7.02 and DB2 Community Express Edition v9.1

This doesn't just apply to Flex, but maybe others might find this useful. Keep in mind I have only tested this in Windows:


Install the db2 client or get access to a machine that does. I installed db2 in the default folder on my dev machine to get this working.
Copy C:\Program Files\IBM\SQLLIB\java\db2java.zip to C:\CFusionMX7\lib. Important: Make sure db2jdbc.dll is in the path somewhere or copy it to same folder!
Restart Coldfusion MX. Login to CF Admin. Go to Datasources.
Add new Datasource:
driver type Other
CF DataSource Name: [sourcename]
JDBC url: jdbc:db2:[dbname]
Driver Class: COM.ibm.db2.jdbc.app.DB2Driver
Driver Name: DB2Driver
username: [name]
password: [password]
[Submit]
Couple things to note. Out of the blue the other day suddenly I started getting this db2jdbc not found in java path error... I figure something I installed hooped my system path. Instead of messing around with why, I figured out that just copying the dll into my CF lib folder fixed the problem. The ...app.DB2Driver is specific to Windows OS I believe. The username and password are usually a Windows account... probably best to use the account that has admin rights to db2 at least until you get it working.

I also did spend a good chunk of time trying to get the built in driver to talk to db2... I personally had no luck whatsoever, and I have read in other places that the drivers generally are only backwards compatible... the driver that ships with CF is definitely not v9, I think it might be v7... not sure though. I did test the backward compatibility claim by using the v9.1 jdbc driver against a db2 v8.x datasource and it worked fine.

Export Data from Flex App using Coldfusion

It's been a while since I blogged, just so amazingly busy these days that I barely have time to breathe, let alone blog. I'm currently up to my neck in building a flex app that uses Coldfusion 7.02 and DB2 v8/9 on the back end. I've never used Coldfusion before so it's been one hell of a time. I managed to figure something out today that I think is definitely worth sharing. In the app I was required to find a way for users to 'export' or 'save' their work to their drive, in a format they could easily open directly. That eliminated shared objects and I wasn't allowed to use a third party tool like swfStudio to build a helper app and use Localconnection to get the job done (can't wait for Apollo!)

I don't have much time so I'm going to just paste code and explain a bit.

Step 1. Enable session management in the CF app. Create an Application.cfm file in the root of your CF application, put this in it:

Step 2. Create a CFC that takes whatever data you wish to save and sticks it in a session variable, return a boolean to let Flex now this worked(Export.cfc):
Step 3. Create a CFM file in the application root that will grab the session variable and output it to http, while flagging it as an attachment (this causes nice save as popup to appear). In my example I'm creating an xml file and I ran into issues with whitespace, hence the cfsetting.. this fixed the problem for me (getFile.cfm)
WriteOutput(session.exportData);Step 4. In flex declare the remote object that will call the cfc:
Step 5. Add your code to call it and handle the result. The result, on success, will make an httpservice call to the CFM you created:
private function test():void{ exportManager.toXml("" + "" + "The application has successfully exported this file" + "Eventually the actual data will be passed into this function" + "");}private function login_result(event:ResultEvent):void{ if(event.result == "true"){ var request:URLRequest = new URLRequest("getFile.cfm"); flash.net.navigateToURL(request, "_self"); }}Conclusion. Basically that's it. I had issues with the session not persisting from setting the variable to getting it, but adding the application.cfm fixed that. I can now push any xml data to the browser for saving. There's lots of other possibilities here as well, such as exporting to Excel or Word, but there's other articles out there that you can google which explain how to do those specific tasks in Coldfusion. Hope this helps!

A closer Look at IFrames and ExternalInterface in Flex

Well I've been super busy as usual, working on some pretty cool stuff, still managing to only put food on the table but also sticking to my guns and doing only Flex projects. Of course, my blogging has suffered dearly.

In one of my current projects, I am faced with the challenge of somehow embedding IFrames inside my flex app, however without having any control over the html wrapper that my Flex app will sit in. Sure I could 'advise' users on adding the appropriate javascript functions and the hidden div element at the bottom of the body, as we've seen in other Flex Iframe examples out there. But I figured there had to be a way to do this without needing to rely on this external dependency.

As it turns out I can do inline Javascript function calls within my ExternalInterface.call, an example of this would be:


ExternalInterface.call("function(){return window.location.href;}");which is a simple little function to quickly get the address of the current page. Another handy example is this one:


ExternalInterface.call("function(){document.location.href=document.location;}");This is a quick way for a user to 'logout' of the flex application, it simply reloads the web page. So as you can see, we can do a great deal without ever needing to touch the html wrapper. So why not do the same thing with Iframe support? Here's what I came up with:

ExternalInterface.call("function(){" + "var tempIFrame=document.createElement('div');" + "tempIFrame.setAttribute('id','vyFrame');" + "tempIFrame.style.position='absolute';" + "document.body.appendChild(tempIFrame);" + "tempIFrame.style.backgroundColor='transparent';" + "tempIFrame.style.border=0;" + "tempIFrame.style.visibility='hidden';}"); I am going to try and create a div element in memory and append it to the DOM. It's best to run this code during the application preinitialize() event. However, before I move on to explain the rest I just want to mention that I did run into some issues here with IE6. As you'll notice I appendChild and then I set the styles. Turns out that if I manipulate a new element too much prior to adding it to the DOM, it just gets all flaky and will not work. Believe me, this was not an easy bug to track down!

Now, we need to change the remaining externalInterface calls as well... things like move, hide, show and source. Building on the example at deitte.com that first got me started ages ago, I changed all the calls as they are found in his IFrame.mxml component:

ExternalInterface.call("moveIFrame",globalPt.x ,
globalPt.y, this.width, this.height);
Becomes:
ExternalInterface.call("function(){" + "var frameRef=document.getElementById('vyFrame');" + "frameRef.style.left=" + globalPt.x + ";"+ "frameRef.style.top=" + globalPt.y + ";" + "var iFrameRef=document.getElementById('vyIFrame');" + "iFrameRef.width=" + this.width + ";" + "iFrameRef.height=" + this.height + ";}");ExternalInterface.call("loadIFrame", source);
Becomes:
ExternalInterface.call("function(){vyFrame.innerHTML='" + "';}");ExternalInterface.call("showIFrame");
Becomes:
ExternalInterface.call("function(){" + "document.getElementById('vyFrame').style.visibility='visible';}");ExternalInterface.call("hideIFrame");
Becomes:
ExternalInterface.call("function(){" + "document.getElementById('vyFrame').style.visibility='hidden';}");
After a bit of testing I did manage to get this to work, sort of. I ended up spending some time playing with the compiler options in Flexbuilder. I found that if I turned off history management, my Iframes wouldn't appear. However removing the script reference to history.js seemed to have no real effect. For those of you that are not Flash-savvy :) it turned out that the only things to really watch out for, and again I am at the mercy of the users who embed my flex app into their html pages, is that the AC_FL_RunContent() has a final parameter setting of "wmode", "opaque" and the object embed tag also contains wmode="opaque". If this setting is not there or set incorrectly the Iframe will appear behind your flash player.

Flex Modules, Compile and Run Time CSS

I've recently become involved in building a very module based Flex app, where the question of css and css inheritance came up, particularly with respect to how Flex handles run time loading of style sheets when they are loaded within not only the shell application but also the therein loaded modules.

Essentially, there are 3 rules that prevail:


The most recent style to be loaded always wins.

Run time overrides compile time styles

StyleManager is a global Manager
Style inheritance is granular to the attribute level
Compile time css will only compile styles found in Application
Let me explain further, and to do so I'm just going to use our trusty

The most recent style loaded always wins
Say you load a runtime style sheet with the following:

Button {
fillColors: #ff0000, #ff0000, #ffffff, #eeeeee; /*red */
letterSpacing:3;
}

Then in a (rather large) module you load another runtime style sheet with this:
Button {
fillColors: #006600, #009900, #ffffff, #eeeeee; /*green*/
letterSpacing:1;
}

You'll notice that the first color style is applied right away, to any buttons in the shell application. However, when the second module finishes loading, all Buttons will change from Green to Red, and spacing will be reduced to 1. To make it even more interesting, you could add an additional module of roughly the same size as the first and have it load its own style sheet. Then the end result is pretty much random, whichever module takes the longest to load wins, the shell run time style never to be heard from again.


Run time overrides compile time styles
In your shell application you add the following:


Once your app loads the run time css, this will be overwritten. Now if you have a huge run time css swf with massive fonts or images embedded in, there's a chance you might even see your original color first and then have it overwritten later. This can cause for some funky effects in your app, in which case you might want to attach an eventListener to StyleEvent.COMPLETE, and hide your interface until that event has triggered using a ViewState or the like.

StyleManager is a global Manager
It that does not distinguish between and . Say you create a custom style class called .myDogAteMyHomeworkButton for Buttons in your module. You then place a corresponding style entry in your compile time or run time styles for this module. Now someone else happens, just happens to use the same exact style class in their module. Or the shell application developers happens to do so. Well again, the last one loaded wins. Your custom style class is never safe. But then again neither are their's. The best thing you can do is be very very unique in your style class naming conventions, and hope for the best.

Style inheritance is granular to the attribute level
Getting back to our original example, you'll notice the style attribute letterSpacing was defined explicitly in both style sheets. Because inheritance is on the attribute level, if you do not specify an attribute in say your run time style sheet for your application, then that attribute can be set in compile time style tags and it will override the default values. What's the lesson to be learned here? If you want to make sure that your runtime css has the final word, then get detailed and explicitly list every style attribute and its value, even if the default will suffice.

Compile time css will only compile styles found in Application
Ever seen this warning "The type selector 'HDividedBox' was not processed, because the type was not used in the application."? Until the dawn of Modules, this was a message I generally ignored. Made sense to me, if I didn't have an HDividedBox anywhere in my application, why include the style? But what would happen to modules that perhaps do use the HDividedBox control but rely solely on the shell application styles for their look and feel? The application doesn't know at runtime that one or more of its modules will need this style defined, so therefore it just ignores it. End result, your HDividedBox in your module will not be styled properly. The solution? Use run time stylesheets. (and that's how this all began!)

SizeableTitleWindow & Custom Skins

Most of you are probably familiar with the SizeableTitleWindow.as that the CF code generator for Flexbuilder spits out, along with a plethora of other useful tidbits of code. In fact that was the only reason I initially installed Coldfusion and the tools - I saw a modal resizable window in Flex and absolutely had to have it!

That was like 8 months ago. Recently I started working a lot more closely with skinning and runtime loading of css. I created some really funky UI's using run time style sheets that I found at http://www.scalenine.com, in particular I like using the Obsidian Theme Skin. However, this skin, like many others, replaces the skins for the Panel control - which, though very cool, breaks the resize function of the SizeableTitleWindow.

In simple terms, an event listener attached to the MouseOver event checks the coordinates of the mouse and if the coordinates fall within the right range, a cursor image is assigned. When the user clicks the mouse, the mouse down event checks which cursor is active and acts accordingly. The only problem is that all the coordinate calculations are based on event.localX and event.localY and those relate to event.target. However when using skins, the event.target isn't the SizeableTitleWindow but rather the skin, so it throws everything off. The result? The east and south cursors don't appear and even when they do, the drag functionality is buggy at best.

I fixed the problem by replacing all localX and localY with event.currentTarget.mouseX and event.currentTarget.mouseY. Also I no longer check to see if event.target is SizeableTitleWindow, and that seems to have fixed it.

Mapping VO's from Flex to PHP using AMFPHP

I sometimes wonder why it is that I never seem to blog till shortly after the midnight hour... oh well... life just gets too crazy when the sun is up. So as it happens, one of my minions spent the better part of today putting together php classes, using a nifty code generator found called DAO Generator by the guys over at Titantic Linux. It seems to do a pretty decent job of generating the sql necessary to create the db table, and then builds three additional files, the VO, a datasource file, and then finally a DAO file that has a ton of functions in it. (and I mean a ton!)

Going to take a moment here to give credit where credit is due... Michael Ramirez's tutorial on Using Amfphp 1.9 with the Adobe Flex 2 SDK is what really got us started in the right direction, it's pretty detailed and yet easy to follow. We quickly were able to get our AMFPHP up and running with the tutorial files as outlined by Michael. Tickled pink by the code generator we figured we could easily start building our own php gateway. But enough background... on to the thick of things.

Passing VO's from PHP seems to be very well covered in numerous articles on the web, and it involves mainly adding a var $_explicitType="tutorials.Person" to the php VO, with a value that corresponds to the [RemoteClass(alias="tutorials.Person")] in the Flex VO. Pretty straightforward and foolproof. But no one seems to spend any time talking about going back the other way.

Generally when a VO is passed from Flex to AMFPHP, it is treated as an Associative Array. In Michael's examples, he treats the ValueObject that is passed back to Save function as just that $valueObject["lastName"]. But we were pretty keen on using the generated code, which actually uses the syntax $valueObject->getLastName(). And this of course, failed, because the $valueObject being passed to PHP from Flex was not in fact being mapped back to the right VO, or any php VO for that matter.

Turns out, after much googling, that only under certain conditions will AMFPHP successfully map an incoming Flex VO to the corresponding PHP VO. In the globals.php, found at the root of the AMFPHP folder structure, you'll find the following line:

$voPath = "services/vo/";

Meanwhile we had been placing our VO in the same folder as our Datasource and DAO files, something like com/crazedCoders/testapp, and this was off the services/ folder, not the services/vo folder. In fact we didn't even have a /vo folder. I found this little tidbit of information: "As for incoming class mapping, remember that if amfphp doesn't find the class to be mapped in the services/vo folder, it will simply deserialize the object as though it were untyped, that is, as an associative array. " in this blog.

It took a little bit of playing around but ultimately, without making any changes to the core AMFPHP files, I was able to get the reverse mapping working successfully. This is what that looked like:

//file: src/tutorials/Person.aspackage tutorials{ [RemoteClass(alias="tutorials.Person")] [Bindable] public class Person { public var firstName:String; public var lastName:String; public var phone:String; public var email:String; }}and then in php:
To test the mapping I added the following function to a PersonService.php file:
//file: services/tutorials/PersonService.php function modify($person){ //this will call a function on person and return it $person->formatLastName(); return $person; }Only if the valueobject was mapped correctly would it be able to call the function on the PHP VO. In Flex I just created a Person object, passed it in to the remoteobject call, and observed the formatting of the last name on the Person object that was returned.

Again, I hope this will save others the time that it took me to figure this out. Enjoy!

Loading Multiple Independent Instances of a Module

So, it's Monday night... my wife's contractions are 13 minutes apart, and it seems I have nothing better to do than blog. Of course, this is more akin to the calm before the storm that will be the next 24 hours and probably the next six months. Eventually I will once again emerge from the dark precipice that lies ominously before me. But on to modules.

I love Cairngorm... I just upgraded all my projects 2.2 and it was painless, nothing like child labor, I'm told. I am working on a project where we have to build all these pretty much independent modules, and in these modules we stick to Cairngorm as well.

The first problem we ran into occurred when attempting to load 2 instances of the same module. ModuleManager, as it turns out, keys modules by url. So if you try to load the same module twice, you're just getting a reference to the same one. There is no way around this (or so I thought) This has a number of repercussions:


Only one ServiceLocator instance can be instantiated - this wonderful little Error message pops up the minute you load a second instance of the module. Quick workaround is to declare the system locator code much like you do model:
private var dataServices:ServiceLocator = ServiceLocator.getInstance();
and abstain from using the mxml format:

All your module instances will share the same model... so if you say do a search, get a searchresult back and stick that in your model, all your modules will display the same search results, which defeats the purpose of having separate file/image search browsers (for example).
Here's a couple other funky things I tried:

Created 2 modules pretty much identical, Mod1.swf and Mod 2.swf. I loaded them up and they both worked fine and independently
Created a copy of Mod1.swf and called it Mod1a.swf. I loaded them up and they both worked fine.
Tried loading two Mod1.swf and suddenly no independence, plus the ServiceLocator error.
I tried wiring up my own ModuleManager, but after a good couple hours I gave up... I was getting all sorts of weird behaviour. I figured out that everything is based around the url that you pass to ModuleManager or ModuleLoader. I was pretty much ready to give up when I had this really silly notion, I did this:

private var count:int;private var spaces:String = "";private function LoadModule():void{ for (var x:int; x < count; x++) spaces += " "; var info:IModuleInfo = ModuleManager.getModule("mod1.swf" + spaces); info.addEventListener(ModuleEvent.READY, done); info.load(); count ++;}private function done(event:ModuleEvent):void{ var visual:DisplayObject = event.module.factory.create() as DisplayObject; tabber.addChild(visual);}Much to my surprise, this hack worked. The modules loaded successfully and ran independently. Of course, I probably need to test this some more, but I figured I'd blog it quick before the trauma of childbirth hopefully graces me with some convenient and kind short term memory loss.

Can Cairngorm and Modules play nice?

Let me say, first off, that my wife gave birth to a beautiful baby girl on Wednesday morning, and they are doing just fine. I've been relocated to the spare bedroom so that I can actually function during the day, however I'm missing about 30 hours of sleep this week that I'll never get back. Having said that, I am blogging today because even though I've sort of fixed my latest issues, I'm not entirely sure I've used the best approach.

This is really a sequel to my previous blog... I am still fighting with getting modules to load properly and independently of each other and the shell flex application. Here's the deal...

I have one complex flex module that is built on the Cairngorm 2.2 framework. In itself, the module works fine, and after the progress from the other day, loading multiple instances of the module into a simple shell works fine too. However, when I tried loading multiple instances of the module into the actual application, things died. Why? Because the shell is built on the Cairngorm framework as well. The minute I add in the line to my shell app, subsequent instances of the module don't load properly. I determined that the shell needed to use a different controller than the module, but that wasn't enough (though still necessary). There were funky things happening again when events were triggered - weird casting errors, events firing across multiple module instances, shared models, etc.

A couple of observations:
CairngormEventDispatcher basically returns a singleton. If the shell app gets an instance of this class, then any Modules that load will use the same instance. So, adding the appcontroller to the application will in fact get an instance of the dispatcher. Running through the debugger, I noticed that as I loaded each new instance of the same module, event listeners were added to the singleton's eventDispatcher. So, say your module was listening for the ContactEvent.LOAD_CONTACT event. If you loaded 3 instances of that module, your controller would execute 3 commands, once for each module.

When an event is received by a command, and you try to cast that event back to its origin, i.e. ContactEvent(event), it will only work in the module that actually originated the event. The other modules will throw the following exception:
" cannot convert com.crazedCoders.moduleTest.event::ContactEvent@4b23281 to com.crazedCoders.moduleTest.event.ContactEvent." Trying to test for it, i.e. if(event is ContactEvent) doesn't work since the event is in fact a ContactEvent. Very frustrating.

If you do not use any Caingorm in your shell application, you will not run into these issues, so for some that might be the quick solution. Sadly I was not afforded that luxury, so I had to find another way.

Since I was trying to treat each Module as an autonomous mini-application, I decided that I needed a CairngormEventDispatcher specifically for each Module and the Application. I created a Factory Class that would do just that. Here's the code:

package com.adobe.cairngorm.control{ import mx.modules.ModuleManager; public class CairngormEventDispatcherFactory { private static var instances : Array = new Array; public static function getDispatcher(obj:Object) : CairngormEventDispatcher { // in order for each module developed using cairngorm to be able // to work independently of the shell and other modules, // we need to create a hash map of cairngormeventdispatchers // that are keyed on module instance or application. // This prevents cross module listening for events, // which is beneficial especially when loading multiple instances // of the same module var ed:Object = ModuleManager.getAssociatedFactory(obj); var parent:String = "application"; if(ed != null){ trace(ed.name); parent = ed.name; } if(instances[parent] == null){ var cgDispatcher:CairngormEventDispatcher = new CairngormEventDispatcher(); instances[parent] = cgDispatcher; return cgDispatcher; } else{ return instances[parent]; } }}}It took me a while, but eventually I stumbled upon ModuleManager.getAssociatedFactory(object). This function *seems* to be able to figure out within the context of which Module (if any) the object was instantiated. If an object belongs to the shell, it returns null, if not, then it returns a ton of information, including a name property that contains a unique name i.e. instance77 for the loaded module. I create a new instance of the CairngormEventDispatcher for each instance and stuff it in the static associative array, then I replace the usual CairngormEventDispatcher.getInstance().dispatchEvent(...) with
CairngormEventDispatcherFactory.getDispatcher(this).dispatchEvent(...));
Now the application shell and each module gets it's own singleton, and the overlap seems to be taken care of.

Again, I welcome any feedback. I'm not particularily fond of this solution, and I hope someone out there can offer a better one.

Can Cairngorm and Modules play nice? Sample App

First I'd like to say thanks to those of you that commented on my previous blog entry. I was inspired to go back and take another look at ApplicationDomain. To be honest, I can't get it to work for me. So I'm just going to put up my prototype application with source code and let you play with it. There is a shell application and 3 very simple modules. The challenge is to have a controller in the shell and still have the modules all work independently of each other. The sample app as it sits on the server works because it's essentially Cairngorm free. Good luck!

Flash.media.Sound & Memory Issues in Flex

Taking a short break from my module woes, I've been working with audio in Flex. In my app I was building a preview intro scan of my listed mp3's. What I noticed is that as the list of mp3's got longer, the memory that my browser was eating up got larger. I haven't really found any articles addressing best practices regarding handling audio in Flex, however I would venture a guess that this has been addressed many times in the past by Flash Developers.

I'm pretty tired so I'll keep this simple. Best way I have found to ensure that an audio stream is destroyed and the memory returned when you stop it:

private var mySound:Sound = new Sound(); private var audio:SoundChannel = new SoundChannel(); private function startPlaying():void{ mySound = new Sound(new URLRequest("music/sample.mp3")); mySound.addEventListener(Event.COMPLETE, completeSound); audio = mySound.play(); } private function stopPlaying():void{ audio.stop(); mySound.removeEventListener(Event.COMPLETE,completeSound); mySound = null; }Trick is to declare the variables outside the function, ensure you configure a sound channel (audio) for your sound, and make sure you that you can reference both from the stop function. Then you need to stop the audio, remove any event listeners, and set sound to null. I found it's also a good idea to do your URLRequest inline, as it seems to get destroyed at the same time as mySound.

Not another Flex, AmfPHP, Cairngorm CodeGen! MAKE IT STOP!

Haven't blogged in quite some time and this is a project that's been half done for far too long. Like everyone else we decided to build our own code generator, just something fairly straightforward that would generate all the DAO code, the Cairngorm code, and a nice little interface to test all the main CRUD and DAD functions we have come to know and love. Lately we've been busy souping up the generated UI, not so much in terms of style... beauty does not live here... functionality however does.

You can get all the gory details by clicking on this link:

http://www.crazedcoders.com/php/codegen.php

We built this code to use AMFPHP, Cairngorm, PHP and Flex 2.01. We've put in place validators, datepickers, checkboxes and textinputs on our forms and generated full Command/Event/Model/Controller classes. We've implemented binding on the generated view form fields. Our code generator will detect relationships between tables and render comboboxes accordingly, for example, if there's a foreign key on a customer table linked to a country table, the customer view will have a combobox linked to the model.countries collection. But I must stop, I'm getting too technical...

Basically, if the generator runs successfully, you're a few clicks away from being able to manage the data in your database from Flex. The generated code is zipped up for you to download. Inside the zip you will find a complete and ready to import Flexbuilder Project and the php packages ready to copy into your amfphp services folder. Further details can be found by clicking on the link.

Using floating IFrames in Flex 3 Beta: wmode buh-bye?

Just a quick one today... we're porting some work to Flex 3 where we do the floating Iframe thing, and noticed some strange behaviour changes. In Firefox, the floating Iframe would briefly flash into view and then disappear, while in IE the Iframe would appear, however if we clicked into the IFrame embedded html page and then clicked outside it somewhere on the flex app, the IFrame would disappear from view.

Took a little bit of sniffing around but in the end the culprit was the html-template\index.template.html file. For some reason, and it might well be a very good reason, the property wmode is no longer included in the flash player tags ("wmode", "opaque" in AC_FL_RunContent() && wmode="opaque" in in FlexBuilder 3. Once we added those back in, the floating IFrame started working again.

Where or where has my intellisense gone?

I'm working on a flex 3 app using the latest flexbuilder 3 beta, both the plugin and standalone versions. For some reason, in some mxml files my intellisense just seems to not work at all. While in other mxml files the intellisense works fine. Turns out that in this latest beta release, Flexbuilder gets cranky if you use double quotations in Metadata Event tags:

[Event("forward", type="mx.events.Event")] will kill your intellisense and your control clicks. You will feel very lonely.

[Event('forward', type='mx.events.Event')] will make everything right again, blue coding skies ahead.

On a side note, the single quote is actually only necessary on the type attribute, intellisense seems to work fine if you use double quotes on the Event name itself.

Hopefully this will be fixed in the next release.

Losing the RollOverColor in TileList

In one of our projects we have a custom effect that plays over each tile as a user mouses over the items in a tilelist. Not getting too much into details, I basically overlay a canvas that appears and disappears as the mouse moves over the tile, giving the illusion that each tile sort of explodes. So the one thing I don't need is the rollOverColor effect, which defaults to a nasty baby blue. Usually I just set the rollOverColor to the same color as the background but that's not working so well on this project, since the background can be an assortment of wallpapers.

Unfortunately there doesn't seem to be any way to disable the rollOverColor, and maybe someone can shed some light on an easier solution. I ended up extending TileList with my own mxml component and overriding the drawitem function, as follows:



As you can see, I override the selected and highlighted parameters with false, thereby eliminating the selected and roll over effect. Seems to work quite well. I now use this mxml component instead of TileList throughout my applications.

DataServiceTransaction & LCDS

Just a quick blog note on something that I've now wasted a good day on twice, only because I never blogged it last time. The challenge is say you need to make changes to data in a database, maybe across multiple tables, and using DataServices just doesn't make sense. For example, cloning x number of records. It's easy enough to create your Java remote objects and call them from Flex, but then in an FDS/LCDS implementation how do you push those changes out to Flex clients?

There's some documentation on this, scattered vaguely across the web, and there's a good chance that perhaps this has already been blogged - but I just couldn't find it. The trick is that there are 2 sides to this story, one, you must perform your operations on the database directly, and then two, you must INFORM FDS that changes have occurred. So say I want to create a new Author record, this is what that might look like:


public void createAuthor(){ DataServiceTransaction dtx = DataServiceTransaction.begin(false); //create record and save: Author auth = new Author(); auth.setFirstName("Ernest"); auth.setLastName("Hemingway"); AuthorDAO dao = new AuthorDAO(); dao.create(auth); //let LCDS know: dtx.createItem("author", auth); dtx.commit(); }So I just do my regular db insert, then I use a DataServiceTransaction to let FDS know that I've created an Item. Alternatively, I could use this approach:
public void createFDSItem(){ DataServiceTransaction dtx = DataServiceTransaction.begin(false); Author auth = new Author(); auth.setFirstName("victor"); auth.setLastName("javarubba"); AuthorDAO dao = new AuthorDAO(); dao.create(auth); dtx.refreshFill("author", null); dtx.commit(); }This approach might be a bit of overkill and might be better suited when doing mass updates across many records. I did a little bit of testing and it seemed that for the most part calling CreateItem() was faster that the refreshFill() in pushing the new record to the Flex Client.

What cost me so much grief is that I was falsely led down the garden path to believe that calling dtx.createItem("author", auth) would not only inform FDS but also actually create the item. This is not the case. There! Officially blogged!

Related Flex Tutorials