Quick Tip – Font embedding in Flex 3.0

Most fonts have four typeface styles: normal, bold, italic and bold-italic. Each typeface need to be embedded separately (even the normal one). You can embed TTF (TrueType) and OTF (OpenType) in Flex. Embedded fonts need not be installed in client’s machine and are anti-aliased for smother edges and better readibility.

Fonts such as Type 1 Postscript can also be embedded by embedding it through SWF and runtime loading. Fonts size smaller than 10 looks fuzzy even on embedding. For this made “advancedAntiAliasing: true” in the font style .

There are primarily two ways to embed fonts through CSS in flex:
- Providing direct source (src) to the TTF or OTF font
- Providing src to the SWF which has the fonts embedded.

Syntax:

@font-face
{
src: url("location") | local("name");
fontFamily: alias;
[fontStyle: normal | italic | oblique;]
[fontWeight: normal | bold | heavy;]
[advancedAntiAliasing: true | false;]
}

The above is self explanatory. The point I would like to highlight is that when you have fonts with separate typeface files for each font style.
For example font MetaOT has MetaOT-Norm for plain (normal) style, MetaOT-Bold for bold and so on. If such is the case, then remember not to specify “fontWeight” for these because then you would be pushing the compiler to understand bold property of a bold typeface font which can lead to improper rendering.

@font-face
{
src                    :    url("asset/fonts/embed_meta.swf");
fontFamily            :     "MetaOT-Norm";
}
@font-face
{
src                    :    url("asset/fonts/embed_meta.swf");
fontFamily            :     "MetaOT-Bold";
}

font-family name should be exactly same as shown in the fla file while embedding. I would suggest using either flash 8 or Flash CS3 for generating the swf.

To use this font-face add it in the style:

.QuestionText
{
font-family            :    "MetaOT-Bold";
color                :     #000000;
font-size            :    16;
}

See the style doesn’t specify fontWeight. One issue which could occur using in separate typeface files is that if any of the parent component of the component using the above style, applies fontWeight:bold then the component wouldn’t render the font properly. This is because the child component takes parent property if not specified. So to make it full-proof use this :

.QuestionText
{
font-family        :    "MetaOT-Bold";
fontWeight        :     normal;
color                :     #000000;
font-size           :    16;
}

fontWeight is made “normal” so that no additional property gets applied.


Categories: Quick Tip Tags: ,

XML Namespace and Actionscript 3.0

As defined by the W3C , an XML namespace is a collection of XML elements and attributes identified by an Internationalized Resource Identifier (IRI); this collection is often referred to as an XML “vocabulary.”

IRI is usually an URI e.g. http://www.brupp.com. Let’s understand this concept briefly. Take this example:

<root xmlns:brupp="http://brupp.com/">
     <data>
          <title>Title</title>
          <link>http://foofoo.com</link>
          <brupp:link href="http://brupp.com/somelink">Some Data</brupp:link>
          <description>description data</description>
          ...
    </data>
...
...
</root>

The XML above has no default namespace. Now lets suppose the XML demands need of reuse of some other existing namespace “http:/brupp.com”  which also has a <link> node. To avoid any ambiguity between the <link> node of both vocabulary XML namespace are added.

Why namespace? As described above it helps in leveraging different vocabulary of XML with same element and attribute name. Understand this way; you created a XML structure for a “Product” and “Customer”. Now you want to utilize these XML structure in a new “Database” XML. The problem: Both “Product” and “Customer” uses <id> node. Solution: Place them in different namespace (simply a unique string) and then use them as shown above xmlns:prod=”some namespace”.

In actionscript 3.0 you can access both< link> node without much hassle. See below a simple example created in Flex:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="732" height="434"
     creationComplete="onCreationComplete()">
     <mx:Script>
     <![CDATA[
          namespace brupp = "http://brupp.com/";
          use namespace brupp;
          private var _objXML:XML =
                     <root xmlns:brupp="http://brupp.com/">
                       <data>
                         <title>Title</title>
                         <link>http://foo.com</link>
                         <brupp:link href="http://brupp.com/somelink" >some</brupp:link>
                         <description>description data</description>
                       </data>
                     </root>;

         private function onCreationComplete():void
         {
             trace("default link  " + _objXML.data.link);

         }
    ]]>
    </mx:Script>
