Category Archives: Uncategorized

Just a quick one : After much pain of trying to upgrade to Spring 3.0.0-RC1, it turns out that the security is not compatibale with Spring BlazeDS 1.0.x. It results in the following error:

java.lang.ClassNotFoundException: org.springframework.security.Authentication

So, head over to Spring and go vote on this issue:

http://jira.springframework.org/browse/FLEX-65

I hope this gets resolved before 3.0.0-GA

Sometimes in Flex, you’ll need to perform asynchronous form validation. where rather than simply checking that a string matches certina criteria, you’ll need to take a trip to the server — Eg., checking to see if a username is already used during signup.

In scenario’s like this, the out-of-the-box validation framework just doesn’t cut it. I’ve tried shoe-horning the standard Validator class to block validation, and it’s just not pretty.

However, I remain a fan of declarative form validation. It’s possible to write screeds of validation code in Presentation Model / Mediator classes, but I still prefer a simple bit of markup that describes the validation being applied.

To address this, I’ve put together a very small validation framework that handles asyncronous validation, amongst others. Instead of decalring Validators in your view, instead decalre a ValidationCollection with a bunch of ValidationRules. Here’s an example:


<mx:Button label="Register" enabled="{ validationRules.isValid }" />
<validation:ValidationRuleCollection id="validationRules">
            <validation:UsernameIsUniqueValidationRule username="{ txtUsername.text }" targetComponent="{ txtUsername }" />
            <validation:EmailIsUniqueValidationRule email="{ txtEmailAddress.text }" targetComponent="{ txtEmailAddress }" />
            <validation:PasswordsMustMatchValidationRule password1="{ txtPassword.text }" password2="{ txtPasswordConfirm.text }" targetComponent="{ txtPasswordConfirm }" />
            <mx:StringValidator required="true" source="{ txtUsername }" property="text" requiredFieldError="{ ResourceManager.getInstance().getString( ResourceBundles.ERROR_MESSAGES , 'REQUIRED_FIELD_ERROR' )}" />
    </validation:ValidationRuleCollection>

The ValidationCollection serves to aggregate the results of all it’s enclosing validation rules, and give a single point useful for databinding. In the above example, the Register button is not enabled unless all the validation rules have passed.

Declared inside are a series of discreet validation rules. The interface here is a lot less prescriptive than using the Validator base class, and it’s possible to write rules as simple or as complex as required.

Eg., in the above example there’s asyncronous checks to see if username & email are both available. In another case, there’s a rule which compares the text values of two passwords to make sure they match.

Also note that you can mix and match validation rules and Validator subclasses (such as the StringValidator above). This prevents you from having to re-invent the wheel by utilising all the validators that come out-of-the-box with Flex.

Under the covers, Validator instances are decorated to instances of IValidationRule to get things working.

Source code is available here, along with some sample validation rules… should you find it useful.

For the past two nights while working on my side project, I’ve been banging my head against the wall trying to pass Enums back and forth across BlazeDS to my Flex Client.

I know it’s possible, after all, I’ve seen it on the internet….

However, depsite what ol’ man google said, I was getting errors when sending the enums back from Flex to my server (though they went fine the other way).

In addition to the standard Flex / BlazeDS stack, I’ve been using two very handy open source tools :

  • dpHibernate to assist with serialization of Hibernate Lazy proxies
  • DTO2FX for some really funky AS class generation

Turns out that very small bugs inside each of these were to blame.  I post here in case — through some odd twist of fate —  you, dear reader, have the same stack:

dpHibernate

dpHibernate was attempting to deserialize Enum classes as a hibernate proxy.  Adding a test for Enum inside the isSimple method of the HibernateSerializer took care of that:


    private boolean isSimple(Object obj)
    {
        return ((obj == null)
                || (obj instanceof String)
                || (obj instanceof Character)
                || (obj instanceof Boolean)
                || (obj instanceof Number)
                || (obj instanceof Date)
                || (obj instanceof Calendar)
                || (obj instanceof Document))
                || (obj instanceof Enum);
    }

DTO2FX

DTO2FX uses an (IMHO) overly complicated template for their generated Enums.  Rather than just use the method discussed here, which allows for a simple enum client side class, they use a much more complex template.  It requires the use of a custom Serializer / Deserializer within Blaze.

Here, I thought of a few approaches:

Change the template used by DTO2FX and recompile my custom version

