Check out our new training course on AngularJS for Flex Developers

Using Flex and HTML together

I wrote an article for this month's newsletter that harken back to our past as Flex developers.

I was recently contacted by a developer who wanted to use the Flex iFrame component to open up a Google Maps link. This was an experienced developer, but one that is new to Flex. He didn't know where to start. I gave him some input, and thought I'd do a write up about it.

What is Flex iFrame?

The Flex iFrame component is a component that uses an iFrame to open up an HTML page over a SWF. This makes it appear as if the HTML portion of the app was part of the Flex app. It is a kludgy way to get HTML and Flex talking to each other, but is functional for certain use cases.

Get the Component Code

The first step is to get the code, which you can do from this GitHub repository. Drill down into the repository to get at the component's code . The code is in two classes, the IFrame class and the IFrameExternalCalls class.

To use this code, you have two options. The easiest is to copy the two classes into your project. The second is to create your own library project and a SWC of the component. The latter is preferred for reusability purposes, but for the sake of this sample we'll use the first option and keep it simple.

Unfortunately, Flash Builder had trouble with the class names, IFrame and IFrameExternalCalls. I believe this is because the 'I' at the front of a class name is convention that denotes the class as an interface, not a real class. As such I had to rename the two classes for them to be usable. I chose FlexIFrame and FlexIFrameExternalCalls. The two classes have references to each other, and each one will have to be modified to reference their newly named counterpart. If the Flash Builder refactor function doesn't perform the code changes for you, a quick search and replace will.

Get your Google Maps URL

Before opening up a URL in the app you have to determine what URL you want to open. Since my new developer friend wanted to open something in Google Maps, the first thing is to get a Google Maps API Key. This is a simple form for you to fill out.

Next you need to create a URL. There are a bunch of different options for creating Google Maps URLs. I am going to bring up a map that points to the Water Park I'd like to be at today. This is the URL:

https://www.google.com/maps/embed/v1/place?key=yourKeyHere=Lake+Compounce+Bristol+CT

With the URL in hand, we can go into the code.

Using the Flex IFrame

This is the code that will open up load a Flex app with an iFrame. It is a simple MXML application, and only uses the Flex iFrame component :


<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:flexiframe="com.google.code.flexiframe.*"
width="100%" height="100%" >

<fx:Script>
<![CDATA[
[Bindable]
public var iFrameURL :String = "https://www.google.com/maps/embed/v1/place?key=YourKey&q=Lake+Compounce+Bristol+CT";
]]>

</fx:Script>
<flexiframe:FlexIFrame id="iFrameBySource"
width="100%" height="100%"
source="{this.iFrameURL}"
/>

</s:Application>

The source of the IFrame component refers to the Google Maps URL.

See this app run here, or view the full source

Mixing Flex and HTML

The previous example just used an iFrame component. However, the iFrame can exist and be placed around other Flex elements; making the iFrame HTML content look as if it were part of the Flex application. This sample will show you how to hide or display the Flex iFrame with the click of a button:

This is the code:


<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:flexiframe="com.google.code.flexiframe.*"
width="100%" height="100%">

<fx:Script>
<![CDATA[
[Bindable]
public var iFrameURL :String = "https://www.google.com/maps/embed/v1/place?key=yourkey&q=Lake+Compounce+Bristol+CT";
protected function button1_clickHandler(event:MouseEvent):void
{
iFrameBySource.visible = !iFrameBySource.visible;
}
]]>

</fx:Script>
<mx:VBox width="100%" height="100%">
<s:Button click="button1_clickHandler(event)" label="Toggle Google Map" />
<flexiframe:FlexIFrame id="iFrameBySource"
width="100%"
height="100%"
source="{this.iFrameURL}" visible="false"
/>

</mx:VBox>
</s:Application>

The map is put in a VBox, which includes a button above the iFrame. The iFrame component's visibility is set to false by default. On the click of the button, the iFrame's visibility is toggled, either displaying or hiding the component.

This is the default load of the app, with the map hidden:

This is the app with the map displayed, after clicking the button:

See this app run here, or view the full source

Final Thoughts

Sometimes this Flex stuff feels like a walk down memory lane, but half of my consulting work is still in the ActionScript and Flex realm. I feel lucky to be able to balance my time between my old world and the new world.

What have you been up to?

Sign up for DotComIt's Monthly Technical Newsletter

Why won't my AdvancedDataGrid sort correctly?

I was having some problems with sorting the Flex AdvancedDataGrid, and went into details of them in DotComIt's newsletter. I thought I'd share them here.

The Problem

I was creating a AdvancedDataGrid in a client project. The dataProvider for the grid had nested objects whose properties were being displayed in the column with an itemRenderer. I was also using a custom itemRenderer that would introspect the objects based on the dataField of the object. The combination of these things made two different columns always perform the same sort, even though my code told them to use a different sortCompareFunction.

This will make more sense with a sample. Let's start with the dataProvider:


[Bindable]
public var collection :ArrayCollection = new ArrayCollection([
{dummyValue:'',user:{firstName:'Arvid', lastName:'Zimmer'}},
{dummyValue:'',user:{firstName:'Jeffry', lastName:'Houser'}},
{dummyValue:'',user:{firstName:'Tom', lastName:'Amilton'}},
{dummyValue:'',user:{firstName:'Kyle', lastName:'Wellington'}},
{dummyValue:'',user:{firstName:'Zipper', lastName:'Stretch'}},
]);

Each property in the ArrayCollection has two values: a dummyValue which is a placeholder and a user value which is an object. I want the DataGrid to display the firstName and lastName in columns. This will do it:


<mx:AdvancedDataGrid dataProvider="{this.collection}"
sortExpertMode="true">

