Archive for August, 2006

Grey Line

My primary clients are Java shops. When I suggest using Adobe Flex 2 as a rich client tool for their Web applications, they typically ask about the cost on the server side. Expected answer: free. When I start telling them about really powerful features of Flex Data Services, they like it. They just do not like the licensing cost,which is very reasonable. But Flex 2 it’s too young, and some people are still in denial phase. It’ll change soon, but there got to be a free solution. Just to get the foot in the door. And there is one.

I’ll be using a JavaServer page (JSP) here, but you can replace a JSP with any technology you’re comfortable with: servlets, Active Server Pages, Python, PHP et al. Whatever can spit out an XML to a Web browser should work the same way.

I’ll show you a really simple application written in Flex 2 that talks to the XML producing JavaServer page. Just to make it simple, let’s take an XML with the information about employees:

<people>
<person>
<name>Alex Olson</name>
<age>22</age><skills>java, HTML, SQL</skills>
</person>

</people>

Now, let’s hardcode this (I’ve got three persons) into a super simple JSP that consists of one out.println() call, where the xml should go between the double quotes:
<%out.println(“…”); %>

The complete JSP looks like this (just put your XML in one line so you won’t bother with string concatenations):
<%
out.println(“<?xml version=\”1.0\” encoding=\”UTF-8\”?><people><person><name>Alex Olson</name><age>22</age><skills>java, HTML, SQL</skills></person><person><name>Brandon Smith</name><age>21</age><skills>PowerScript, JavaScript, ActionScript</skills></person><person><name>Jeremy Plant</name><age>20</age><skills>SQL, C++, Java</skills></person></people>”);
%>

Deploy this JSP under some servlet container. I have Tomcat, so I just saved it as employees.jsp under my webapp\test directory. Do a sanity check to make sure that you’ve deployed this JSP correctly: entering http://localhost:8080/test/employees.jsp in your Web browser has to return the employee data.

Now comes the client part. If you have extra $500 laying around, purchase a license of Flex Builder from Adobe and enter the code below code in its editor. If you do not want to spend any money, just type this code in any text editor and use free command line mxmlc compiler that comes with Flex 2.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
applicationComplete=”employees.send()”>
<mx:HTTPService id=”employees” useProxy=”false” method=”POST”
url=”http://localhost:8080/test/employees.jsp” />

<mx:DataGrid dataProvider=”{employees.lastResult.people.person}” width=”60%”>
<mx:columns>
<mx:DataGridColumn dataField=”name” headerText=”Name”/>
<mx:DataGridColumn dataField=”age” headerText=”Age”/>
<mx:DataGridColumn dataField=”skills” headerText=”Skills”/>
</mx:columns>
</mx:DataGrid>
</mx:Application>

Not too much typing, isn’t it?

This code uses the <mx:HTTPService> component that allows you to connect to a specified URL either directly or through a proxy. In my example I just specify the URL of my JSP. The data provider of my data grid uses binding (see the curly braces) and E4X syntax to parse the XML and populate this table with the elements located under the

XML tag that is coming from our employees.jsp. Next month, I’ll write a piece explaining Flex data binding in more details. On the application Complete event, we send a request to the HTTPService object known under id employees, and our JSP readily returns the XML, which is bound to the data grid. Compile and run this program, and it’ll show you the following:

Not a bad result for a dozen lines of code.

Of course, it’s better to be rich and healthy than poor and ill. But my point is that even poor (or pretending to be poor) people can use Flex 2 with their existing server side Web tools for free.

Read about Flex to servlet communication at http://flexblog.faratasystems.com/?p=143

Comments (6)

 

Grey Line

For years, object-oriented programmers knew that one of the main OOP features is encapsulation: an ability to hide and protect object internals. Private and protected properties were invented to support just this. But who are we hiding from? From stupid developers who will decide to use our smart framework classes.
In some OOP languages only descendent classes can access protected variables from the ancestor. Java relaxed this rule a little bit and allows accessing protected variables from classes located in the same package. Recently, I had to extend a class from a particular third party framework, which had a protected variable defined. My class was not located in the same package as that third party component…

Let’s look at the example: the code below works fine:

public class Father {
    protected int abc = 25;
}

public class Son extends Father{
   public Son (){
       System.out.println(“abc=” + abc);
   }
}

public class MyNewClass {
   public static void main(String[] args) {
       Son son = new Son();
       System.out.println(“Son.abc=”+ son.abc);
   }
}