</mx:Application>

The trace above will show both <link> nodes because we have told the compiler to “use namespace” brupp. If you comment the code line:

use namespace brupp;

and then run the application again; the “brupp” namespace <link> will not appear.

To add, if you only want to access the “brupp” namespace <link>, do this:

trace("brupp link  " + _objXML.data.brupp::link);

If you liked this post, please spread the word. Share and cheer!!!.

If you need more information on above post drop a comment. Your comments are valuable and helps in molding the article so do share in.


Categories: Flex Tags:

Quick Tip: Issues handling legacy files (Pre-Flash Player 9 swfs)

Loading legacy (pre flash player 9) application/content and communicating with it is avoidable for following reasons:

-        Difficult to communicate (LocalConnection/SharedObject etc)

-        Not reliable behaviour

-        Loading multiple pre-Flash Player 9 SWF’s into the same app breaks sometime

-        Issues with _global, static variables and singleton classes which remain stuck

-        Garbage collection needs to be handled carefully. Pre flash player 9 uses AVM1Movie sandbox which has entirely different garbage collection management and methods

-        Memory leak issues

There are several restrictions on an AVM1 SWF file loaded by an AVM2 SWF file:

  1. The loaded AVM1Movie object operates as a psuedo-root object for the AVM1 SWF file and all AVM1 SWF files loaded by it (as if the ActionScript 1.0 lockroot property were set to true). The AVM1 movie is always the top of any ActionScript 1.0 or 2.0 code execution in any children. The _root property for loaded children is always this AVM1 SWF file, unless the lockroot property is set in a loaded AVM1 SWF file.
  2. The AVM1 content cannot load files into levels. For example, it cannot load files by calling loadMovieNum(“url”, levelNum).
  3. The AVM1 SWF file that is loaded by an AVM2 SWF file cannot load another SWF file into this. That is, it cannot load another SWF file over itself. However, child Sprite objects, MovieClip objects, or other AVM1 SWF files loaded by this SWF file can load into this

References:
http://jessewarden.com/2007/05/controlling-flash-player-8-swfs-in-flash-player-9-swfs.html
http://livedocs.adobe.com/flex/2/langref/flash/display/AVM1Movie.html

Categories: Quick Tip Tags:

Quick Tip: ModuleEvent.Ready not firing

public function loadModule(objEvent:Event):void
{

	var objModuleInfo:IModuleInfo = ModuleManager
                                      .getModule("module/ModuleViewA.swf");
	objModuleInfo.addEventListener(ModuleEvent.READY, onModuleReady);
	objModuleInfo.addEventListener(ModuleEvent.ERROR, onModuleLoadError);
	objModuleInfo.load(); 

}

The above code must be familiar to you when you try loading Module using ModuleManager (flex sdk 3.4). But ModuleEvent.READY won’t fire. Why? because the IModuleInfo object above has local scope and ModuleManager maintains weak references to this object. By the time module loading completes it gets Garbage Collected :) .

Solution
: Maintain the reference to the IModuleInfo object by making it a member variable.

Categories: Quick Tip Tags: ,

Quick Tip – Generating AsDoc

AsDoc is a command line tool for generating API documentation for as HTML pages of your packages/classes.

I prefer to use it as external tool running inside the Flex Builder. It provides a console window to diagnose any issues that might occur during HTML generation.

1) Go to Run->External Tools->Open External Tools Dialog..

2) Add new Program/Configuration

3) Fill Name e.g. asdoc_files

4) Add Location of the asdoc executable (bin folder in your Flex Builder installation)

5) Add “Working Directory” by selecting your project from “Browse Workspace”

6) Add following arguments:
“-source-path “src”
-doc-sources .
-external-library-path=”libs” ”