<mx:columns>
<mx:AdvancedDataGridColumn visible="false" />
<mx:AdvancedDataGridColumn headerText="first Name" sortable="true" dataField="user" sortCompareFunction="sortFirstName">
<mx:itemRenderer>
<fx:Component>
<s:MXAdvancedDataGridItemRenderer dataChange="itemrenderer1_dataChangeHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function itemrenderer1_dataChangeHandler(event:FlexEvent):void
{
if(!data){
return;
}
labelDisplay.text = data[this.advancedDataGridListData.dataField].firstName;
}
]]>

</fx:Script>
<s:Label id="labelDisplay" />
</s:MXAdvancedDataGridItemRenderer>
</fx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="last Name" sortable="true" dataField="user" sortCompareFunction="sortLastName">
<mx:itemRenderer>
<fx:Component>
<s:MXAdvancedDataGridItemRenderer dataChange="itemrenderer1_dataChangeHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function itemrenderer1_dataChangeHandler(event:FlexEvent):void
{
if(!data){
return;
}
labelDisplay.text = data[this.advancedDataGridListData.dataField].lastName;
}
]]>

</fx:Script>
<s:Label id="labelDisplay" />
</s:MXAdvancedDataGridItemRenderer>
</fx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
</mx:columns>
</mx:AdvancedDataGrid>

I simplified things from my client app, however the key to remember is that I was setting the dataField property so that the itemRenderer could access it. The problem with this is that clicking the column to sort would treat the columns as if they were identical. You can try a full sample. The top grid in the sample exhibits the problem.

Once one column was clicked, the other would always call the first column's sortCompareFunction; thus sorting based on the wrong criteria. For example. Load the app, click the first name column:

You'll see that the first name column is sorted. However, you can also see the sort arrow show up on the second column. Now click the last name column:

After clicking the last name column, the first name column is sorted in reverse order, but there is no sorting on the last name column. Reload the app, and try to sort the second column first. It sorts correctly. Then click the first column, and you'll see that only the second column is affected. Using the Flex Debugger I determined that once one column was clicked that column's sortCompareFunction was called for all columns that had the same dataField specified. That was not expected behavior.

My Solution

After some experimentation, I determined that the problem was that the dataField on both columns was identical. My solution was to add the dummy property into the dataProvider's objects and change one of the column's dataFields to point to the dummValue:


<mx:AdvancedDataGridColumn headerText="last Name" sortable="true" dataField="dummyValue" sortCompareFunction="sortLastName">

The side effect of this change is that I could no longer use the 'generic' itemRenderer. Instead of using the listData object in the renderer, I had to hard code the value. Like this:


labelDisplay.text = data.user.lastName;

I determined using a non-generic itemRenderer was better than having the columns not sort properly. I'm sure my client would agree. Click the first column in the grid and see this:

The first name column is sorted properly, and the last name column is untouched. Now click the last name column:

You see that the last name column is sorted properly and the first name column is untouched. This is how it is supposed to work.

Play with the full app here and check out the source code. The top grid shows the problem and the bottom grid shows the solution.

Sign up for DotComIt's Monthly Technical Newsletter

Check out the Flextras AutoComplete KickStarter

Earlier this week, I launched a Kickstarter project for Flextras. The intent is to flesh out the API of the Flextras Spark AutoComplete component, and then donate it to Apache Flex.

This is an experimental approach to fund some of the the development I want to do around Apache Flex. At the time of this writing, the project has reached over 10% of it's goal. There are a bunch of cool rewards including T-shirts, Flex Show content, and personal mentoring time with me. If you're interested in Flex, and how it is going to thrive under Apache, check out, and fund the Flextras AutoComplete Kickstarter.

In Defense of Flash - Revisited

I wrote this post for a Flextras newsletter. Before I get into details; I want to remind everyone that they should check out 360|Min coming this October. It is an unconference style event in Las Vegas by the folks who put on 360|Flex. It should be lots of fun and educational on stuff happening now.

Back in November, I wrote a newsletter entitled In Defense of Flash. There was a lot of client confusion about the future of the Flash Platform; and they were worried that all their apps would suddenly stop working; or that their investment in the platform would turn out to be a significant waste of time and money. My original post spoke about a lot of specific issues; but at the time some things were unknown. I thought it was time to revisit that post and see where things stand, 10 months later.

Flash Player on Android

The ball that started the “Flash is Dead” bandwagon rolling was that Adobe announced it would cease development on Flash Player for Android devices. This made sense to a lot of people. Although, it was nice to have a Flash Player in mobile browsers; no one was building browser based Flash Applications with mobile devices as the target. The fact that the iOS browser did not support Flash in any way decreases the ubiquity that the platform used to offer on desktop devices.

With the release of Android 4.1, Jelly Bean, Adobe has removed the Flash Player from the Android store.
There will be no certified implementations of Flash Player for Android 4.1

Beginning August 15th we will use the configuration settings in the Google Play Store to limit continued access to Flash Player updates to only those devices that have Flash Player already installed.
Source

Although, this is sad to see; it is not a surprise. It is interesting to note that a few days after the app was pulled, the BBC pressured Adobe to return the app to the Android UK store; as they do not have another technology solution in place for browser based streaming on mobile devices, yet:
Adobe's mobile Flash Player has returned to the Google Play store in the UK. According to BBC News, Flash's encore is the result of pressure from the BBC and "strategic partners" that rely on Flash for their Android apps
Source

It’s weird that an app with over 500,000 ratings, and a 4.5 star average could be considered a failure. Most of us independent developers can only dream of having that many people try out something we built. 

Despite the news about Flash Player, I still believe that Adobe AIR, especially with captive runtime, is still a fantastic choice for building cross platform native mobile applications.

Long Live Apache Flex


In the original post, I spoke about Flex and how Adobe planned to donate Flex to the Apache foundation. At the time, details were very sketchy. We have plenty more information now. Adobe has successfully donated Flex to the Apache Foundation. They have contributed the Adobe Flex 4.6 code base, a testing framework named Mustella, and the Text Layout Framework used in many Spark controls.