The MyNewClasss is happily printing
abc=25
Son.abc=25

Now move the Father and Son to the package com.thirdparty.framework.
After adding the import com.thirdparty.framework.*; to MyNewClass, the code still does not compile complaining that son.abc is not visible. Of course, because designers of the third party framework wanted to protect their precious abc variable, and they wanted to force me to inherit MyNewClass from their Father or Son.. Did they achieve their goal? Not at all. They just forced me to create a Grandson in my default package with a public getter to the abc property.

import com.thirdparty.framework.Son;
public class Grandson extends Son {
public int getAbc(){
return abc;
}
}

And MyNewClass now looks as follows:

public class MyNewClass {
   public static void main(String[] args) {
      Grandson grandson = new Grandson();
      System.out.println(“Grandson.abc=”+ grandson.getAbc());
   }
}

It’s just annoying that I need to add the GrandSon because designers of the third party framework decided to make the abc protected.

If you want to restrict the access to a property, make it private and give me a public getter, if needed. If you want to let everyone work with a property, make it public.

But who needs this protected access level?

You may also be wondering, what this has to do with Flex? I’ll tell you. ActionScript 3 is also an object-oriented language, and people will create their own components by extending classes that are available in the Flex framework. What if I want to access a variable that exists in a Flex component? If Flex designers made it protected, I’ll have to make my code more complex then needed to overcome this design issue.

Comments (4)

 

Grey Line

I am staying away from the heated discussion on WebServices vs RPC vs HTTPRequest vs FDS. Here at least there is a smaller chance that people would feel necessary to defend their point of view, and approach they claim to be successful.

First, I have to admit that I used all of them and to some extent is guilty of the flame mails in the past proclaiming flavor of the month the best thing invented. In the years to come, while running certain applications, I had to do adaptations, compromises, and run-arounds to make damn thing work.

It is true for WebServices – regardless of what industry says they do not work outside of controlled environment. The parsing libraries are large and slow, large datasets have bad performance, router tend to break them, recoverability is bad, and security systems always have problems with them. For 4 years while in pure WebService environments, I had to provide alternative (XML) packaging to deal with the above issues, tweak compression filters for every router/https error known to human kind while claiming that it is wort it as the lowest denominator solution that is fully open and provide widest range of servers and clients. I am still have to see those system implementing second type of client or moved to different server platform

On the other end of spectrum, I would not use FDS for large reporting system for example as it was clearly engineered for different types of applications

RPC and HTTP can be customized by small development team to provide ideal solution for your problems. Take RPC – (RemoteObject) – I can give any of developers here the request to get it working with any platform – PHP, Java, C++, ASP or whatever – and can expect reasonably working gateway in weeks. I would add few options to our code generators, and it would produce platform specific code for serialization/deserialization that would be both fast and reliable.

The point I am trying to make it this: there is no magic bullet or single protocol for anything. You need to see through it  and try to solve business problem first. Connectivity in Flex is so rich and simple, you would be able to adopt and use all options in one day. Then you decide what works and what does not – and still keep your options open.

Technorati Tags: , , , ,

Comments (1)

 

Grey Line