It is of extreme importance that you should add external library path (as above) for any “SWC” that you have used in the project.

asdoc config

Categories: Quick Tip Tags:

Cairngorm: Getting Started – Part 4

This is fourth and conclusive part of “Getting Started” series of Cairngorm. I hope the first three parts must have shown you a door to enter to this framework. This article will brief about other parts of the Cairngorm and will leave for you to explore and getting into deep of this framework.

Lets start with the left out part of MVC, that is Model. Cairngorm encourages use of having a ModelLocator in the system (a Singleton one) though if you look at ModelLocator its not being referenced in the any other class in Cairngorm framework. So actually you have a choice here to have one or not, to have it singleton or have different model instances directly. Anyways, by definition and implementation the ModelLocator you create should implement IModelLocator interface (which is empty) and scope of this class will be having other model classes and client state maintainence. Each model or data can be then fetched by this ModelLocator.

public class SomeModelLocator implements IModelLocator
{
     ...
     public function get  mySomeViewModel():SomeViewModel
     {
          return _objSomeViewModel;
     }

}

Now lets move to the business layer which consists of delegates and services in Cairngorm. Command with help of Delegates pushes the data to the model. In simpler terms its just another class which connects a command with a service.

public class SomeDelegate
{
...
...
               public function SomeDelegate( responder : IResponder )
               {
                       this.service = ServiceLocator.getInstance()
                                          .getRemoteObject( "someServiceId" );
                       this.responder = responder;
               }

               public function getData() : void
               {
                       var call : Object = service.getData();
                       call.addResponder( responder );
               }

               private var responder : IResponder;
               private var service : RemoteObject;
...
...
}

Key points:

  1. Command instantiates Delegate.
  2. Command implements IResponder.
  3. Command knows only about delegate and provides its reference (‘this’ as IResponder) to the Delegate.
  4. Delegate invokes a Service (through ServiceLocator) and adds the responder (the Command instance) to Service.

So Delegate essentially doesnt do much other than loosening the coupling. Command is only bothered about the result and not from where it is coming from. To sum up business delegates is a proxy services for Command.

Finally the ServiceLocator, its a singleton class that holds the services at one place. Any delegate can request for a service (HTTPService, WebService etc) through it.

<cairngorm:ServiceLocator
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:cairngorm="/2006/cairngorm">

<mx:RemoteObject
id="someServiceId"
destination="servicename"
showBusyCursor="true">
</mx:RemoteObject>

</cairngorm:ServiceLocator>

This is all for what you require for getting started. I hope the series was beneficial for you. If it was; please spread the word. Share and cheer!!!.

If you need more information on above post drop a comment. Your comments are valuable and helps in molding the article so do share in.

Categories: Flex Tags: , ,

Cairngorm: Getting Started – Part 3

To get full benefit from the post I will suggest you to go through the following posts first:

http://brupp.com/blog/2009/09/feed-reader-in-flex/

http://brupp.com/blog/2009/09/cairngorm-getting-started-part-1/

http://brupp.com/blog/2009/09/cairngorm-getting-started-part-2/

Since Flex framework is event driven; Cairngorm is designed in keeping it in mind. For an event to dispatch you need three things:

1) Event – In case of Cairngorm it is “CairngormEvent”.

2) Event dispatcher – “CairngormEventDispatcher”

3) Listener – Handled by FrontController and Command

This is how an event is dispatched in Cairngorm framework:

CairngormEventDispatcher.getInstance()
                    .dispatchEvent(new CairngormEvent("POPULATEGRID"));

CairngormEventDispatcher is a singleton class used to invoke event using “dispatchEvent” function. “POPULATEGRID”  is a event identifier constant which the listener will listen to. Now where is the listener? Listener is the command (loosely said). Lets understand the Command first.

Command is a ephemeral class. It has a very short life. It is “executed” when an event is invoked and dies when the task is completed. Every Cairngorm event we create has an associated command class which handles the business logic when event take place. For a class to be a Command class it should implement the Cairngorm’s  ICommand interface:

package com.brupp.command
{
	import com.adobe.cairngorm.commands.ICommand;
	public class PopulateGridCommand implements ICommand
	{
         ...
              public function execute(event:CairngormEvent):void
	     {
              }

        }
}

The interface asks for the “execute” method which is so to say the listener function of the command class which gets called by FrontController.

OK! So now there is an event there is a listener (so to say) then how it is registered to listen who does the mapping of event and command. Here comes in the FrontController.

package com.brupp.controller
{
	import com.adobe.cairngorm.control.FrontController;
	import com.brupp.command.PopulateGridCommand;

	public class FeedreaderController extends FrontController
	{
		public function FeedreaderController()
		{
			super();
			addCommands();
		}

		private function addCommands():void
		{

			this.addCommand("POPULATEGRID", PopulateGridCommand);
		}

	}
}

So our FrontController is FeedreaderController which holds the mapping (check the code in bold) by utilizing “addCommand” method of “FrontController”. The “execute” method is the single entry to the Command class which is called by the Front Controller when a user-gesture indicates that the user wishes to perform a task for which a particular concrete command class has been provided. FrontController is a centralized request handling class in Cairnorm. As mentioned in Cairngorm API documentation, the role of the Front Controller is to first register all the different events that it is capable of handling against worker classes, called command classes. On hearing an application event, the Front Controller will look up its table of registered events, find the appropriate command for handling of the event, before dispatching control to the command by calling its execute() method.

Diagram below demonstrates the role and flow of control in Cairngorm. Other than what we have discussed in this and previous post the following also depicts the Model. Only Command can change the model. View elements can be bound by model properties so that when a property is updated the View doesnt has to listen and fetch for this information. It is handled all internally by Flex framework. Moreover Command can also update the View directly if the change in View isn’t dependent on Model property.

Cairngorm Micro Architecture

Cairngorm Micro Architecture

So by now you know know where to put which code in Cairngorm. Just to brief all the term/classes we read:

ViewHelper - Your view helper should have code to interact/change view. Remember the class in no brainier. It can just update the view and has no business logic.
FrontController - The front controller shouldn’t do more than mapping events with commands.
Command - Put the brain here. Command can update Model and View (through view helper). Uses delegates to fetch data. Will discuss more on these in the next article.

Categories: Flex Tags: , ,

Cairngorm: Getting Started – Part 2

We will pickup from where we left in the last article http://brupp.com/blog/2009/09/cairngorm-getting-started-part-1/. So lets redesign the feedreader application built in one of the previous post (http://brupp.com/blog/2009/09/feed-reader-in-flex/). Before continuing I ll suggest you to go through the previous two posts I have mentioned or else you will feel off track. At the end of the post you will have fairly good understanding on ViewHelper.

Create a new MXML application file which will be the “default” application file in our case. For the sake of understanding we will name it “FeedreaderUsingCairngorn.mxml“. This mxml is the main view of the application for which we will have a viewHelper, where all the view interaction code will be written.  Lets call it “FeedreaderViewHelper.as”

Download the complete example from here.

package com.brupp.view
{
  public class FeedreaderViewHelper extends ViewHelper
  {
	public function FeedreaderViewHelper()
       {
	       super();
	}
  }
}

Note the helper class should extend the Cairngorm’s ViewHelper. Next is how to provide the “view” access to this helper class. It’s dead simple, just instantiate the helper object in the “FeedreaderUsingCairngorn.mxml” file.

<view:FeedreaderViewHelper id="viewHelper"  />

Now the catch is the “id” that you give to the helper that actually serves as an identification to locate the helper from any class through the Singleton class “ViewLocator” (part of Cairngorm architecture). What happens is that the helper thus instantiated registers its identity mapped with its “id”, while doing so the “ViewHelper.as” class (Cairngorm framework class which is the parent class of our FeedreaderViewHelper) also stores the instance of “FeedreaderUsingCairngorn” in a property named “view” from where it was created. This is an internal mechanism (Will discuss in Advance Cairngorm tutorial series). So now our helper class can access the main view through “view” property like this:

package com.brupp.view
{
  public class FeedreaderViewHelper extends ViewHelper
  {
	public function FeedreaderViewHelper()
       {
	       super();
	}
...
        public function onItemClick(e:ListEvent):void
	{
               FeedreaderUsingCairngorm(this.view).....
	} 

...
  }
}

Now once you have access to the view all the public objects can be accessed by helper; this way you dis-tangle the code from design. A viewhelper can serve multiple related views. Say if the main view has a sub-view called “FeedreaderView.mxml” then this view can have its method defined in the “FeedreaderViewHelper.as” itself. So we will put all our design elements that we created in our “Feedreader” post earlier here with only change that its events are now handled in FeedreaderViewHelper.

<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" >
<mx:Script>
<![CDATA[
import com.brupp.view.FeedreaderViewHelper;
import com.adobe.cairngorm.view.ViewLocator;

[Bindable]
private var _objViewHelper:FeedreaderViewHelper;

public function onCreationComplete():void
{
_objViewHelper = ViewLocator.getInstance().getViewHelper("viewHelper") as FeedreaderViewHelper;

}
]]>
</mx:Script>
...

<mx:DataGrid id="dgFeed" width="100%" height="100%"
itemClick="{_objViewHelper.onItemClick(event)}"
doubleClickEnabled="true"
itemDoubleClick="{_objViewHelper.onItemDoubleClick(event)}">

...
</mx:VBox>

Two important things (in bold) to note. Notice in the code above how the helper is accessed and how the event handling is passed to helper. So just to get started with Cairngorm you need a view and a viewHelper and voila you started digging into the framework slowly.

Summarizing ViewHelper (taken from Cairngorm API documentation) :
ViewHelper is used to isolate command classes from the implementation details of a view. Model-View-Controller (MVC) best practices specify that command classes should interact with the view using the model (see the ModelLocator class), but, in some instances, command classes may require to both interrogate and update the view directly. Prior to performing any business logic, the command class may require to fetch values that have been set on the view; following completion of any business logic, the final task may be for a command class to update the View (user interface) with any results returned, or perhaps to switch the View entirely (to a different screen).

By encapsulating all the logic necessary for interrogating and updating a particular View into a single helper class, we remove the need for the command classes to have any knowledge about the implementation of the View. The ViewHelper class decouples our presentation from the control of the application.

A ViewHelper belongs to a particular View in the application; when a ViewHelper is created, its id is used to register against a particular View component (such as a particular tab in a TabNavigator, or a particular screen in a ViewStack). The developer then uses the ViewLocator to locate the particular ViewHelper for interrogation or update of a particular View.

I’m sure a lot of above must have started making sense to you now except the “Command” stuff. Right? Keep hooked to my future posts. So going back to the feedreader example we now need an event to call the web-service to populate our grid. CairngormEvent, Command and FrontController conjunction serves the purpose and we will see how in the next post.

If you liked this post, please spread the word. Share and cheer!!!.

If you need more information on above post drop a comment. Your comments are valuable and helps in molding the article so do share in.

Categories: Flex Tags: , ,

Cairngorm: Getting Started – Part 1

This is the first one of the series of article about Cairngorm Framework. This is for a beginner who is lost in bunch of classes the Cairngorm comes with. Prerequisite is that you have hand-on experience in Flex and have an idea of design patterns, atleast MVC (if you don’t have please leave a comment and based on requests received I may cover it next series). I am sure you had gone through various other resources, tutorials about Cairngorm before you reached here. Your search will end here. I will try to put it in a lay man’s language and would leave aside the tech jargon. I might not cover all the aspects/features of Cairngorm but surely at the end of this series you will be able to play around Cairngorm classes.