In a few weeks, Adobe is expected to donate a new ActionScript compiler, named Falcon. The Falcon compiler will be included in Flash Builder 4.7; which was recently released on Adobe Labs. But we’ll have the code, and hope to get it integrated with Flex in the future.

In addition to the Adobe donations, there is a lot of new code and bug fixes done by the community. The Apache Flex team has released Apache Flex 4.8. I wrote about building Apache Flex 4.8 from the source last month.

Since an Apache release must be source only; they have also put together an installer Application which will allow you to easily prep Apache Flex for use in Flash builder. Flex has a lot of dependencies, such as the AIR SDK and BlazeDS, which Apache cannot distribute due to licensing terms. This installer takes care of that downloading and setup for you.

Flash Player on Windows 8


Another pressing issue is the Flash Platform support on Windows 8. As I stated in my original post, the “Windows 8 UI”—previously Metro—browser will not support plugins. This affects all plugins including Silverlight and Flash. However, Microsoft and Adobe have worked together in order to support Flash in the metro style browsing. Flash Player will be included as part of the browser.

I’m going to quote the Flash Platform runtime whitepaper, as the source here:
Flash Player release and debug players will be available and supported for Windows 8 Desktop and Metro style experiences on both x86/64 and ARM platforms.
This was a happy surprise to many in the developer community, including myself. Flash Player will be supported on all variants of Windows 8. We’re still waiting for the formal notice that Adobe AIR will be supported on Windows 8; but for the moment we have to believe the Flash Platform Whitepaper:
Adobe is committed to adding both Windows 8 Desktop and Metro as supported platforms for Adobe AIR.
I’m looking forward to converting Igor Knots, my mobile game, to a Windows 8 experience with Adobe AIR.

Final Thoughts


Two years ago, when a client approached me about building an application with Flex and Flash, I think we made the right decision.  Ten months ago, when we decided not to abandon our project, or rebuild it in a different technology, I think we made the right decision.  Today, if I were to start a new project, there are very specific questions I’d ask about the user base. 

Does your app have to run in a mobile browser?  If so; then don’t use Flash!  However, if your target is multiple desktop browsers spread across multiple operating systems in your Enterprise; then Flash can suit your needs.  

Do you want to run on multiple platforms?  If so, then AIR allows you to deploy your app to Mac and Windows desktops; and as Native Android or iOS Application.  AIR can help your app run on a multitude of devices and desktops.  It may be a good choice.

Thoughts On Flex, Business Models, and Apache

Over the past few years a few friends have told me that I always have a plan. I didn't think about it much until it was mentioned to me, but I guess that is true. I'm always trying to think two steps ahead and plan my next move and carve out a path in life. Sometimes this is a lot harder than it is.

Gareth sent me a question through the Flextras site about the future of Flex, the availability of mobile components; and the viability of AIR.

Hi Jeff, I know things are a little bleak right now with Flex (hopefully with 4.8 SDK release things will perk up with the community), but I was wondering if you'd thought about still doing the mobile component creation. I'm still making AIR apps for mobile and have found the landscape pretty scarce when looking for various components [snip].

[snip] ...the flex mobile component still seems to be a viable model. I'll keep using Adobe AIR to make my cross platform apps until Adobe decides to get rid of that too :) I do the app thing as a supplement to my day job, so being able to purchase low cost components that will help make my apps more "snazzy" is something I'd look into (even at $5-10 a pop would be better than having to write it myself).

I've even considered the whole business model myself, but have not had the infrastructure set up to do it. Anyway, hope things are still going well with the Flex Components side of things. Just wanted to suggest something as I see your Flextras Friday Lunch, but haven't seen you on the "build" side of things recently.

I responded to this email after a very long day and about 4 hours past my bedtime. I think I was a bit blunt. I thought I'd turn my response into this blog post, perhaps with a bit more polish than the "late at night" ramble I sent to Gareth.

Things are a Little Bleak with Flex

I think I agree that things look a bit bleak for browser based Flash applications, and that has affected Flex. I also hope that Apache Flex can help turn things around; and I believe there are many ways to do this including improving performance on mobile applications (with AIR) and targetting other runtimes (such as HTML5).

There are also a lot of "little picture" things, such as bug fixes, that can help make Flex more pleasant to deal with.

I have faith in Apache and I have faith in the community. I just hope we can prove ourselves while Flex and Flash Player are still relevant.

Flex Mobile Components seem to be a Viable Model

I have been doing some Mobile Component development, but not much. There are some things in my Apache Flex Whiteboard. I have not wrapped up any of those components into the Flextras component set, though.

I wasn't sure what Gareth meant by Model in his original email to me. If he is referring to a "Development" model. Then, I agree. AIR offers a compelling offering. Right now it feels like there are lots of cross-platform development approaches for native mobile apps. AIR offers a good solution. I suspect over time, the market will condense and I hope that AIR is one of the success stories. I don't know if AIR will be the winner, but it has the potential to do so.

If Gareth was referring to a "business" model in flex Components, then I'm not sure a successful one ever existed. Or rather, I haven't found it yet. Selling Flex Components was never a viable model for Flextras. It grew to a nice side business, making roughly $10K a year, but that was not enough for me to do it full time. Even though I did do it full time for 2 years or so, though.

I had planned for a 70% drop in income to launch Flextras, then have it grow from there. But I actually had a 90% drop in income. At some point I stopped telling consulting clients to shove it.

Flextras was growing each year, although slowly, but Adobe pulled the rug out from under that. Generally we did 20% of the sales in December, yet after last November things just nose dived to nothing. That cut into revenues, of course. This year sales will be in the $2K range at best, most likely lower. There are a ton of different reasons for this; and not all of them are Adobe's fault. I could probably write a book on the many ways to fail in business.

What is the Future of Software?

The Internet will change software just like it will change music and movies. Boxed software is going to go away, just like CDs and DVDs.

