Archive

Posts Tagged ‘Flex’

Quick Tip -Type Coercion failed: cannot convert mx.managers::BrowserManagerImpl to mx.managers.IBrowserManager

OKay. This is a real quick post. You may find this error (or error of similar nature) occurring when you try loading a Flex application in another Flex application.

e.g. TypeError: Error #1034: Type Coercion failed: cannot convert mx.managers::BrowserManagerImpl@2ee8581 to mx.managers.IBrowserManager.

FIX: Import the class to which the compiler is trying to cast to in the parent application. In this case

import mx.managers.IBrowserManager;
private var bm:IBrowserManager;

Hope this will save some of your time.

Categories: Quick Tip Tags:

Flex Builder and SVN

For seamless integration with Flex/Flash Builder IDE and SVN use ‘subclipse’ plugin. Here, http://subclipse.tigris.org/update_1.0.x/, you would find the latest plugin for eclipse.

To install:
Help->Find And Install->Search for new features for install->New remote site
Add Name: subclipse and in URL put http://subclipse.tigris.org/update_1.0.x/

subclipse

To Checkout the project from SVN:
File->New->Other..->SVN->Checkout projects from SVN->
Click “Next” -> Create a New Repository-> Add URL and then select the project folder

There are couple of ways to create branch. But before that one key note.
Say if you are using Tortoise SVN as your desktop client and subclipse as the the eclipse plugin. There could be version conflicts; so do ensure that you make all commits and checkout through subclipse.

Coming back to branching.
Follow these steps from your desktop client for Branching:

1- Create a new folder in SVN for holding branches e.g. “branches”
2- Right Click the folder (trunk) whose branch need to be created
3- Selected “Branch/Tag” option
4- In “To URL” add the location https://foo.com/svn/foosvn/branches/{foobranch}
Note: Don’t create {foobranch} folder on SVN beforehand. If you do then you might get an error saying “Path Already Exists”.
5- Now select an option the choice e.g.”Head Revision”,  “Working copy” etc.
6- Click OK
This will create a folder named “foobranch” as a branch of trunk

To Switch to branch:

1- Right click the project folder (which you have checkout from trunk) in the Flex Builder IDE
2- Select Team->Switch..
3- Add the branch URL in “To URL”
Press OK and now your project will be on branch. Any changes that you might have made in your local will now get committed in the branch when you make a commit now.

Categories: Flex Tags: , ,

Quick Tip – Flex Profiler Issue

Flex profiler is one of the biggest advantage of using Flex Builder IDE. It works wonders for developer who want to understand the nuances of flash player. If you want to write clean code and avoid memory and performance issues, use profiler.

Read more about profiler here: http://livedocs.adobe.com/flex/3/html/help.html?content=profiler_1.html

Okay, so the post is not about what and how profiler works. In most of the cases you just need to click the “profile..app” button in the IDE. But at times you may find it not working. Here I am putting down one possible way to fix it and look out for:

Flex profiler actually listens for messages from the profiler agent. The profiler agent is a swf launched in parallel to your main swf. It is located in your Flex workspace at .metadata/.plugins/com.adobe.flash.profiler/ProfilerAgent.swf.

Now Flex Builder reads a file called mm.cfg which has the location profileragaent.swf. mm.cfg can be located at  c:/users/user (Windows). It should have a name-value pair indicating the location of ProfilerAgent.swf. Create (or edit existing) mm.cfg and add following line

PreloadSwf=Drive:/…/yourworkspace/.metadata/.plugins/com.adobe.flash.profiler/ProfilerAgent.swf?host=localhost&port=9999

In addition to above you can other options which are quite helpful for debugging:

ErrorReportingEnable=1
TraceOutputFileEnable=1

Above options will redirect the trace() output to an external file which can you browse using any text editor.

The flashlog.txt file will be created in the following location: C:\Documents and Settings\username\Application Data\Macromedia\Flash Player\Logs\flashlog.txt

Let me know if this post saved your couple of hours :)

Flex profiler is a part of the Flex Builder IDE, that listens for messages from the profiler agent. The profiler agent is a swf launched in parallel to your main swf. It is located in your Flex workspace at .metadata/.plugins/com.adobe.flash.profiler/ProfilerAgent.swf.

I had a hard time getting it worked. Here is what worked to make it working:

Create (edit existing) file named mm.cfg (location windows: c:/users/user) and add following line

PreloadSwf=F:/user/workspace/.metadata/.plugins/com.adobe.flash.profiler/ProfilerAgent.swf?host=localhost&port=9999

In addition to above you can other options which are quite helpful for debugging:

ErrorReportingEnable=1
TraceOutputFileEnable=1

Above options will redirect the trace() output to an external file which can you browse using any text editor.

The flashlog.txt file will be created in the following location:

Windows; C:\Documents and Settings\username\Application Data\Macromedia\Flash Player\Logs\flashlog.txt

Categories: Quick Tip Tags: ,

Communicating with a loaded Application in Flex 3.0

Communicating with a loaded flex application is not intuitive.  SWFLoader lets you load one Flex Application into another Flex Apllication as a SWF file. Once the SWF is loaded you can retrieve the SystemManager (class that manages an application window).

_objLoadedAppSystemManager = SystemManager(_objLoader.content);
trace(_objLoadedAppSystemManager.application) //null

The SystemManager’s ‘application’ property holds the reference to the application loaded. The problem is if you try to access this property once the SWF is loaded (by listening SWFLoader’s COMPLETE or INIT event) you will get null since the loaded ‘application’ didnt get initialized properly. One of the solution is to listen to the SystemManager’s APPLICATION_COMPLETE event.

_objLoadedAppSystemManager.addEventListener(FlexEvent.APPLICATION_COMPLETE, onLoadedAppInit);
...
...
private function onLoadedAppInit(objEvent:FlexEvent):void
{
	_objApplication = (_objLoadedAppSystemManager.application) as Object;
	_objApplication["functionname"](param);
}

Now you would be able to call the function (e.g. “functionname” as shown above). This function should be defined the main application file/class of the loaded application.

Categories: Flex Tags: ,

Quick Tip – Font embedding in Flex 3.0 – II

There is so much to font embedding that I keep getting new problems and resolutions :)
The problem: Embedding font on textfield which renders HTML text.

...
instancetextObj.htmlText = "<font size='28' face='Arial' >Hello <b>How</b> <font
size='28' face='SomeOtherFontFace' >Are </font> You</font>"
...
<mx:Text id="instancetextObj" />

I ensured that the fonts used above are embedded. My css look like:

@font-face {
    src      : url("asset/font/embed_fonts.swf");
    font-family    :  "SomeOtherFontFace";
}

@font-face {
    src      : url("asset/font/embed_fonts.swf");
    font-family    :  "Arial"; 

}

The swf has all the necessary fonts embedded (all required font-weight/typefaces). But somehow it didn’t worked.

Solution:
The solution is that the texfield requires a default font family defined which is embedded
So if you make a simple change to the mxml definition of your textfield like this:

<mx:Text id="instancetextObj" fontFamily="Arial" />

It will work. :)
The better solution is to defined the font family in a “global” style name in css

global
{
     font-family   :   "Arial"
}

I hope this might save your few hours!

<span style=”font-family: Arial;”>Hello <strong>How</strong> <span style=”font-family: Dadhand;”>Are </span> You</span>

Categories: Quick Tip Tags: ,

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: ,

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: ,

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: , ,