Saturday, September 18, 2010

Adobe FlexPMD & FlexCPD

Overview:

FlexPMD is a tool that helps to improve code quality by auditing any AS3/Flex source directory and detecting common bad practices, such as:Unused code (functions, variables, constants, etc.)
  • Inefficient code (misuse of dynamic filters, heavy constructors, etc.)
  • Over-complex code (nested loops, too many conditionals, etc.)
  • Over-long code (classes, methods, etc.)
  • Incorrect use of the Flex component lifecycle (commitProperties, etc.)
The FlexPMD report is produced describing the violations of a given rule set. FlexPMD includes a rule set that is broad ranging and continually growing. It is also straightforward to create new rules.

FlexCPD is reusing the JavaCPD engine. This project consists in giving a stream of tokens to the CPD engine using the FlexPMD lexer and let the CPD engine detects duplications in those streams.

Flex Builder IDE PMD Plug-in Configuration:


Download the Eclipse PMD plug-in jar file from below URL and paste into the Flex Builder IDE plugins folder (c:\Program Files\Adobe\Flex Builder 3\plugins) and restart the Flex Builder.

URL: http://opensource.adobe.com/svn/opensource/flexpmd/plugin/trunk/flex-pmd-eclipse-plugin-site/plugins/

Check the FlexPMD plug-in is successfully configured into Flex Builder, through clicking the Window->Preferences->FlexPMD (While clicking the FlexPMD option, show’s configuration fields )

FlexPMD Configuration:

Download the FlexPMD librarys from the following link:

URL:http://opensource.adobe.com/wiki/display/flexpmd/Downloads

Note: Try to download the FlexPMD Zip file from the column (All-in-one-bundle) zip file.

Extract the downloaded zip file into available local drive (Ex: C:\PMD\flex-pmd-all-in-one-bundle-1.1.zip) and extract it. This All-in-One-Bundle contains all supporting jars (Flex PMD, CPD, Rule set, and Code Metrics).

Open the Flex Builder IDE; Click Menu Window->Preferences->FlexPMD

Able to see the below fields, that needs to configure with downloaded PMD Zip (flex-pmd-all-in-one-bundle-1.1.zip) file.

  • FlexPMD Command line Installation: Click Browse and open the extracted folder (C:\PMD\flex-pmd-all-in-one-bundle-1.1\) and select the flex-pmd-command-line-1.1.jar.
  • FlexPMD custom Ruleset: This field is optional, if any customized Rule set (RuleSet.xml) is defined, we can configure the file path (C:\PMD\customRuleSet.xml) or if it’s blank, the Adobe Flex default Ruleset will be configured automatically.
  • Java Command Line: No need to configure, Predefined one.
  • FlexCPD Command line Installation: Click Browse and open the extracted folder (C:\PMD\flex-pmd-all-in-one-bundle-1.1\) and select the flex-pmd-cpd-command-line-1.1.jar.
  • Minimum tokens: No need to configure, Predefined one.

Steps to FlexPMD Execution:

Right-click any Flex Project & Select the FlexPMD, It shows four sub menus listed below:
  • Run FlexPMD – It executes the FlexPMD process and lists the errors in the Flex PMD View.
  • Find suspect cut & paste – It executes the FlexCPD process and lists the errors in the CPD View.
  • Clean FlexPMD markers – It removes the FlexPMD markers (PMD Error & Warning icons) from the source code.
  • Add/Remove FlexPMD Nature – It enable/disable the FlexPMD Nature option. If it’s enabled to our project, while compiling itself, shows the PMD errors (No need to run the FlexPMD separately). As the same, having an option to disable the PMD Nature.
Note: Able to execute the FlexPMD for whole project or package or single file through right-click -> FlexPMD-> Run FlexPMD option.

Creating Custom Rule Set:

Adobe Flex provides a separate link to create a custom Ruleset.

URL: http://opensource.adobe.com/svn/opensource/flexpmd/bin/flex-pmd-ruleset-creator.html

Note: Having an option to generate the FlexPMD Ruleset as xml file in the above URL.

Trouble Shooting Section:

FlexPMD has some issues, So at the time of configuration, Please make sure on below areas.

a. Avoid spaces in the following items:
  • Flex Project Name (Eg: CSPortal)
  • Project workspace name & Path (Eg: C:\flexworkspace)
  • Flex PMD extracted workspace (Eg: C:\PMD\flex-pmd-all-in-one-bundle-1.1)