The cost of duplication and distribution have fallen close to nothing. Creation of said software is, basically, a sunk cost that no customer cares about. Marketing is still needed, though. People have to notice you. But, as the cost of software drives towards zero; how does a software development company make income?

I believe the future of Flextras is in formal support services. I've been working on this for a while. I hope to have it ready in time for 360|Flex in Denver. In 2011. I could write another book on why this is so late. The vendor I hired to rework our shopping cart took 6 months past the deadline to deliver code that worked.

Delivering code to spec is a completely different issue; and that never happened. I've lost count of the number of times I've missed the goal of "Flextras selling Support Services."

What Have I Been Up To?

I should be spending my summer seeing if I can make the new shopping code do what I want it to do; or if I should throw it out and start from scratch. But for reasons of personal sanity; I put that aside. I need to crawl back into my cave and refresh.

I've been trying to spend my summer riding waterslides at the local amusement park, going to as many Soul Asylum concerts as I can, and catching up on some video games I hadn't played yet. Check out the new Soul Asylum album; it's great.

What is the Plan?

Ideally, I'll come back to the shopping cart in 3rd quarter of this year, ready to tackle said problems with a fresh mind. Then I'll have 1-2 (or 6 or 12) months to finish the infrastructure problems that would allow Flextras to sell support services around Flextras and [in theory] Apache Flex.

Once that infrastructure is in place; I'll turn my head back to promoting said stuff and building new components. I have even consider launching a Kickstarter [or two or three] to 'fund' my Flex development time.

I'd love to create a Spark Alert class that works well on Mobile. I think I can do better than what is already out there. I'd love to create a ViewStack that easily supports Spark Components, MX Components, and even non Flex Display Objects because why does a ViewStack need Flex dependencies? I'd love to create a Spark port of the Flextras Calendar. That can be mobile optimized easily.

But a lot has to happen for any of this to come to fruition.

Make sure you're signed up for the Flextras Monthly Newsletter if you want to know when stuff like this moves forward. It's the best way to keep up on any Adobe Flex or Flextras related news I have to share.

Random Thoughts from the 360|Flex Experience

After every conference, I like to put down my thoughts about it and get a blog post out. A few weeks ago I had the pleasure of being a sponsor, presenter, and attendee at 360|Flex in Denver. The conference was great, as always, and I walked away with very positive vibes for the future of Flex. Although no one is too happy with Adobe, they are positive about Flex and the Apache foundation.

Being a Sponsor

Flextras was a sponsor of the conference this year, promoting our line of UI Components. The components are now free for production use. It is one step in our switch to advanced support. People seemed very positive about the move.

We put together My speaker ratings were kind of middle of the road, but at least most people found the session informative. Ever since the rating app moved to mobile devices; the amount of comments available have gone down tremendously, which is a bit of a bummer. I'd love feedback if you happened to have seen my presentation. I'll be giving the same presentation at D2WC next week.

The conference had a weird vibe during the Speaker Sponsor dinner. It felt a bit like a last hurrah. In some respects it was. Times are changing. Thanks to the advent of mobile devices the "it runs the same everywhere" stance is no longer guaranteed. I believe the use of Flash (or AIR) is going to be more focused; and discrete.

360|Flex MCP

For a while 360Conferences have added a "MVP" designation to certain people who have helped the conference in some manner. I got blessed this year to be one of those. John actually called me a "Business Mentor" up on stage when I was awarded my hoodie.

I was amused by this, because I don't feel like a business success. I don't feel like a failure either, but I'm chugging along having fun. DotComIt hasn't grown to where I want it to be; but I haven't had to give it up either.

John and I often bounce ideas off each other. I see it more of a peer relationship than a mentoring relationship. I don't have any magic secret business sauce.

I also got to see a lot of other friends; and that is part of the reason I love 360|Flex. Tom Ortega, asked me what my plan was. He mentioned that I always have a plan. I have no idea when I learned to start thinking two steps ahead, but he's right. I do have a plan. :-)

Welcome to 360|Stack

360|Flex started as a "cool idea" to get a bunch of Flex Developers together and has blossomed into a conference company that extends beyond just Flex. They put on a Mac development conference and a iPhone developer conference. Some of the "beyond Flex" started to trickle into 360|Flex. There have been a bunch of non-Flex related sponsors and sessions this year such as Appcelerator and Sencha.

As John said, the community around 360|Flex is about the work we're focused on doing; not a specific technology. As such the conference is being rebranded as 360|Stack. Next year will represent the full dev stack; whether that is HTML5 or Flex Development or something different.

I can't wait to see how the next year unfolds.

Is Flex Dead?

This question comes in from a reader; and to be honest I've been at a loss as to how to respond without writing a book. I finally found time to devote some time to putting down some thoughts.

I'll start by quoting the full question and then trying to answer points one by one:

As I was viewing your blog I noticed you seem very knowledgeable about Flex. I've just become aware of Flex and bought a few books then realized that Flex is dependent on Adobe Flash which has recently been dropped from Linux support which affects Android and the growing mobile market. I was wondering what your insight, I know you don't have a crystal ball, is on Flex usage and could you tell me if you think it has a future. Also, what is Flex really good at? I've not been able to find any example Flex apps out there... only Adobe Air apps. Thanks!

I'm going to answer the question in reverse order. First,

...what is Flex good at?

Flex is a Software Development Kit used for building Enterprise Applications. It provides a component set and a framework for rapid development. By making use of the Flash Player runtime; it is easy to build a consistent experience across multiple desktop browsers.

I've not been able to find any example Flex apps out there... only Adobe Air apps.

An AIR App can be a Flex app. Most Flex apps that I'm aware of are internal apps used for browser based applications in an "big business". You probably won't find too many public applications.

Now, Let's tackle this sentence; which is full of misconceptions:

I've just become aware of Flex and bought a few books then realized that Flex is dependent on Adobe Flash...