Half year ago I made few comments regarding tricks I like to use when developing large Flex 2 applications. SInce then I have been receiving steady stream of emails – once every week in the beginning, up to few per days lately. They are asking for information from the upcoming Ria Book we are writing (http://www.riabook.com).  Apparently, there are quite a few developers that a) become impatient if the build takes more then 5 seconds and b) concerned that their application will be delivered to the user with similar attention span that could walk away in 10 seconds  or less - regardles of artwork in the progeress meter.

That pretty much forces developers to break the applications in the manner similar to the current generation of loosely  applications:

  • application has to use RSL methodology to speed up development and minimize linkage time 
  • bootstrap application has to be kept to bare minimum – just initialize global managers and list common runtime libraries – to keep “rebuild” time low and initial load fast
  • optimized runtime libraries – while it is tempting to load complete  framework SWC with every application, it would amount to extra 500-600KB on the initial download – better managememt via automatic extract to shared RSL is required
  • application should make use of automatic download of “pages” – essentially parts of application that are either optional or independent or can be customized/added due to subscription /security.

Given those requirements the book talks about static linkage of Flex applications (unlike classical environments that compile everything and then link object modules Flex starts from the “application” and pools necessary resources via sophisticated linker/preprocessor/compiler/optimizer/packager workflow. The book describes the differences between MXML and ActionScript applications, differences between compile-time and run-time linkafe, class loading, self-initialization of dynamically loaded SWFs, and other small details that you only need to know when your application grows over 10-15 screens /1MB of statically linked SWF.

I am starting this thread here in format of Q&A to answer the forementioned issues.

Technorati Tags: , , , , , , ,

Š

Comments (3)

 

Grey Line

IBM Developers Works has a tutorial on how to build an RSS reader using AJAX. The amount of code you need to write is scary (and this is not the complete code). Adobe Flex 2 plus a simple Java programming to support DB interaction allows you to achive the same functionality using A LOT LESS coding.Just take a look at this screen:

The Flex 2 code below populates the bottom portion of the screen with financial news based on the selected stock on top ( (it does not work with a DB to store the RSS source so it’d add some 50 lines of Java code ). The data come from the Yahoo! Finance RSS feed. The URL looks as follows: http://finance.yahoo.com/rss/headline?s=MSFT
The suffix can be MSFT or whatever is selected on top is being passed to the code below.
Flex object is used through a proxy deployed under Tomcat or any other servlet container.
The entire application code and its description can be found in this article.

&lt;mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml"
title="News" width="100%" height="100%"�>
&lt;mx:DataGrid id="newsGrid" width="100%" height="100%"
dataProvider="{newsFeed.lastResult.channel.item}"�variableRowHeight="true">
&lt;mx:columns>
&lt;mx:DataGridColumn headerText="Date"�dataField="pubDate" width="200"/>
&lt;mx:DataGridColumn headerText="Title"�dataField="title"�wordWrap="true" />
&lt;mx:DataGridColumn headerText="Description"�dataField="description"�wordWrap="true"�/>
&lt;mx:DataGridColumn headerText="Link"�width="130">
&lt;mx:itemRenderer>
&lt;mx:Component>
&lt;mx:LinkButton label="{data.link}"�click="navigateToURL(new URLRequest(data.link), '_blank')"/>
&lt;/mx:Component>
&lt;/mx:itemRenderer>
&lt;/mx:DataGridColumn>
&lt;/mx:columns>
&lt;/mx:DataGrid>
 
&lt;mx:HTTPService id="newsFeed" useProxy="true"
destination="YahooFinancialNews"�concurrency="last"
resultFormat="e4x" fault="onFault(event)"�>
&lt;/mx:HTTPService>
 
&lt;mx:Script>
&lt;![CDATA[
import mx.utils.ObjectProxy;
import mx.rpc.events.*;
public function set security(value:String):void {
this.title = "News: " + value;
newsFeed.send({s:value});
}
 
private function onFault(event:FaultEvent):void {
mx.controls.Alert.show(
"Destination:" + event.currentTarget.destination + "n" +
"Fault code:" + event.fault.faultCode + "n" +
"Detail:" + event.fault.faultDetail, "News feed failure" );
}
]]>
&lt;/mx:Script>
&lt;/mx:Panel>

Technorati Tags: , , ,


Š

Comments (1)

 

Grey Line

There was a big thread on FlexCoder forum related to the lack of BigDecimal class on the client. It boiled down that the only implication of that is that if you use BigDecimal and other exotic datatypes on the server side it can be rounded incorrectly.  To cure it there was proposition to build custom ActionScript BigDecimal class and serialization that would solve the issue. Here are my thoughts on the subject – in the thread context:

There are few ways to look at the problem – theoretical (as a former mathematician) or practical (as Wall Street programmer for the last 17 years). It is a big problem – theoretically. Numbers obviously do not match. It has always been that way – and I can probably dig messages from 15 years old messages CompuServe describing exactly the same precision issues with almost any type (timestamp, numbers, rowid, etc) when the client and the server do not share the same underlying data structure. The practical solution I have seen is not to do calculations on the server, but rather do intelligent rounding on protocol level. With your sample of x=1.919999… rounding to 2 decimal places you go with x = round( round(x+.5),3),2)

Please take a look how the db drivers deal with the same issue when they need to include timestamp or double in WHERE portion of update/delete statement – they always have the same issue as client precision is almost always different from the server one.

If you use automatic code generator for your database access ( we use our own daoFlex tool that you are welcome to take a look at), you can use DB precision attribute to automate rounding for the numbers on updates – making your programmers blissfully unaware of the problem.

The next step is to understand why Flex is dealing not just with single double type, but gets “int” in the conversion. Typical DB case would be retrieval argument. If you try to update Sybase’s table that have int id as primary key, the statement “where id=?” with setDouble(1, param) it will not use index on id (but will find the record as the rounding will kick in later). At that point you are looking at full table scan to update single record – and it might be much worse problem then loosing one cent on rounding.

Bottom line is that you always have to be aware that ANY data crossing machine boundaries with an exception of string needs to be rounded. You have to make sure your DAO layer can make use of DB metadata to hide it from the developers that are guaranteed to make the mistake.

Sincerely,
Anatole Tartakovsky

Comments (1)

 

Grey Line

A lot of things happening here and I can not make myself to do proper project management by the book. If you are also swamped, need to do a lot of prototypes that will be refactored later or just do not like to do things by the book here is a post for you: bypass flex remoting registration and get extra functionality in return (disclaimer: we all know that it is security hole, but you can eliminate it by allowing access to the classes that match certain patterns)

Here is self explainatory package. Unload Flex portion in your Flex project, Java portion in Java, register PojoFacade class for remoting – it will use introspection / serve as facade for all your pojo classes on server.

But that is not all. The package located here allows you to create custom remoting batches, transactions or just add server-side error  processing/logging. Please note that you will need to enforce security as we bypass registration XML

Enjoy,

Anatole

Technorati Tags: , , , ,

Comments

 

Grey Line

I’ve been doing a small research as to what’s happening under the hood when Flash Player 9 loads and starts a Flex 2 application. Since Flex 2 is still pretty young, there is not too many resources are available, so I’d appreciate any feedback.
The main manager that controls the application window, creates and parents the Application instance, popups, cursors, manages the classes in the ApplicationDomain, and more. The SystemManager is the first class that is instantiated by Flash Player for your application. It stores the size and position of the main application window, keeps track of its children, such as floating popups and modal windows. Using the SystemManager you can access embedded fonts, styles and the document object. SystemManager also controls application domains, which are used to partition classes by security domains (see description of the ApplicationDomain class in Flex Language Reference).
If you’ll be developing custom visual components (descendents of the UIComponent class), keep in mind that initially such components are not connected to any display list and the SystemManager=null. Only after the first call of the addChild() a SystemManager will be assigned to them. You should not access SystemManager from the constructor of you component, because it can still be null.

In general, when the Application object is created, it goes through the following steps:

1. Instantiation of the Application object begins.
2. Initializes the Application.systemManager property
3. The Application dispatches the preinitialize eventat the beginning of the initialization process.
4. The method createChildren() is called on the applicatoin. At this point each of the application’s components is being constructed, and each component’s createChildren() will be also called.
5. The Application dispatches the initialize event, which indicates that all application’s components have been initialized.
6. The creationComplete event is being dispatched
7. The Application object is added to the display list.
8. The applicationComplete event is being dispatched.

For performance reasons, it is not recommended creating components in a constructor – use createChildren() for this.

As opposed to Flash movies that consist of multiple frames being displayed over a timeline, Flex SWF files have only two frames. The SystemManager, Preloader, DownloadProgressBar and a handful of other helper classes live in the first frame. The rest of the Flex framework, your application code and embedded assets like fonts and images resides in the second frame. When Flash Player initially starts downloading your SWF, as soon as enough bytes come for the first frame, it instantiates a SystemManager, which tells player to stop at the end of the frame. Then SystemManager creates a Preloader, which creates a DownloadProgressBar and these two objects are watching the rest of the byte streaming-in process. What all bytes for the first frame are in, SystemManager sends the enterFrame for the second frame, and then renders other events. Eventually, the Application object dispatches the applicationComplete event.

You may say, why do I need to know what’s happening before my application starts? This knowledge may become quite handy. For example, you can create a fading splash screen with the image of your choice by substituting the standard Flex Preloader and the DownloadProgressBar objects with the custom ones. Ted Patrick from Adobe has provided a sample code that does exactly this: displays a splash screen using an image from a from a .gif file (see http://www.onflex.org/ted/2006/07/flex-2-custom-preloaders.php).

The application tag of this sample looks pretty straightforward:

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
preloader=”preload.CustomPreloader” >

Download the code from this application and you’ll see that the classes CustomPreloader that extends the DownloadProgressBar and a helper WelcomeScreen that loads the image and fades it away are also pretty small.

The most important feature of the Flex 2 is that it’s an open and extendable framework. I’m used to be in complete control with Java, and Flex does not tie my hands either.
That’s all…for now

Comments (4)