Recently, I was having a requirement to develop the Flex Log management functionality. After doing lots of research and investing a time for 3 to four days I successfully managed the things to achieve the flex logging Mechanism which can log Line Number, Function Name, Class name into log File.
After delivering the functionality I was happy that I have done it Its really a nice feeling. I was hoping for appreciation but result was bit different I have received a clients mail saying that on some of the machines Flex app not working without debug version of Flash Player, It was really an Head scratching experience when application just stopped running with a white background in screen with clock display. I was quite surprised that application which were running perfectly well on my PC, wasn’t displayed properly on some of the PCs.
Hmm.. No Clues at all. I must say Adobe Sometimes handles such situation in very ugly, and with very unprofessional manner, its a horrible handling of such situation by Adobe Flex Framework Developers must criticized them for such things.
After lots of efforts and lots of revision to the newly added code, after doing everything finally the application showed up on one of the problematic machine when I changed the Flash Player version from standard one to debug.
Scenario and Solution
I was using following code
//Call To The Function traceDetails(new Error())
private function traceDetails(err:Error):void { err.getStackTrace(); } On My part i was using the method “getStackTrace()” Here the thing to remember is that getStackTrace() method is only available with Flash Debugger and Not With Flash player. So wherever i do not have Flash Debugger installed my application stops running.
So Things to do
1. Check if You’re using any API call that are only available in Flash Debugger and Not in Flash player (If You found Try commenting that line Application will start running).
2. Solutions may be Install Flash Debugger Version wherever you are running your application but not feasible considering end user because your application is not loaded successfully and you cannot prompt user.
3. In wrapper class put a check with JavaScript for Flash Debugger version availability and if it is not available through JavaScript Message Saying you need to have flash layer Debugger version installed along with link to install it J
4. Simply before your Flash Debugger API calls Check if(Capabilities.isDebugger) only then use those API or Skip those lines.
This is another chapter to the amazing errors, which does not leave behind any signals how to solve it, and more interestingly what is the exact reason for it.
When we have a pretty large code base where many developers check in and check out the code regularly, it is very hard to find the exact cause of the error which comes while compiling the code. Same thing happened with me and to find the exact cause and the solution for it took a lot of time and interestingly and amazed feeling why it is happening so,
For Demo let’s compile the following code,
Case 1: Error :An internal build error has occurred. Right-click for more information
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="init()">
<mx:Script>
<![CDATA[
private function init():void{
var type:String;
switch(type) {
/* case "test":
break; */
}
}
]]>
</mx:Script>
<mx:Label text="Blank Switch"/>
</mx:Application>
While Compiling we get the Compilation error as “An internal build error has occurred. Right-click for more information.” No line number in error and we start scratching our head. But solution is simple just remove the switch block and application will get compiled again and we can move on with coding.
Case 2: Error : Classes must not be nested.
Replace the init() method and compile the code we get the error Classes must not be nested. same problem here but at least this time we will get the error at function call so it is bit easier to track
privatefunction init():void {
var type:String;
switch(type) {
case“hi”:
//var i:int = i+1;
break;
}
}
]]>
solution is simple just remove the switch block and application will get compiled again and we can move on with coding.
Same Problem is been discussed here as common problem but some times it becomes hard to find it so.
Case 3: 1047: Parameter initializer unknown or is not a compile-time constant.
Possible Solutions:
Checking the constant at function argument,Constructor is one of the big cause of such error,
like
package
{
public class Test {
//Constants is Class
//public class Constant{ public static const LOGINNAME:String=”test” }
public function Test(s:Sting=Constants.LOGINNAME){
}//Function test Ends Here
}//Class Ends Here
}
Solution: Here if we replace s:Sting=Constants.LOGINNAME by s:Sting=”test” Error is resolved
1047: Parameter initializer unknown or is not a compile-time constant. Error will be solved. Note that for error to display we must instatiate the Test class
Some other reasons :
Missing semicolon in Anycode where you have defined constants and Forgot to enter the Semicolon.
Especially if you use ArrayCollection in Constant you mest give a semicolon or else be ready for Unexpeted error.
See if Server is in restart mode then some times project doesnot get cleaned up properly and deployed properly so check Server status as “Started” and clean project it will do for you.
Before Reading this documentation. Its been a simple effort by me to share the information whatever i have with all of the world through internet. So whatever written is all what i had understood from the FlexUnit Framework it may have some mistakes so sorry for those. But Please do inform me if you find something wrong with it ,so that this can be of great help to everybody who navigates to this page.
This is the First big document which i have made and published so Please do comment if you think you can help me or give me a some suggestions.
Thanks in Advance.
Some Definitions
Code coverage : Code coverage is a measure used in software testing. It describes the degree to which the source code of a program has been tested. It is a form of testing that inspects the code directly and is therefore a form of white box testing (Testing done only on internal specification).
Test harness or automated test framework : It is a collection of software and test data configured to test a program unit by running it under varying conditions and monitoring its behavior and outputs.
The typical objectives of a test harness are to:
Ø Automate the testing process.
Ø Execute test suites of test cases.
Ø Generate associated test reports.
A test harness typically provides the following benefits:
Ø Increased productivity due to automation of the testing process.
Ø Increased quality of software components and application.
Regression : Regressions occur whenever software functionality that was previously working correctly stops working as intended. Typically regressions occur as an unintended consequence of program changes.
Test Case : A test case in software engineering is a set of conditions or variables under which a tester will determine whether a application meets specifications. Test cases are often referred to as test scripts, particularly when written. Written test cases are usually collected into test suites.
Test Oracle : The mechanism for determining whether a software program or system has passed or failed a test . In some settings an oracle could be a use case or Requirement. It may take many test cases to determine that a software program or system is functioning correctly.
Mock objects : mock objects are simulated objects that mimic the behavior of real objects in controlled ways. In a unit test, mock objects can simulate the behavior of complex, real (non-mock) objects and are therefore useful when a real object is impractical or impossible to incorporate into a unit test.
Feature creep : It is the proliferation of features in a product where extra features go beyond the basic function of the product and so can result in over-complication rather than simple, elegant design.
Unit testing
What is Unit and Unit testing?
Unit testing is a method of testing that verifies the individual units of source code are working properly. A unit is the smallest testable part of an application. In Flex, this means a function, or more appropriately a method as Flex/ActionScript is an object oriented language.
Unlike many other forms of software testing, unit tests are usually completed by the developer.
The developer tests code at a low level to make sure each method is performing as expected. In theory, if each function is working properly at a low level then the higher levels of integrtion testing should have fewer errors.
Why ?
To ensures that new additions or changes to a project do not introduce bugs or modify expected behavior.
To enables large teams to work in tandem without introducing bugs and confirm that small individual parts of a program, down to specific methods, all return the expected results.
When ?
Before writing a code for any functionality we should pass a unit test for every functionality.
Reasons for Unit Testing
Tests Reduce Bugs in New Features
Tests Are Good Documentation
Tests Reduce the Cost of Change
Tests Improve Design
Tests Allow Refactoring
Tests Defend Against Other Programmers to make unwanted changes
Testing Forces You to Slow Down and Think which gives clean and simple design
Tests Reduce Fear of worrying about breaking existing code as you add new features.
FlexUnit
“FlexUnit is an open source framework created by Adobe for unit testing in Flex”
The FlexUnit Framework allows you to create test cases and synchronous tests and evaluate test suites in a test harness application that provides a visual display of all the tests in that test suite.
The visual display has a very clear Representation for
Number of Tests Run, Time Taken to Run Tests, Average assertions made per Test, Number of Errors, Failures and so on
It has Filter Option for results and Search functionality
Table View representation where we can check Result, Assrtion , expected and Actual
We can Handle Events and Test Visual Components with FlexUnit
How to include FlexUnit ?
FlexUnit is available for download on Google Code at http://code.google.com/p/as3flexunitlib/.After you extract the file from the zip, you will find a flexunit.swc in the bin directory. You need to add this library to your project
Important API
TestRunnerBase() : TestRunnerBase is the default graphical test runner included with the FlexUnit Framework.
Property : test ( To Add the Suite ) , startTest and
Event : TestCompleteEvent
TestSuite : TestSuite to hold the collection of tests to be run.
TestCase –It defines the fixture in which to run multiple tests it inherits Assert class which provides all types of assertions(Assuptions).
Assertion Types
assertEquals – Asserts that 2 values are equal.
assertFalse – Asserts that a condition is false The first argument can be the message when the assertion fails.
assertMatch – Asserts that a string matches a regexp.
assertNoMatch – Asserts that a string doesn’t match a regexp.
assertNotNull – Asserts that an object is not null.
assertNotUndefined – Asserts that an object is not undefined.
assertNull – Asserts that an object is null.
assertStrictlyEquals – Asserts that two objects are strickly identical The first argument can be the message when the assertion fails Assert
assertTrue – Asserts that a condition is true The first argument can be the message when the assertion fails Assert
assertUndefined – Asserts that an object is undefined.
Steps in Writing the TestCases
Write a single test
Implement just enough code to get the test to compile
Run the test and see it fail
Implement just enough code to get the test to pass
Run the test and see it pass
Refactor for clarity
Repeat
Unit Testing Example
Problem :We have to make functionality of checking an opening Balance for Account. If Account is of Type saving , then the Opening balance will be 1000 and if it is of type Current Account then opening balance is 5000.
FlexUnit is available for download on Google Code at http://code.google.com/p/as3flexunitlib/. After you extract the file from the zip, you will find a flexunit.swc in the bin directory.
Now lets start a TDD process
Create a project say TDD
flexunit.swc add this library to your project
In src Create Two Folders as testCases and utils
Our Application level file will be TDD .mxml
Step 1 :
In TDD.mxml Create an Object of TestRunnerBase Class Give it name as “testRunner” Code will look like this
//Assigns a testSuite to the TestRunnerBase which we will start executing
//Called from CreationComplete Event of Application
privatefunction onCreationComplete():void
{
testRunner.test = createSuite();
testRunner.startTest();
}
privatefunction createSuite():TestSuite{
var testSuite:TestSuite = new TestSuite();
return testSuite;
}
Step 2 :
Create a class AccountManagerTest Extends TestCase within the package testCases.Write a method “testOpeningBalance” where We will write a test cases for
/**
* Account types are
* s – Saving Account with minBalance = 500;
* c – Current Account with minBalance = 1000;
*
*/
publicfunction testOpeningBalance():void
{
}
Step 3 :
Create a class AccountManager.
Write a two methods
openAccount() – It will create a account with given type with required respective opening balance.
getMinBalance() – It will return the balance of the particular Instance which we will test in our test case method testOpeningBalance method of AccountManagerTest.
The Code should look like :
privatevar balance:int = 0;
privatevar _type:String;
publicfunction openAccount(type:String):void
{
_type = type.toLowerCase();
}
publicfunction getMinBalance():Number{
return balance;
}
Step 4 :
Add the Tests to the testOpeningBalance method of AccountManagerTest class as
publicfunction testOpeningBalance():void
{
var validatedeposite:AccountManager = new AccountManager();
validatedeposite.openAccount(“S”);
assertEquals(“Balance after Opening Saving Account is 1000″, 1000, validatedeposite.getMinBalance());
validatedeposite.openAccount(“C”);
assertEquals(“Balance after Opening Current Account is 5000″, 5000, validatedeposite.getMinBalance());
}
Now Run The Project see that the Test Case Fails
Step 5 :
Now implement just enough code so that the testCase Passes.
For this rewrite the method openAccount() in AccountManager class so that the testCase passes.
The Code looks like this,
publicfunction openAccount(type:String):void
{
_type = type.toLowerCase();
if(_type==’s’)
{
balance = 1000;
}elseif(_type==‘c’)
{
balance = 5000;
}
}
Run the Project again Test Case Passes
Now I guess You are Rocking with Flex Unit Hurrey.
Adding Tool Tips to Datagrid and Combobox Guess How Can we do it ,,, Dont Worry we have solution just check this just add the property itemRenderer=”mx.controls.Label” and Your Done
<?xml version=”1.0″ encoding=”utf-8″?>
<!– Adding Tooltips to Data grid and Combobox –>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”vertical”
verticalAlign=”middle”
backgroundColor=”white”>
<mx:XML id=”cmbDP”>
<nodes>
<node Alphabets=”Akola”/>
<node Alphabets=”Buldhana”/>
<node Alphabets=”Chikhli”/>
<node Alphabets=”Dhule”/>
<node Alphabets=”Elora”/>
</nodes>
</mx:XML>
<mx:XML id=”dataGridDP”>
<nodes>
<node Alphabets=”A” A-ZString=”The quick brown fox jumped over the lazy dog” />
<node Alphabets=”B” A-ZString=”The quick brown fox jumped over the lazy dog” />
<node Alphabets=”C” A-ZString=”The quick brown fox jumped over the lazy dog” />
<node Alphabets=”D” A-ZString=”The quick brown fox jumped over the lazy dog” />
<node Alphabets=”E” A-ZString=”The quick brown fox jumped over the lazy dog” />
</nodes>
</mx:XML>
<mx:DataGrid id=”dataGrid”
dataProvider=”{dataGridDP.node}”
width=”300″
height=”200″>
<mx:columns>
<mx:DataGridColumn dataField=”@Alphabets” itemRenderer=”mx.controls.Label”
headerText=”Alphabets”
headerRenderer=”mx.controls.Label” />
<mx:DataGridColumn dataField=”@A-ZString” itemRenderer=”mx.controls.Label”
headerText=”Lines Containing the A-Z Alphabets Check it”
headerRenderer=”mx.controls.Label” >
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
<mx:ComboBox id=”cmb” width=”60″ toolTip=”{cmb.selectedLabel}” labelField=”@Alphabets” dataProvider=”{cmbDP.node}” itemRenderer=”mx.controls.Label”/>
</mx:Application>
We all know Array and Arraycollection provides the facilities of doing sort in themselves but some times there are needs to search the Array/Arraycollection depending on the entered search term. So that is something which we need to implement. So here is the simple logic to search the item in the Array/Arraycollection
FullScreen Application in Flex,, Yup sounds very interesting…
It has been one of our project requirement , I did it quite long days ago, So I thought why not put this thing here on blog so if somebody faces any problem with it he can use this code … Why Not?
Before proceedingas you makes your new project goto your HTML wrapper i.e.
index.template.html . Now
Step 1.
In the script section add comman (,) in last property ofAC_FL_RunContent function and add the line
“allowFullScreen”, “true”
Also in <object> tag add
<param name=”allowFullScreen” value=”true” />
Property so that we can avoid upcoming Security error.
private var arrList:ArrayCollection = new ArrayCollection([{Label:'Central Beer',Path:'assets/get_video1111.flv'},{Label:'Clinton',Path:'assets/Clinton.flv'},{Label:'Banned Ad',Path:'assets/bannedAd.flv'},{Label:'Love',Path:'assets/get_video.flv'},{Label:'Darling',Path:'assets/get_video2.flv'},{Label:'Just Call US',Path:'assets/get_video3.flv'}])
We all know that to make use of browse window facility, Flex provides inbuilt class ‘FileReference’ which has method named “browse”, Which allows us to open the File Browsing window.
To restrict the Browsing window to open some limited file extensions(Such as .mp3,.mp4 file only), we make use of FileFilter class which holds the fileFilter to be applied to the browsing window
eg.
private var allFileFilter:FileFilter = new FileFilter(“All, *.mp3; *.mp4; *.flv; *.wmv; *.mpeg; *.mpg;”, “*.mp3; *.mp4; *.flv; *.wmv; *.mpeg; *.mpg; “);
private var fileRef:FileReference = new FileReference();
fileRef.browse([allFileFilter]) ;
But this File filter validation can be broken easily to Upload wrong files, For this just type *.* and press enter , Here you see all files available for upload Now select Any Invalid file and go with upload.
So in such cases we need to apply self made file extesion validation logic which should be able to verify the extension of the file to be uploaded.
So here is short and sweet sample code to workout this logic,
/**
* Standard File extensions allowed to be Uploaded
*/
private var fileTypeArray:Array = ["mp3","mp4","flv","wmv","mpeg","mpg","rtf","doc","txt"];
/**
* Selected file type,Selected from Browsing window
*/
private var fileType:String;
/**
* FileReference class object provides browsing and uploading methods
*/
private var fileRef:FileReference = new FileReference();
/**
* File Filters Applied for restriction of Files to be browsed
*/
//FileFilter takes two Arguments 1. Description to be shown in Browse window. 2. List of Extensions
private var allFileFilter:FileFilter = new FileFilter(“All, *.mp3; *.mp4; *.flv; *.wmv; *.mpeg; *.mpg;”, “*.mp3; *.mp4; *.flv; *.wmv; *.mpeg; *.mpg; “);
private var videoFilter:FileFilter = new FileFilter(“Video, *.flv; *.wmv; *.mpeg; *.mpg;”, “*.flv; *.wmv; *.mpeg; *.mpg;”);
private var audioFilter:FileFilter = new FileFilter(“Audio, *.mp3; *.mp4; *.wma;”, “*.mp3; *.mp4; *.wma;”);
private var textFilter:FileFilter = new FileFilter(“Test, *.rtf; *.doc; *.txt;”, “*.rtf; *.doc; *.txt;”);
/**
* Function for validating the correct file extension.
*/
private function validateFileType(fileName:String):Boolean
{
txtErr.text = ”;
txtFileName.text = ”;
fileName = StringUtil.trim(fileName.toLowerCase());
var fileExtensionArray:Array = fileName.split(“.”);
if(fileExtensionArray.length>1)
{
fileType= fileExtensionArray[fileExtensionArray.length-1];
for(var i:int =0;i<fileTypeArray.length;i++)
{
if(fileType==fileTypeArray[i])
{
txtErr.text = ” File Selected is of proper Extension, Thank You.”;
txtFileName.text=” Uploaded File Name is =>” + fileRef.name +
”\n Size is => “+fileRef.size+” bytes”
”\n Creation Date is => “+ fileRef.creationDate +
”\n Creator is => “+ fileRef.creator ;
return true;
}
}
}
txtErr.text = “You have not Uploaded the file within the standerd extensions provided.”;
return false;
}
/**
* Function Used to open the Browsing window
*/
private function selectFile():void
{
fileRef = new FileReference();
//browse method excepts the filefilter array as an arguement
fileRef.browse([allFileFilter,audioFilter,videoFilter,textFilter]);
fileRef.addEventListener(Event.SELECT, onSelectFile);
}
/**
* Function used to catch the Select event
*/
private function onSelectFile(event:Event):void
{
validateFileType(fileRef.name);
}
]]>
</mx:Script>
<mx:Button x=”63″ y=”86″ label=”Browse” click=”selectFile()”/>
<mx:TextArea id=”txtFileName” editable=”false” x=”161″ y=”114″ width=”360″ height=”97″/>
<mx:Text color=”#ffffff” selectable=”false” id=”txtErr” x=”161″ y=”63″ width=”397″ height=”25″/>
<mx:Label x=”143″ y=”47″ selectable=”false” text=”Enter *.* in file name of browsing window to Select wrong file.” fontWeight=”bold” fontSize=”15″/>
<mx:Label x=”161″ y=”86″ selectable=”false” text=”Retrived Local File Information => “/>
<mx:Label x=”161″ y=”256″ selectable=”false” text=”Validate wheather the selected file is valid or Not.”/>
</mx:Application>
Hi,
Changing the layout of container dynamically at runtime is one of the problem we all regularly meet with.
Suppose we are using the controlls in the HBox where all childrens are lined up horizontally and suddenly at runtime we need to place the children vertically and on some conditions we need to place all the childrens horizontally then it becomes impossible to do it with HBox
So to come up with such solution it is always easier to do it with container ‘Box’ which is actually the parent container for VBox and HBox.
With Box Container childrens are by default arranged vertically.
With the “direction” property of Box we can change its layout dynamically.
Hmm Sometimes it didnt work then try it by removing the Height and width of of that container
Following is the small Sample to workout this challege
private var prefixArray:ArrayCollection = new ArrayCollection([{Item:'Select'},{Item:'Tel'},{Item:'Mob'},{Item:'Fax'},{Item:'Freephone'},{Item:'24 Hour'},{Item:'Sales'},{Item:'Service'},{Item:'Reservations'},{Item:'Emergency'},{Item:'Textphone'}]);
private function initCombo():void
{
bx.direction=”horizontal”;
}
Recently, I was having a requirement to develop the Flex Log management functionality. After doing lots of research and investing a time for 3 to four days I successfully managed the things to achieve the flex logging Mechanism which can log Line Number, Function Name, Class name into log File. After delivering the functionality I was [...]
This is another chapter to the amazing errors, which does not leave behind any signals how to solve it, and more interestingly what is the exact reason for it. When we have a pretty large code base where many developers check in and check out the code regularly, it is very hard to find the exact [...]
After making Flex SDK open source ADOBE have bounce back again for Unemployeed Developers with Free Flex builder 3. Its really a great initiative by ADOBE to cache in the opportunity for spreding the Flex among the common masses. Link to Flex Builder version for UnEmployeed professionals : https://freeriatools.adobe.com/learnflex/ Link to Flex Builder versi […]
Before Reading this documentation. Its been a simple effort by me to share the information whatever i have with all of the world through internet. So whatever written is all what i had understood from the FlexUnit Framework it may have some mistakes so sorry for those. But Please do inform me if you find [...]
Adding Tool Tips to Datagrid and Combobox Guess How Can we do it ,,, Dont Worry we have solution just check this just add the property itemRenderer=”mx.controls.Label” and Your Done
Searching Within the Array We all know Array and Arraycollection provides the facilities of doing sort in themselves but some times there are needs to search the Array/Arraycollection depending on the entered search term. So that is something which we need to implement. So here is the simple logic to search the item in the Array/Arraycollection
Hi, Probably Hyperlinking is one of the most commonly seen thing to navigate to other page. But to write this post here i thanks to one of mine Orkut friends querry. For such querries i am always welcome.. So lets get on with example The label, text, and textarea controls can dispatch a link event when the user selects [...]
Hello All, FullScreen Application in Flex,, Yup sounds very interesting… It has been one of our project requirement , I did it quite long days ago, So I thought why not put this thing here on blog so if somebody faces any problem with it he can use this code … Why Not? Before proceeding as you makes [...]
Hi, We all know that to make use of browse window facility, Flex provides inbuilt class ‘FileReference’ which has method named “browse”, Which allows us to open the File Browsing window. To restrict the Browsing window to open some limited file extensions(Such as .mp3,.mp4 file only), we make use of FileFilter class which holds the f […]
Hi, Changing the layout of container dynamically at runtime is one of the problem we all regularly meet with. Suppose we are using the controlls in the HBox where all childrens are lined up horizontally and suddenly at runtime we need to place the children vertically and on some conditions we need to place all the [...]
Recent Comments