This isn't necessarily true. Flex is dependent upon Adobe Runtimes; however the browser based Flash Player is just one of them. Adobe AIR is a second runtime which you can use to build Flex applications. Adobe AIR can be used to deploy your Flex app as a desktop for Mac and Windows, or as a native mobile application on iOS, Android, or Blackberry's Playbook.

I expect that, in time, we'll be able to use Adobe AIR to create Windows Metro applications and Native Applications for the Blackberry "next" phones. More info on Adobe and its runtime commitment is in the "Roadmap for Flash Runtimes" whitepaper.

However, keep in mind that Flex is in the process of being donated to the Apache Foundation and the Apache Flex Project is in the process of creating their first release.

There is interest in decoupling Flex from the Adobe Runtimes, so that we can use the same Flex code and deploy them to other languages or platforms, such as HTML5 / JavaScript, such as Native Android, or Native iOS. I think it will be a couple of years before we start to figure out if such endeavors are going to become a reality for building Enterprise Applications. There are a lot of smart and motivated people, involved in the Apache project; and I have faith they will do great things.

...which has recently been dropped from Linux support...

Adobe has not dropped Flash Player support on Linux. However, as I understand it they will only be supporting the Flash Player on browsers which support a new plugin API that was developed in conjunction with Google. At the moment, only the Chrome browser will support the Flash Player on Linux; however if this API is implemented on other Linux browsers, it seems probable that this will also come with Flash Player support.

As I understand it, however, Adobe AIR, will not have any support on Linux moving forward. I understand a lot of developers find this troublesome because they were using Adobe AIR as part of their build and test process; which run on Linux machines. In practical terms, this has not affected any of my clients.

...which affects Android and the growing mobile market.

Adobe support for Linux is completely different than Adobe's support for Android. Adobe did cease development of the Mobile Browser Plugin for Android. But, you can still use Adobe AIR to build Native Android applications.

In terms of clients who I speak to; people are more interested in building Native Applications on devices and care less about browser based applications--which is where Flex excels. I do not know of anyone building Flash content targeted towards mobile browsers.

And finally....

tell me if you think it has a future

It's hard to say. At the moment, a lot of people I talk to are taking a wait and see attitude. They aren't ceasing Flex development or retiring their current applications. However some are halting on starting new projects with a technology that is "deemed" To be abandoned. People want to see the Apache Flex team create a formal release. They want to see the Apache Flex team prove they can move the SDK forward in a relevant manner. Once we prove that; I think things will improve in terms of corporate mindshare for Flex.

If I were to "guess" what is going to happen, I'd say that browser plugins are going to go away completely in the future. Apple started this with the iPhone; and Microsoft is going to accelerate it with Windows Metro apps. However, I believe that Adobe AIR is going to thrive; as it solves a unique problem (Cross platform deployment on mobile) which the browser based Flash Player used to solve. I anticipate that AIR may become more focused / niche than the Flash Player was; but I anticipate it will be a profitable niche.

There is potential for great things; and I believe that the potential can be realized.


Update 6/20/2013
This page has been translated into Spanish language by Maria Ramos from Webhostinghub.com.

Flash Remoting won't connect "NetConnection.Call.Failed"

I've been doing some with for the Flextras promotions around 360|Flex. As part of the promotions I am creating a customized version of my Game; strictly for Flextras. It is going to allow people to login and will keep score on our server instead of internally to the app.

Since this is a Flash app; I'm using Flash Remoting to connect to our ColdFusion server. Everything worked fine on my local machine. Everything worked fine on my development server (AKA Staging). However, my production machine was giving errors that looked like this:

faultCode: "Client.Error.MessageSend"
faultDetail: "Channel.Connect.Failed error NetConnection.Call.Failed: HTTP: Failed: url:
faultString: "Send failed"

I've tried a lot of different things including not using http instead of https. I knew that Flash Remoting was working on the production server because I had other Flex apps working without problems. So, what was the problem?

I've been working on this on and off for about five days; so tried a lot of different things. In the end I discovered two things:

  1. Make sure your Flash Remoting URL has a '/' at the end of it. 'https://www.flextras.com/flex2gateway' was not working. It appeared to add a JSessionID on it; which was causing the server to throw a 404 error; causing the whole call to fail. However, if I changed this to 'https://www.flextras.com/flex2gateway/' that problem went away.
  2. Turn off the Flash Builder Network Monitor. The Flash Builder Network monitor was intercepting the call and causing it to fail. The calls appeared to work fine from a web browser with the Flash Builder Network Monitor enabled, but not from the mobile app.

I think--but am not completely sure--part of my issues related to using HTTPS on the server instead of HTTP. That could be the reason I had issues on the production server, but not my local or staging box.

Moving your Flex Components from MXML to ActionScript 3

I wrote two articles for InsideRIA when the site was still active. I'm purging my personal digital archives and came across them. I decided to repost them here for posterity.

This article is about educating folks on how to move from MXML to ActionScript. I wrote the article in February of 2010; but it didn't get posted until later.

You can find the original on this DevelopRIA site. I remember it being slightly controversial, but I'm not sure why. Sadly the comments do not seem to be archived. Here is the article.

I often hear it said that all the cool kids write their Flex components using ActionScript without MXML. I'm not sure that I agree. MXML is great for layout purposes. It is great for building simple components quickly. The declarative syntax makes many development tasks easier, such as setting styles and adding events listeners. But, if you look closely at the Flex Framework source code or commercial grade components, such as what I build at Flextras, you'll notice they do not use MXML. Everything is built using ActionScript. Why is that?

ActionScript gives you granular control over your code. MXML is an ActionScript generation language. The Flex Framework takes your MXML and turns it into ActionScript. That means the code you write, isn't the code that is running. If coding were cooking, using MXML would be like buying a cake mix from the store. You just add water and you're ready to bake. ActionScript is akin to starting with flour and choosing your other ingredients carefully. It takes longer, it requires more thought, but the results are often worth it.