This requires downloading no less than 5 seperate open source projects from CVS (who the hell uses CVS anymore?) and working out what was going on.  I have previously given up on changing DTO2FX as a simple task, so didn’t even bother this time.

Don’t use DTO2FX to generate the Enums — do it by hand

I’m not using a large number of Enums in my project, and I can live with hand coding them.  However, one of the wonderful features of DTO2FX, is that it uses compile time checking of your Java project to ensure that every dependent type has been generated.  If you miss a type out (even intentionally), you get an error at compile time.  Sadly, there’s no way to turn this behaviour off — which meant I had to consider:

Stop using DTO2FX completely

I seriosuly considered this.  I love DTO2FX because it’s quick to use, maintains my classes in the background, and uses the Generation Gap pattern, meaning that in my generated classes I can still put custom code.  However, this is not the first time that I’ve ground to a halt because of some quirk in the way that DTO2FX generates it’s code.

Also, I find that having to make an architectural decision on my project because a tool won’t generate code in a specific way is unacceptable.  If it wasn’t so good in other ways, I’d have ditched it.

I googled for an appropriate replacement for DTO2FX, but couldn’t find one.  Which left me with….

Make DTO2FX’s Enums work.

Although the fix is simple, the debugging and locating the fault was the hard part.

In the end, all it took was adding this override to EnumPropertyProxy :

    public Object createInstance(String className)
    {
        Class cl = AbstractProxy.getClassFromClassName(className);

        if (cl.isEnum())
        {
            return new EnumHolder(cl);
        }
        else
            throw new IllegalArgumentException("**** samples.EnumProxy registered for a class which is not an enum: " + cl.getName());
    }

And from there, (after I reverted all my other hackery) it worked.

Cheers

Marty

Just a quick post on a flex builder 3 bug I just found.

Defining a constant on an interface causes Flex Builder to give you the ever helpful message at compile time :

“An internal build error has occurred.  Right click for more information”

Of course, there is no more information, you have to find what you did to break it through old fashioned sleuth work.

Anyway, constants on interfaces :  A stupid mistake, yes… but it’d be to have the compiler issue a stern telling off rather than flex builder throw it’s hands in the air and give up on me completely.

Really, Flex Builder – after all you and I have been through!?

Faithfully yours,

Abandoned.

I’m now finally allowed to post information about a project I worked on : Morgan Stanley’s  ”Matrix

It’s by far the biggest flex application I’ve ever worked on, and probably one of the most significant uses of the Flex platform to date.

The client, Morgan Stanley is one of the biggest investment banks in the world, and their product - Matrix is a trading platform that allows rich, real time collaboration through chat, video, sharing of trade ideas, charts.  

The development team was full of some of the top developers I’ve ever worked with, working on the project was a priveledge and a non-stop learning experience!

Check out the site, and take the tour!

I’ve recently been getting my feet wet in Java, and starting integrating with dpHibernate to facilitate lazy loading across to Flex.

Here’s what my stack looks like:

  • Spring 2.5.6
  • Hibernate 3.3 (including annotations, and transaction management)

Trying to get dpHibernate wired in, I was getting lots of errors along the lines of the following:

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

 

The problem here is that using transaction management, things get a lot tighter on how and when you can get access to a hibernate session.  dpHibernate tries to get it’s session by essentially calling sessionManager.getCurrentSession();

However, as far as Spring’s transaction manager (which is wired into the SessionManager) is concerned, the thread which is executing has no session, and has no business trying to create one — specifically, outside of a transaction.

After spending several hours trying to work out how to sidestep Springs transaction management, I realized the trick was simply to wire dpHibernate closer to spring.  This is tricky, because dpHibernate is using an extension of the flex’s JavaAdapter, and exists completely outside of the Spring infrastructure.

HibernateSerializer makes a call to a dpHibernate object called SessionManager, which returns the current session outside of a valid Spring transaction.

So, I ditched the SessionManager completely, and replaced it with a good old fashionsed SessionFactory object, as follows:

    @Resource
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

The @Resource tag there tells Spring to give me a wired up sessionFactory instance.

I also decorated the HibernateSerializer with a @Transactional tag, so that Spring knows the context in which this will operate:

@Transactional(readOnly=true)
public class HibernateSerializer implements ISerializer
{

Now, if I add the HibernateSerializer as a bean, Spring knows to give it access to a sessionManager, and to do so in the context of an active transaction.

Add the bean declaration as follows:

<bean id="hibernateSerializerBean" class="net.digitalprimates.persistence.translators.hibernate.HibernateSerializer" />

Nearly there. Finally, I just need to tell dpHibernate to go and fetch this wired up Serializer from Spring, rather than instantiate it’s own. Inside SerializationFactory, I modified the getSerializer() call to read as follows:

    public static ISerializer getSerializer(String type)
    {
        if( HIBERNATESERIALIZER.equals(type) )
        {
            ServletContext ctx = FlexContext.getServletContext();
            WebApplicationContext springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(ctx);
            ISerializer serializer = (ISerializer) springContext.getBean("hibernateSerializerBean");
            if (serializer == null)
            {
                throw new RuntimeException("bean named hibernateSerializerBean not found");
            }
            return serializer;
        }

        throw new RuntimeException("unsupport serialization type: " +type);
    }

Note that I’ve hard coded the name of the bean here for simplicity sakes. Chances are you’ll want to paramaterize that.

That’s it! Now, calls that pass through dpHibernate happen with a Spring managed transactional session. Great!

 

Edit: Espen came up with a simpler alternative over on his blog — check it out : http://espenskogen.wordpress.com/2009/06/04/more-dphibernate/

Here’s a trick which you may already know about (after all, it’s in the docs) but I only discovered it today when I needed it.

Conditional compilation allows you to vary the classes and functions included in a compilation based on a config value.

Eg., You may have a slightly different codebase used for your debug build than for your release build.

For example, on my current project we have a couple of convenient hacks in use in our test environment to prevent us from needing to log in every time we launch a debug session.

However, somewhat predictably, one of these hacks recently made it through to our testing team, and broke all sorts of stuff.

So, I figured I’d find a way to automatically remove it as part of our build process.

The class got modified to look a little something like this:

public class PrepCommand extends SimpleCommand
{
      public override function execute(notification:INotification):void
      {
            doDebugLogon();
      }

      CONFIG::debugging
      private function doDebugLogon():void
      {
            trace("This is where the logon should happen");
      }

      CONFIG::release
      private function doDebugLogon():void {}
}

Note that the doDebugLogon() method is defined twice within the method, varied by the CONFIG attribute.

This attribute defines under which compilation configuration to include the method. You can do the same thing for a full class.

Next, I modified the compiler-config.xml file used for our project to include this snippet:

<flex-config>
    <compiler>
        <define>
            <name>CONFIG::debugging</name>
            <value>true</value>
        </define>
        <define>
            <name>CONFIG::release</name>
            <value>false</value>
        </define>
    </compiler>
</flex-config>

Then, simply swapping the values of debugging & release would modifiy which of the function calls are included in the compiled source.

Not bad, but still not very automatic.

Because we’re a .NET shop here, our build tool of choice is nAnt. Most of our config files for the flex build are generated from template files, using nAnt variables to give us nice flexible builds. (pardon the pun).

So, I introduced a new target into our build file for performing a release compile:

    <target name="release" description="Performs a release, setting appropriate config values.">
        <property name="debug" value="false" />
        <call target="build" />
    </target>

…and added a couple of new variables to the properties file:

    <property name="useDebugConfig" value="true" />

    <!-- Derived from useDebugConfig.  Set the value of useDebugConfig rather than setting useReleaseConfig.
        Note that only one of these values must be true, or compilation will fail -->
    <property name="useReleaseConfig" value="${string::to-lower(not(useDebugConfig))}" />

Then, I tweaked the compiler-config described above to look like this:

<flex-config>
    <compiler>
        <define>
            <name>CONFIG::debugging</name>
            <value>${useDebugConfig}</value>
        </define>
        <define>
            <name>CONFIG::release</name>
            <value>${useReleaseConfig}</value>
        </define>
    </compiler>
</flex-config>

Now, ensuring the correct code is included is as simple as:

nant // Calls 'build', our default target using the debugging compilation options
nant release // Uses release compilation options

That’s it.

It’s worth reading up on conditional compilation in the docs, as there’s a bunch of great examples in there.

Questions / comments welcome.

Marty

Although there’s a bunch of cool plugins out there for formatting code, for those of us too cheap to host our own wordpress blog, options are limited.

Luckily, there’s a handy javascript app over on blogger which gives us some clean markup to paste in.

Checkit:

http://formatmysourcecode.blogspot.com/