Cairngorm is an architectural framework which was designed to meet the need to medium to complex RIA applications. It is a skeleton which can be used as a starting point for creating your application’s architecture (for more about this, read http://www.adobe.com/devnet/flex/articles/cairngorm_pt1_02.html).  For the sake of understanding, in this article we will look at re-creating the feed reader application which I created in my previous post. Please go through the post as I would be referencing the same in this post. Click here to Download Cairngorm 2.2 .

Before continuing any further lets visit definition of some commonly related (yet different) terms. “Architecture” should be looked specific to the application’s need. So if you have to design a complex application you build an architecture to wrap your application around it. “Architectural framework” (Caringorm, pureMVC, Swiz, Mate etc) can be used as a base for your application architecture. “Application framework” like Flex can be used as a solution for you application design.

There are two ways to study Cairngorm, one is to understand different parts/elements of it and see how and why they are there. Other is to see how and why it actually evolve. I will follow the latter and will start it by taking one of the design pattern it uses and will put each element one by one “in and circum-scribing” it. Cairngorm design aids in separating user gesture, business logic and state of application. It favors event driven programming model. MVC being the principle design pattern on which the Cairngorm is based we will start taking a basic MVC as a starting point and see how different design pattern plugs in and give shape to Cairngorm. Figure below shows the basic communication channels in MVC.

mvcWhen user interacts with the view elements the interaction is directed to Controller. Controller, based on the interaction could either directly respond back to View to update itself (if no change in model) or can ask the model to update itself. Model after doing so will give the update information to all the registered Views. View will fetch the updated data from Model and change itself.

This is just a broad level aspect of MVC there are other communication that can happen in a MVC;  even independent of user interaction, for example Model updating itself after some time interval (stock prices, clock etc). MVC  in itself utilizes different design patterns like Observer and Strategy.

View is essentially where the visual elements are kept so its better to separate the View’s code from the View itself. What this means is that the view’s code/functionality, lets say it ViewHelper, will have all the functionality code to change/update the view (keep in mind that this helper won’t hold the business logic). ViewHelper is a layer of separating the View from other environmental elements. This is an interesting concept of Cairngorm, however it is deprecated in its current release, but I still favors it.

In this article you get to know about frameworks and the first element (ViewHelper) of Cairngorm. In the next article we will look into Commands, Controller.

If you liked this post, please spread the word. Share and cheer!!!.

If you need more information on above post drop a comment. Your comments are valuable and helps in molding the article so do share in.

UPDATED: Next post will elaborate a bit more on ViewHelper

Categories: Flex Tags: , , ,

Creating Feed reader with Flex

This is small article which will detail out steps for creating a feed reader in flex. I know there are lot of feed readers in this world and I am not intended to leave a mark in that space. This article is actually a precursor to my next article which will be about “Cairngorm” framework in which I will take this as an example and base it on Cairngorm framework. So you will be able to compare which lies where in framework and why? If you want me to notify you when the next article is released either subscribe to the feed or leave your comment.

Before you read further, please download the source from here .

The essentials for creating the feed reader as you can see in code are:
a)  HTTPService object (non visual) – To make an HTTP request to the feed url. Note that the resultFormat is set to “e4x” and the result of this request will call “onResult(event)” method.

b) DataGrid - The result will get populated in this. Note that the dataProvider is bound to the _xlFeed in which the result will be populated.

c) TextArea - To show the content of the feed article when DataGrid row is selected.

Feedreader_img

The flow:

1) On creationComplete the HTTPService is invoked with send().
2) On receiving the result the _xlFeed value is set to the list of”item” nodes of the feed xml.
3) As a result the DataGrid shows the result in coloumns as title and published date (you can add more columns, DataGridColumn in the DataGrid)
4) Clicking on an item in DataGrid, extracts the “description” from that item (onItemClick method)
5) On double clicking the item, another node “link” is accessed from the feed and new webpage is launched (onItemDoubleClick method)

Play with other node values and get creative. Extend the application e.g. add feed urls at runtime etc. “Debug” run the application with breakpoint to observe feed structure. Most importantly you should have “namespace“s defined for rss and atom (depend on feed type)  other wise the application won’t work. If this article did any help to you then please spread the word and share this.

Categories: Flex Tags: , , ,