This article will show you how to move your component development from MXML to ActionScript. Along the way we'll touch on various aspects of the Flex Component Lifecycle. Often when you are building your own applications, in controlled environment, it will make more sense to build with MXML; and that is fine. But, understanding how to build from scratch using ActionScript will give you a deeper knowledge of how Flex works and help you build all your components better.

Today's Application

Today, I want you to pretend that your boss asked you to build a survey application. As with most surveys, this application includes a bunch of questions, and needs some way to collect answers. Many of those questions can be answered with a simple yes or no. In a normal situation, you would collect yes and no answers using radio buttons.

Unfortunately, and try to stretch your imagination with me on this, your boss is a bit irrational. He hates radio buttons. You're never quite sure why, but it is what it is. Instead of a radio button, he insists that you use one of those dropdown select box thingies. Fine! We can work with that. Knowing that your survey is bound to have a lot of yes and no questions, you decide to make a component out of it.

YesNoQuestion Component Version 1

Let's just jump in and create the first rendition of our component. You can use a Text component for the question, and a ComboBox for the 'dropdown select thingy'. Throw this all in an HBox and the code would look something like this:


<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%">
    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            [Bindable]
            public var dp : ArrayCollection = new ArrayCollection([
                {label:'Yes'},
                {label:'No'}
            ]);
        ]]>

    </mx:Script>
    <mx:Text id="question" />
    
    <mx:ComboBox id="answer" dataProvider="{dp}" />
        
</mx:HBox>

We are already making our first use of ActionSCript in this otherwise MXML component. The dataProvider of the ComboBox is coded in script. It contains two objects, one for yes and one for no.

Unfortunately, this component is still lacking in functionality. When using this component, how do we specify the question text? Your developer could access "question.text", but it would be nicer if we gave them a simpler way. How do we know which answer the survey taker has chosen? We'll need to add a property to expose that value too.

Add these two variables to your ActionScript block:


[Bindable]
public var questionText : String;
            
[Bindable]
public var selectedAnswer : String;

Since the variables are public, they are easily accessible by people using our component. I call these variable properties, although I don't think that is a formal name for them. Next you'll want to tie the variables to the two components. Modify the MXML, like this:


<mx:Text id="question" text="{questionText}" />

<mx:ComboBox id="answer" dataProvider="{dp}" change="selectedAnswer = answer.selectedItem.label" />

Data Binding ties the questionText to the text display. You can use the change event to update the selectedAnswer each time you the ComboBox value changes. For all intents and purposes, this component would work for what we need it to do. It's time to test it.

To test the component, you'll need to build a simple application. I decided to build an AIR app to test, so I don't have to muck around with web server settings. From a code point of view, a web based app is almost no different; just change the WindowedApplication to an Application. This is my main application file:


<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:MXMLToAS3="com.flextras.InsideRIA.MXMLToAS3.*">
    
<mx:VBox>
    <MXMLToAS3:YesNoQuestionV1 id="q1" questionText="Do you want to take a Survey?" />
    <mx:Text text="{q1.selectedAnswer}" />        
</mx:VBox>
    
</mx:WindowedApplication>
The code imports the package that contains the component. It creates an instance of the component, q1, and specifies the question text as a string. The code contains an additional text component instance that is bound to q1's selectedAnswer property. As we change answers to the question, we can see that the selectedAnswer property changes too. Here is the running app:

Version 2: Implementation Hiding

One of the key reasons to separate your code out into a component is so that you can hide the implementation. With a hidden implementation, you can change that implementation without changing the API and all code using the component should have no issues. The current component does not hide the implementation details, as you see here:

The question and answer field are both exposed. By creating them in MXML, they are treated as public properties. What would happen to our component if someone changed the dataProvider on the ComboBox? You want to prevent this type of meddling as much as possible.

To address this we are going to turn our MXML components for Text and YesNoQuestion into protected ActionScript variables and make use of the Flex Framework's component lifecycle createChildren() to create the components and add them to the stage.

The createChildren() method is run during the component's initial setup, and is intended to be used to create children and add it to the parent container. When dealing with ActionScript States, I'll often initialize any AddChild or RemoveChild state elements in createChildren(). I do this in the Flextras Calendar component to implement day, week, and month views. To keep the selectedAnswer variable in sync with what is going on, we were responding to the change event and setting the value. Our new approach will be the same, but we'll set up the event listener and the event handler in ActionScript, not using in-line MXML.

First, create the component variables:


protected var question : Text;
protected var answer : ComboBox;

Because these variables are protected, it means that any components that extend this component can access them, but if the new component does not extend this file, it cannot. This is our createChildren() method:


override protected function createChildren():void{
    super.createChildren();
            
    this.question = new Text();
    this.question.text = questionText;
    this.addChild(this.question);
                
    this.answer = new ComboBox();
    this.answer.dataProvider = this.dp;
    this.addChild(this.answer);
    this.answer.addEventListener(ListEvent.CHANGE, onChange);
}

createChildren() is initially defined in the UIComponent class. All Flex User Interface Components extend UIComponent, and ours is no exception, even though we are down the chain a bit. To implement it in our YesNoQuestion component, we override the method signature and call the super method. When overriding methods, it is important to call the super method. You never know what code magic may be executing higher up in the chain. Then the component creates the question Text instance and answer ComboBox instance. It sets the default value and adds it to the container.

In our MXML version, you kept the selectedAnswer in sync using the change event in MXML. In ActionScript, you'll use the same approach, but need to set up the event listener with the addEventListener() method. It specifies the type of event you are listening for, change in this case, and the function to run when that event is dispatched. Instead of using the event name, 'change', I'm referring to the event constant from the event class. Either approach should work, but referencing that constant is a bit more flexible. If the event name changes, our code does not have to. This is the listener function


protected function onChange(e:ListEvent):void{
this.selectedAnswer = this.answer.selectedItem.label;
}

The listener function accepts an event argument. The single line of code inside the method is the same that we used in-line in our MXML version.

Version 3: commitProperties()