Note: It’s Adobe Issue (Bug no: FLEXPMD-127)

b. If FlexPMD view is not generated. Please follow the below steps to find issue type.

  • Open the Flex Builder in DEBUG mode (Type “FlexBuilder –debug” in command prompt ( Eg: C:\Program Files\Adobe\Flex Builder 3\ ).
  • Run the FlexPMD by selecting the Project/Package/file. If any configuration issues or errors, it may listed in the IDE debug console.

Friday, September 11, 2009

CHECKING NETWORK & INTERNET LIVE OR NOT in AIR


NETWORK EVENT:

Using the NETWORK_CHANGE event, Add this listener in the applications - creationComplete property.

NativeApplication.nativeApplication.addEventListener(Event.NETWORK_CHANGE, onNetworkChangeHandler);

private function onNetworkChangeHandler(event:Event):void
{
Alert.show("Network Event Triggered");
}

Check the above scenario by disabling & enabling the Network connections manually in start->settings->Network Connections.


IS INTERNET LIVE OR NOT:

Using the URLMonitor class, The defined URL is monitored , If the network is failed , The event dispatches the status using the urlMonitor.available property.Refer the below code:

private var urlMonitor:URLMonitor;

private function checkNetworkLive():void
{
var url:URLRequest
= new URLRequest("http://www.google.com/");
url.method = "HEAD";
urlMonitor = new URLMonitor(url);
urlMonitor.pollInterval = 3000;
urlMonitor.addEventListener(StatusEvent.STATUS,statusChanged);
urlMonitor.start();
}

public function statusChanged(event:StatusEvent):void
{
if(urlMonitor.available)
{
Alert.show("InterNet Live");
}
else
{
Alert.show("InterNet Failed");
}
}

PDF FILE LOADER IN AIR


You can add a PDF to an AIR application by creating an HTMLLoader instance, setting its dimensions, and loading the path of a PDF.The following example loads a PDF from an external site. Replace the URLRequest with the path to an available external PDF.

import mx.core.Application;

public function loadPdfUI(path:String):void
{
if(hasAdobeReader())
{
var htmlloader:HTMLLoader = HTMLLoader.createRootWindow(true);
htmlloader.window.document.title="PDF CONTAINER - "+path;
htmlloader.window.document.width = Application.application.width;
htmlloader.window.document.height = Application.application.height;
var url:URLRequest=new URLRequest(decodeURIComponent(path));
htmlloader.x = 0; htmlloader.y = 0;
htmlloader.load(url);
}
}

private function hasAdobeReader():Boolean
{
return (HTMLLoader.pdfCapability == HTMLPDFCapability.STATUS_OK) ? true : false;
}

The hasAdobeReader() method is used to detect the Adobe Reader is in the system.

Thursday, August 27, 2009

Flex Unit Framework Testing



Intro:
FlexUnit is an open source framework created by Adobe for unit testing in Flex. It is based on the widely used JUnit testing framework for Java. FlexUnit provides a low level automated testing system that is your first line of defense for catching bugs in your application.

What is Unit testing?
To understand unit testing, you must first understand what a “unit” is. A unit is the smallest piece of code that is testable. This doesn’t mean each line of code, but a piece of code that performs a specific task. In Flex, this means a function, or more appropriately a method since Flex/ActionScript is an object oriented language.

Steps to build FlexUnit Sample:
  1. Open the new project in Flex Builder (LoginSample.mxml).

  2. Write the sample code (login functionality - Components in separate mxml file & method should be in script file).

  3. Copy the FlexUnit.swc to lib folder.

  4. Create a new mxml application file (in the same project folder -loginTestSuite.mxml).
  5. Create a new script file to write a test case for unit testing.

  6. Run the loginTestSuite.mxml for unit testing, If any errors the UI listed the line number.

Create a Test Case :

Open the script file LoginAccountTest.as and Our unit tests will be contained in a new class file (LoginAccountTest.as) that extends the base TestCase class. This class will contain methods with our unit tests in them. Typically need to create a new method for each unit . In this case we testing the login methods of the user. so my test class method names will be testLoginComponent(). The method names for our test methods must start with the word test. Later on when we add the unit tests to the test suite it automatically looks for method names that begin with the word test. If your method names do not begin with the word test they will not be run.
Ex:

  • testLoginComponent()

  • testHttpConnection()

  • testConnectionFail()

A unit test is made up of logical assertions. If an assertion is true, the unit test passes. If an assertion is false then the unit test fails.There are several assertion methods like :

  • assertTrue
  • assertFalse
  • assertNull
  • assertEquals.

Ex:

  • assertTrue("Login Status ", loginScript.getdetailsLogin() == true );

  • assertEquals("Username is FlexUnit", "FlexUnit" ,loginScript.getUsername());

The below displayed is the test case class file, refered from the TestSuite Component.

LoginAccountTest.as


/** * Test Login functionality */

public function testLoginComponent():void{

var loginScript:scripts = new scripts();

loginScript.checkLoginData("FlexUnit", "FlexCoder");

assertTrue("Login Check ", loginScript.getdetailsLogin() == true );

}


/** * Test Username functionality */

public function testUserName():void {

var loginScript:scripts = new scripts();

loginScript.checkLoginData("FlexUnit", "FlexCoder");

assertEquals("Username is FlexUnit", "FlexUnit" ,loginScript.getUsername());

}

Calling the Test Cases:
Create a simple Flex application (loginTestSuite.mxml) which only has one component, TestRunnerBase, which is part of the FlexUnit library. Make sure you include the flexunit name space flexunit.flexui.* in the application tag, so you can access the GUI components from the library. Next we must add functions to set up the test suite and start the testing. We create a createSuite() method to create a new TestSuite object and adds all of our TestCase classes to it using the addTestSuite() method. The addTestSuite() method uses reflection to find all the methods in the class that start with the name test and adds them to list of tests to run. We only have one TestCase class (the LoginAccountTest.as we created in the loginmodel folder). Finally we create an onCreationCompleteHandler() method that is called on the creationComplete event of our TestSuite application. This function sets the unit test property of the TestRunnerBase object to our test suite that is returned by the createSuite() method. Now we start the testing by calling the startTest() method on the TestRunnerBase component.

The code should look like:

Component:

Methods:


/**
* onCreationCompleteHandler - To start the Test Suite UI and Testing
*/
public function onCreationCompleteHandler():void
{
testRunnerComp.test = createTestSuite();
testRunnerComp.startTest();
}


/**
* createTestSuite - To start the Unit Testing by calling the LoginAccountTest.as file
*/
public function createTestSuite():TestSuite
{
var testSuite:TestSuite = new TestSuite();
testSuite.addTestSuite(LoginAccountTest);
return testSuite ;
}

Saturday, July 11, 2009

Image smoothing in Flex

The Smoothing is a nice feature for removing jaggies from images that have been scaled either up or down.

The goal is to provide an image component thats quick and easy to use, and takes care of turning the smoothing property on after the image has loaded. This is helpful if you have an image that you want to look the best it can at different sizes through zooming in and out.

Please look the following codes:

mx:Image id="imageComp" source="favoritesBtnDown.png" x="326.5" y="156" complete="smoothing(event)"

public function smoothing(e:Event):void
{
var bitmapAsst:Bitmap = e.target.content as Bitmap ;
bitmapAsst.smoothing = true ;
}

The image smoothing process is done in Image Component's complete event.

Monday, December 29, 2008

Monitoring System Idle State in AIR


Please look this code:

NativeApplication.nativeApplication.idleThreshold = 120;

NativeApplication.nativeApplication.addEventListener(Event.USER_IDLE, idlefunction(event:Event) {trace("Idle");} );

NativeApplication.nativeApplication.addEventListener(Event.USER_PRESENT, presentfunction(event:Event) { trace("Present");} );


Note:
Using the idleThreshold property, the specified interval( in seconds) are set, The system is reaching the idle state, upto specified seconds, Event.USER_IDLE is fired and any interrupt to the system (keyboard, mouse or input devices) is done, Event.USER_PRESENT is fired. Its very helpful to screen saver samples.

Finding Screen Resolutions in AIR

Using the capabilities , we can find the current screen resolutions ,As per the simple code, listed below :


desktopWidth = Capabilities.screenResolutionX;


desktopheight = Capabilities.screenResolutionY;




The screenResolutionX is defines the screen width and screenResolutionY is defines the screen height.