What happens if the questionText is still an empty string when the createChildren() method is called? Our question will have nothing to display. There is nothing in our current code to update the question text if the questionText property changes. There is a solution. The Flex Framework provides the commitProperties() method to run code after all the component's properties have been set. We will make use of this method to set and update the question text whenever the value changes.

First, add the commitProperties() method into your code. We can copy and paste the line to set the question text into the body:


override protected function commitProperties():void{
    super.commitProperties();
    this.question.text = questionText;
}

The method, of course, calls its' super just as we did with createChildren(). The Flex Component Lifecycle provides us with an invalidation method named invalidateProperties(). We can call this at any time on our component and it will force the commitProperties() to run during the next render event. This is a difference between createChildren() and commitProperties(). createChildren() only runs once; while commitProperties() runs during initial setup, and then again as needed. In order to trigger the commitProperties() invalidation, we're going to replace the questionText variable property with a get/set property. Flash Builder 4 contains some code generation to do this, and the resultant code will look something like this:


private var _questionText : String;
[Bindable]
public function get questionText(): String{
    return this._questionText;
}
public function set questionText(value:String):void{
    this._questionText = value;
}

The commitProperties() method will most likely execute during the life of our application more often than when we change the questionText. To let commitProperties() know what it actually needs to do, we'll add a propertyChanged flag, like this:


private var questionTextChanged : Boolean = false;

The set method will be modified to set the flag to true and to call invalidateProperties():


public function set questionText(value:String):void{
    this._questionText = value;
    this.questionTextChanged = true;
    this.invalidateProperties()
}

The commitProperties() method will need to be revisited to check for that flag:


override protected function commitProperties():void{
    super.commitProperties();
    if(this.questionTextChanged == true){
        this.question.text = questionText;
        this.questionTextChanged = false;
    }
}

By setting up the selectedAnswer method using a variable property, users of the component can change it at will; which could leave to undesirable effects. We can replace this property with a get method. Leaving out the set method will make the value read only from the outside. This is the updated set method:


private var _selectedAnswer : String
[Bindable(event='selectedAnswerChanged')]
public function get selectedAnswer (): String{
    return this._selectedAnswer;
}

Notice that I changed the Bindable metadata tag. Instead of using its default state, I added an event. The Flex Framework knows to make properties Bindable when the set method exists, but will cause a warning if no set method exists. The solution is to specify the bindable event, and dispatch it on your own when the property changes. We can add a method for the property change:


protected function setSelectedAnswer(value:String):void{
this._selectedAnswer = value;
    this.dispatchEvent(new Event('selectedAnswerChanged'));
}

The property was being set in the onChange event handler. We have toChange that so it accesses the set method instead of the variable property directly:


protected function onChange(e:ListEvent):void{
    setSelectedAnswer(this.answer.selectedItem.label);
}

I want to point out that there is nothing code related that will prevent you from having a get method and set method with different access modifiers. But,the ASDoc tool does have a problem with it, which is why I just remove the space between the set and property name. If you don't use ASdocs, feel free to make public getters and protected setters.

To test the setting of the questionTxt, we can make some modifications to our main application file. Add in a TextInput and a button to modify the questionText on q1:


<mx:TextInput id="questionText" />
<mx:Button click="q1.questionText = questionText.text" />

Run and test the code and you'll find that we can change the question text without any issues; and the read only selectedAnswer property is still changing the main application's Text component when it changes. Things are good.

Version 4: Moving to All ActionScript

If you look at your component code, you realize most of it is ActionScript already. It is not a big leap to turn the MXML component into an all ActionScript component. The component first starts with a package definition:


package com.flextras.InsideRIA.MXMLToAS3 {

The package definition is the folder structure where the component is located. So, in my application the YesNoQuestionV4.as file is located in the MXMLToAS3 directory of the InsideRIA directory of the Flextras directory of the com directory. The com directory is located off the main source root. This piece was masked from us in the MXML alternate.

Next we put the class imports:


import mx.containers.HBox;
import mx.controls.ComboBox;
import mx.controls.Text;
import mx.collections.ArrayCollection;
import mx.events.ListEvent;

The only difference between these and the previous MXML Version is that we are importing the HBox, which our component is based off of. The imports were also in a script tag of the MXML component. In the ActionScript version, there is no script tag; in fact there are no tags at all.

Next up, comes the class definition:


public class YesNoQuestionV4 extends HBox{

Classes can use the same access modifiers that properties and methods use. Access modifiers cannot be specified when developing in MXML. Next is the class constructor:


public function YesNoQuestionV4(){
    super();
}

In this sample, the constructor does nothing other than calling its' parent's constructor. But, I'll often use it for defining default styles or performing setup of the component's states. Any code that you commonly write in response to the creationComplete event most likely belongs in the constructor; however MXML components do not support constructors.

Next comes all the ActionScript code that was in the code block from our previous MXML version. I won't replicate it for you here. Finally, the open brackets for the class and package definition close:


}
}

Even though your component is now 100% ActionScript, our main application does not have to change. In a true nod to implementation hiding, the application, or other component, that uses your components do not care whether it was implemented in ActionScript or MXML or some mix of the two.

Version 5: Extending UIComponent

In the previous versions, we were extending the HBox class. This makes our lives a bit easier, because we were able to use the HBox's inherent ability to position and layout our question Text and ComboBox components. However, the layout algorithms in some of the classes may be too complicated for your needs. Sometimes something simpler will offer better performance. For the final rendition of our YesNoQuestion, we're going to extend the UIComponent. The first line to modify is the class definition. Previously it extended HBox, now it extends the UIComponent, like this:


public class YesNoQuestionV5 extends UIComponent

That is the only line of code that needs to change, but we do need to make some additions. There are two Flex component LifeCycle methods we haven't implemented yet, measure() and updateDisplayList(). Implementing these two methods will finish our component.

The purpose of the measure() method is to decide in the ideal height and width that your component needs without showing scroll bars. A component's parent is ultimately responsible for its' size, so the measure() method is really just setting suggestions, via the measuredHeight and measuredWidth property.

This is the method:


override protected function measure():void{
super.measure();
this.measuredHeight = question.measuredHeight + answer.measuredHeight;
this.measuredWidth = question.measuredWidth + answer.measuredWidth;
}

The method overrides the parent, and calls the super version of its method. Then it calculates the measuredHeight by adding the measuredHeight and measuredWdth of each child, respectively. In most cases, the measure method just loops over the children and calculates the values similar to what we've done here.

The measure() method can, optionally, set the measuredMinWidth and measuredMinHeight properties. These properties specify how small the component can go before it stops sizing down. I did not specify those values here, but often default them to 100 just so that they have a value. I've run into odd issues when using percentage heights on components that do not specify the minimums.

The last method to implement is updateDisplayList(). updateDisplayList() is used primarily to position and size the children. However, you can also use it for other display items, such as setting styles or drawing with the graphics API. This is our updateDisplayList() method:


override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
    this.question.setActualSize(
this.question.getExplicitOrMeasuredWidth(),
this.question.getExplicitOrMeasuredHeight());

    this.question.move(0,0);

this.answer.setActualSize(
this.answer.getExplicitOrMeasuredWidth(),
this.answer.getExplicitOrMeasuredHeight());

    this.answer.move(this.question.width, 0);
            
}

updateDisplayList() contains to arguments, the unscaledWidth and the unscaledHeight of the component. These values are, essentially, the height and width that you want to use to size your component. To position the components, use the move method. The first one, question, is positioned at the top left corner, with an x position of 0 and a y position of 0. The answer component is positioned next to the first one, with a x position equal to the width of the question instance. The answer's y value still remains 0.

setActualSize() is used to size the components. In this case, we use the two methods: ,getExplicitoOrMeasuredWidth() and getExplicitOrMeasuredHeight(). Since we never set an explicit height or width, this sets the components to their measured height and width.

Final Code

Before you start to build your components, think for a second. Are these components that you want to optimize for reuse and use in a lot of different places, and a lot of different ways? Or are these onetime components that you want to build for your application? Even if you can build everything in ActionScript, it may not be worth your extra time. But, even with MXML components, you can still make use of the ActionScript techniques and Flex component lifecycle methods to make robust components.

For the same of completeness, the final code follows the end of this article.


package com.flextras.InsideRIA.MXMLToAS3
{
    import mx.containers.HBox;
    import mx.controls.ComboBox;
    import mx.controls.Text;
    import mx.collections.ArrayCollection;
    import mx.events.ListEvent;
    import mx.core.UIComponent;
            
    public class YesNoQuestionV5 extends UIComponent
    {
        public function YesNoQuestionV5()
        {
            super();
        }

        [Bindable]
        public var dp : ArrayCollection = new ArrayCollection([
            {label:'Yes'},
            {label:'No'}
        ]);
        
        private var _questionText : String;
        private var questionTextChanged : Boolean = false;
        [Bindable]
        public function get questionText(): String{
            return this._questionText;
        }
        public function set questionText(value:String):void{
            this._questionText = value;
            this.questionTextChanged = true;
            this.invalidateProperties()
        }
        
        private var _selectedAnswer : String
        [Bindable(event='selectedAnswerChanged')]
        public function get selectedAnswer (): String{
            return this._selectedAnswer;
        }
        
        protected function setSelectedAnswer(value:String):void{
            this._selectedAnswer = value;
            this.dispatchEvent(new Event('selectedAnswerChanged'));
        }
        
        protected var question : Text;
        protected var answer : ComboBox;
        
        override protected function commitProperties():void{
            super.commitProperties();
            if(this.questionTextChanged == true){
                this.question.text = questionText;
                this.questionTextChanged = false;
            }
        }
        
        override protected function createChildren():void{
            super.createChildren();
            
            this.question = new Text();
            this.addChild(this.question);
            
            this.answer = new ComboBox();
            this.answer.dataProvider = this.dp;
            this.addChild(this.answer);
            this.answer.addEventListener(ListEvent.CHANGE, onChange);
        }
        
        override protected function measure():void{
            super.measure();
            
            this.measuredHeight = this.question.measuredHeight + this.answer.measuredHeight;
            this.measuredWidth = this.question.measuredWidth + this.answer.measuredWidth;
        }
        
        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
            this.question.setActualSize( this.question.getExplicitOrMeasuredWidth(), this.question.getExplicitOrMeasuredHeight());
            this.question.move(0,0);
            this.answer.setActualSize(this.answer.getExplicitOrMeasuredWidth(), this.answer.getExplicitOrMeasuredHeight());
            this.answer.move(this.question.width, 0);
            
        }
        
        
        protected function onChange(e:ListEvent):void{
            setSelectedAnswer(this.answer.selectedItem.label);
        }

        
    }
}

360|Flex is Coming in April

If you're scared that Flash is dead; I can understand the fears. Adobe has been stomping us into the ground as if were the ashes of a freshly smoke cigarette.

I expect 2012 will be a year of transition for Flash Platform Developers. It may be because we have bitterness towards Adobe, or that we want to "follow the jobs", or just because we love learning new stuff. We'll spend a lot of time learning new technologies, such as Objective C, Java, and HTML5.

Learning all that new stuff will make us smarter, and better, developers all around. The 360|Flex schedule is full of sessions on these alternate technologies. If you're a Flex Developer and are looking for your next steps, this is a great conference to go to.

I'll be speaking on building games with Flex, and explaining why that is probably a bad idea. There will be tons of good info you can take with you back to Enterprise apps, especially in the mobile space.

I think there is a good chance that I'll be paying the bills by Flexing long beyond 2012; but that won't stop me from learning new stuff. Swing by 360|Flex in Denver this April 15th-18th and say Hi to me.

More Entries

All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.