RSS

Author Archives: shashankkulkarni

About shashankkulkarni

@Flex ,Fully loaded. Internet surfer, blogger.Post graduate from India

Unrecognized Windows Sockets error: 0: JVM_Bind Flex, the workaround

Ohoooo , Its again the unsolved one, Sadly a page to Flex(Amazing Errors).

Its been happening with Flex Builder on my  machine mostly when i tried to do the debug of my code and it simply  stops my working (i.e. it only disables my debugging functionality) , sometimes till i restart my machine.

Error I am getting: ” Unrecognized Windows Sockets error: 0: JVM_Bind “

My Environment Details is :

Windows 7

Flex Builder (Eclipse Plug-in ) ( Flex Builder 3)

JBoss server running inside the Flex Builder environment

Workarounds i tried most of the time are :

  • Switching the Server mode to debug, sometimes help.
  • Closing all the Java instances apart from my Flex Builder sometimes helps.

If both of above does not work , Solution is “Leave with the Pain of debugger functionality unavailability”

But to me the query is that what the hell is happening with my Flex Builder?

Adobe forums are with no help about this topic, with the two query seems to be unresolved on the forums. I haven’t found any definite solution on it. If u have one please don’t forget to comment it, It will be great help

http://forums.adobe.com/message/15429

http://forums.adobe.com/thread/682171

It certainly is not the happy coding way with the above scenario, I really feel Adobe needs to address this one.

Any links, comments or suggestions  are highly welcomed

Best Luck.

Thanks and regards,

Shashank Kulkarni

Feel free to comment on the post :)

 
1 Comment

Posted by on August 21, 2010 in Flex(Amazing Errors)

 

Validating if the url exists or not on Client side with FLEX

Yup, Quite interesting isn’t it ?

Mission: Validate URL Existance on client side.

Expected Result: Anyhow create POC of a code with the efforts to check the possibility of verifying URL existence from Flex i.e. from client side only.

Result: . I think i managed to crack it with a simple solution, When code not deployed works very smooth and gives result as expected.

On Local Environment Without server deployment of code

Result is great !

But at last Buck Stops at “Security Sandbox Error” when we deployed it on to the server.

Path Followed:

Knowing flash.net package : The flash.net package contains classes for sending and receiving from the network, such as URL downloading and Flash Remoting.

http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/net/package-detail.html

Understand HTTP response status meanings

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

With Some 2-3 days reading i just went on to build one example with URL existence verification application.

If Somebody is intrested to solve this puzzle, take the below code.

Project Hierarchy:

src-assets-HttpCodes.xml

src-ValidateURL.mxml

Lets Walk Through the code, I am sure the written code is pretty simple to understand so wont be elaborating it.

Code for “ValidateURL.mxml


<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:net="flash.net.*"
layout="absolute"
creationComplete="httpIOError.send();">

<mx:Script>
<![CDATA[

import mx.controls.Alert;
import mx.utils.ObjectUtil;
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import flash.net.*;

private var httpCode:int;

private var errorCodesAC:ArrayCollection = new ArrayCollection();

private function loadURL():void
{
var urlReq:URLRequest = new URLRequest('http://'+ urlString.text);
urlStream.load(urlReq);
}

private function checkUrl(e:HTTPStatusEvent):void
{
httpCode=e.status;
}

private function ioErrorHandler(e:IOErrorEvent):void
{
for(var i:int=0;i<errorCodesAC.length;i++)
{
if(httpCode==errorCodesAC[i].number)
{
responseText.text = "Status Code: "+httpCode.toString() + "\nError Details: \n"+errorCodesAC[i].details;
}
}
}

private function returnSuccess(e:Event):void
{
responseText.text = "Status Code: "+httpCode.toString() + "\nURL is valid."
}

private function securityErrorHandler(e:SecurityErrorEvent):void
{
Alert.show(ObjectUtil.toString(e),"Security Error Details");
}

private function faultHandler(e:FaultEvent):void
{
Alert.show(ObjectUtil.toString(e));
}

private function resultHandler(e:ResultEvent):void
{
errorCodesAC = e.result.HttpStatus.statusCodes.statusCode
}

]]>
</mx:Script>

<mx:HTTPService id="httpIOError" url="assets/HttpCodes.xml" result="resultHandler(event)" fault="faultHandler(event)"/>

<net:URLStream  id="urlStream"  complete="returnSuccess(event)" httpStatus="checkUrl(event)"
ioError="ioErrorHandler(event)" securityError="securityErrorHandler(event)" />

<mx:Label x="135" y="30" text="Enter Url to be validated:"/>
<mx:Button x="321" y="84" label="Check URL" click="loadURL()"/>
<mx:TextInput id="urlString"  x="288" y="28"/>
<mx:Text x="288" y="58" text="eg: www.shashankkulkarni.wordpress.com"/>
<mx:TextArea  id="responseText" x="135" y="133" height="93" width="414" editable="false" wordWrap="true"/>
<mx:Label x="135" y="107" text="Response Description:"/>
</mx:Application>

 “HttpCodes.xml” is as below


<HttpStatus>

<statusCodes>

<statusCode number="400">
<details>
Unable to understand request.[Bad Request]
</details>
</statusCode>

<statusCode number="401">
<details>
User authentication required. [Unauthorized Request]
</details>
</statusCode>

<statusCode number="403">
<details>
Server refuses the response. [Forbidden Request]
</details>
</statusCode>

<statusCode number="404">
<details>
Page Not Found. [Page Not Found ]
</details>
</statusCode>

<statusCode number="407">
<details>
Proxy Authentication required. [Proxy Authentication]
</details>
</statusCode>

<statusCode number="408">
<details>
Request failed to reach server within specified time. [Request Timeout]
</details>
</statusCode>

<statusCode number="500">
<details>
Unexpected condition occured. [Internal Server Error]
</details>
</statusCode>

<statusCode number="501">
<details>
Functionality required is not supported. [Functionality not supported]
</details>
</statusCode>

<statusCode number="502">
<details>
Invalid response received by server. [Bad Gateway]
</details>
</statusCode>

<statusCode number="503">
<details>
Service is not available temporarily.[Service Unavailable]
</details>
</statusCode>

<statusCode number="504">
<details>
Timely response not received. [Gateway Timeout]
</details>
</statusCode>

<statusCode number="0">
<details>
Input stream is not well Formatted [IOError]
</details>
</statusCode>

<statusCode number="200">
<details>
Yes! This URL exists. [Success]
</details>
</statusCode>

</statusCodes>

</HttpStatus>

I gone through details of Sandbox Security restriction with Flash player ( http://www.adobe.com/devnet/flashplayer/articles/flash_player_9_security.pdf ) but unfortunatly could not solve it to success,  i really feel this should have been done from Flex itself.

I would have been happy to see it working, But I guess some more understanding is needed on my part. I am still finding the missing things.

There must be some way to DO it ???? Still searching the answer, If some body finds it… Just ping it down here. I will be glad to resolve it.

Any suggestions are welcomed.

Best Luck & Happy coding :)

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
 

Could not resolve to a component implementation… Simple solution steps

Just installed Adobe Flash Builder 4 Plug-in to my Eclipse installation at different location but amusingly My Existing Flex 3.4 SDK  stops working after first restart of Eclipse. IT started foul crying “Could not resolve <mx:AdvancedDataGrid> to a component implementation. ”  and I was stuck…..  I restarted my Flex Builder but no Luck ,Then  on doing some Googling I just went to Adobe Site for Flex 3 Release notes at  http://www.adobe.com/support/documentation/en/flex/3/releasenotes_flex3_sdk.html which says,

Using The Data Visualization Components with Flex SDK

“A new version of the data visualization libraries needs to be downloaded and installed into the SDK 3 installation to leverage features such as charts and the Advanced DataGrid”

It just gave me a direction that somehow my Existing Eclipse based Flex 3.4 SDK has lost two library files namely

1. “datavisualization.swc”

Location:  C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.4.0.9271\frameworks\libs

2.  “datavisualization_rb.swc”

Location :

C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.4.0.9271\frameworks\locale\en_US

(Note: Please refer your native installation path)

The library can be downloaded from the main Flex download page:
http://www.adobe.com/products/flex/flexdownloads/

Steps to Resolve:

  1. Goto C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.4.0.9271\frameworks\libs and check for “datavisualization.swc”
  2. Goto

C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.4.0.9271\frameworks\locale\en_US

Check for “datavisualization_rb.swc”

3. Download these from http://www.adobe.com/cfusion/entitlement/index.cfm?e=flex3sdk

Which is located under heading “ ADOBE FLEX 3.5 DATA VISUALIZATION COMPONENTS FOR FLEX BUILDER

Unzip ‘datavisualization_SDK3.5.zip’ which will extract SDK 3 installation

  • datavisualization.swc into the frameworks\libs folder
  • the datavisualization RSL into the frameworks\rsls folder
  • datavisualization_rb.swc into the appropriate frameworks\locale\<locale> folder

Now get those SWC and place to your installation location

If it Still not work try to toggle between SDK s from Project Properties – Flex Compiler option and Restart your installation.

Hope it will work out for you ! If still does not work just drop a comment to resolve

Best Luck & Happy coding :)

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
2 Comments

Posted by on July 16, 2010 in Flex(Amazing Errors)

 

How Clone() method works and Why to Write it?

Small round up to Events basic, I think that is important  :)

As we know “Event” class is used as the base class for the creation of Event objects, which are passed as parameters to event listeners when an event occurs. So to make avail the Event Object and its properties we always extends Event

Basically in Event class(flash.events.Event class) there is one method called as clone()

How clone() method works?
clone() method duplicates an instance of an Event subclass. Returns a new Event object that is a copy of the original instance of the Event object.

Why To write clone() method?

When creating your own custom Event class, we must override the inherited Event.clone() method in order for it to duplicate the properties of your custom class.

What if I don’t override clone() method?

This works fine if implementation doesn’t re-dispatch the event, but as soon as we re-dispatch the event (by calling dispatchEvent(event) in a handler that is handling event), we get a TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@28ef5b1 to events.

Lets Produce the error :)

Main Application Code

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" creationComplete="onCreationComplete()">
	<mx:Script>
		<![CDATA[
			import events.DemoCloneImportance;
			import mx.controls.Alert;
			private function onCreationComplete():void
			{
				demoCloneDispatcher.addEventListener(DemoCloneImportance.CLONE_EVENT,cloneDemoHandler);
				this.addEventListener(DemoCloneImportance.CLONE_EVENT,cloneRedispatchHandler);
			}
			
			private function cloneDemoHandler(event:DemoCloneImportance):void
			{
				Alert.show('In Dispatch Handler');
				this.dispatchEvent(event);		
			}
			
			private function cloneRedispatchHandler(event:DemoCloneImportance):void
			{
				Alert.show('In Redispatcher Handler');
			}
			
		]]>
	</mx:Script>

	<local:CloneInvokerComponent id="demoCloneDispatcher"/>
	
</mx:Application>

Component Class is as follows:


<?xml version="1.0" encoding="utf-8"?>
<!--CloneInvokerComponent.mxml-->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
	<mx:Script>
		<![CDATA[
			import events.DemoCloneImportance;
		]]>
	</mx:Script>
<mx:Metadata>
	[Event(name="CloneEventDemo", type="events.DemoCloneImportance")]
</mx:Metadata>
	<mx:Button label="Dispatch Event" id="btnDispatch" click="dispatchEvent(new DemoCloneImportance(DemoCloneImportance.CLONE_EVENT,true))"/>
</mx:VBox>

Wrong Implementation of Event Class, (Without overriding clone() method )Must avoid it :)

package event
{
import flash.events.Event;

public class DemoCloneImportance extends Event
{
public function DemoCloneImportance(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}

public static const CLONE_EVENT:String = 'CloneEventDemo'		// Override the inherited clone() method.

}

}

Run the Application and we get Runtime error (Visible if Flash Debugger installed)

Now To Resolve it make Custom Event class implementation right :)

package event
{
import flash.events.Event;

public class DemoCloneImportance extends Event
{
public function DemoCloneImportance(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}

public static const CLONE_EVENT:String = 'CloneEventDemo'		// Override the inherited clone() method.

override public function clone():Event {
return new DemoCloneImportance(type, true,false);
}

}

}

This is something very basic but i think most important also :)

Best Luck & Happy coding :)

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
5 Comments

Posted by on March 30, 2010 in Flex(Amazing Errors)

 

Flex application not working without debug version of Flash Player

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.

I am sure this will solve many peoples problem.

Following thread discussed the same problem

http://stackoverflow.com/questions/1137223/flex-app-not-working-without-debug-version-of-flash-player

Another Example how developer suffer due to some mismanaged framework things

http://stackoverflow.com/questions/867788/compile-flex-application-without-debug-optimisation-options-for-flex-compiler

Best Luck & Happy coding :)

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
Leave a comment

Posted by on August 27, 2009 in Flex(Amazing Errors)

 

Tags: , , , , , ,

Compilation Error: An internal build error has occurred. Right-click for more information.

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

private function 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.

http://learn.adobe.com/wiki/display/Flex/Flex+Builder+3+Compiler+Errors

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.

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
4 Comments

Posted by on July 30, 2009 in Flex(Amazing Errors)

 

Tags: , , , ,

Adobe Flex Builder 3 is Free

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.

  1. Link to Flex Builder version  for UnEmployeed professionals : https://freeriatools.adobe.com/learnflex/
  2. Link to Flex Builder version for Student/Institutes/Faculty/Labs : https://freeriatools.adobe.com/flex/
  3. Link to Flex Builder version For 60 Days Trial  For Other : http://www.adobe.com/cfusion/entitlement/index.cfm?e=flex3email

Happy Coding with Flex Builder :)

Thanks and regards

Shashank Kulkarni

Feel free to comment on the post :)

 
1 Comment

Posted by on April 8, 2009 in FLEX

 

Tags: , ,

Unit Testing with FlexUnit

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 probability that regression testing will occur.

Ø 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

  1. Tests Reduce Bugs in New Features
  2. Tests Are Good Documentation
  3. Tests Reduce the Cost of Change
  4. Tests Improve Design
  5. Tests Allow Refactoring
  6. Tests Defend Against Other Programmers to make unwanted changes
  7. Testing Forces You to Slow Down and Think which gives clean and simple design
  8. 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.

Property : addTest , testCount(): getTestMethodNames():

  • 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 :)

  1. Create a project say TDD
  2. flexunit.swc add this library to your project
  3. In src Create Two Folders as testCases and utils
  4. 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

<flexunit:TestRunnerBase width=”100%” height=”100%” />

Write Two Function as

//Assigns a testSuite to the TestRunnerBase which we will start executing

//Called from CreationComplete Event of Application

private function onCreationComplete():void

{

testRunner.test = createSuite();

testRunner.startTest();

}

private function 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;

*

*/

public function 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 :

private var balance:int = 0;

private var _type:String;

public function openAccount(type:String):void

{

_type = type.toLowerCase();

}

public function getMinBalance():Number{

return balance;

}

Step 4 :

Add the Tests to the testOpeningBalance method of AccountManagerTest class as

public function 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,

public function openAccount(type:String):void

{

_type = type.toLowerCase();

if(_type==‘s’)

{

balance = 1000;

}else if(_type==‘c’)

{

balance = 5000;

}

}

Run the Project again Test Case Passes

Now I guess You are Rocking with Flex Unit Hurrey.

Download Links are As Follows

flexUnit Sample Application zipped and renamed

(Download the file and rename .doc by .zip)

All Flex Unit Resources can be found at

http://opensource.adobe.com/wiki/display/flexunit/Developer+Documentation

Say Cheese

Thanks and regards

Shashank Kulkarni.

Feel free to comment on the post :)

Download FlexUnit Presentation

 
4 Comments

Posted by on March 5, 2009 in FLEX

 

Tags: , , , , , ,

Adding ToolTip to Datagrid and Combobox

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>

Best Luck
Thanks and regards

Shashank Kulkarni

Feel free to mail me ) shashank.pawan@gmail.com

 
1 Comment

Posted by on September 27, 2008 in Best of Flex Utillity

 

Tags:

Searching an item within Array, Arraycollection

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

 

<?xml version=”1.0″?>

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” initialize=”initApp()”>

 <!–Shashank Kulkarni–>

 <mx:Script>

 <![CDATA[

  import mx.utils.StringUtil;

  import mx.utils.ObjectUtil;

  import mx.controls.Alert;

 import mx.collections.ArrayCollection;

  private var arr:Array= new Array('Shashank', 'Tushar', 'Ashish','Kailas','Rahul','Pankaj','Shrikant','Amol','pravin');

 [Bindable]

 private var ac:ArrayCollection= new ArrayCollection([{Name:'Shashank'}, {Name:'Tushar'}, {Name:'Ashish'},{Name:'Kailas'},{Name:'Rahul'},{Name:'Pankaj'},{Name:'Shrikant'},{Name:'Amol'},{Name:'pravin'}]);

  private var resultAC:Array;

  private function initApp():void

{

dgList.dataProvider = ac;

txtResult.text = ;

txiSearch.text = ;

}

  private function search():void

{

resultAC = new Array();

 for(var i:int=0;i<arr.length;i++)

{

 var tempArr:Array = new Array();

  var str:String = String(arr[i]).toLowerCase();

 tempArr = str.match(StringUtil.trim(txiSearch.text).toLowerCase());

 if(tempArr!=null)

{

if(tempArr.index==0)

{

resultAC.push({Name:arr[i]});

}

}

}

assignValues();

}

 private function searchAc():void

{

resultAC = new Array();

for(var i:int=0;i<ac.length;i++)

{

var tempArr:Array = new Array();

 var str:String = String(ac[i].Name).toLowerCase();

 tempArr = str.match(StringUtil.trim(txiSearch.text).toLowerCase());

 if(tempArr!=null)

{

if(tempArr.index==0)

{

 resultAC.push({Name:ac[i].Name});

}

}

}

assignValues();

} 

private function assignValues():void

{

dgList.dataProvider = resultAC;

txtResult.text = ;

for(var j:int=0;j<resultAC.length;j++)

{

txtResult.text = txtResult.text + ObjectUtil.toString(resultAC[j].Name);

}

}

]]>

</mx:Script>

<mx:Label text=”Enter Search Term :” x=”116” y=”26/>

<mx:TextInput id=”txiSearch” x=”284” y=”24” enter=”search()”/>

 <mx:Button id=”Search” label=”Search Array Item” click=”search()” x=”114” y=”65/>

<mx:Button id=”SearchAc” label=”Search ArrayCollection Item” click=”searchAc()” x=”280” y=”65/>

<mx:Text x=”174” y=”139” id=”txtResult/>

<mx:Label x=”477” y=”26” text=”Searches Within Array On Direct Enter/>

<mx:DataGrid x=”153” y=”195” id=”dgList>

<mx:columns>

<mx:DataGridColumn headerText=”Name” dataField=”Name/>

</mx:columns>

</mx:DataGrid>

<mx:Button x=”341” y=”247” label=”Refresh” click=”initApp()”/>

 </mx:Application>

 

 

Best Luck   )

Thanks and regards

Shashank Kulkarni

Feel free to mail me :) shashank.pawan@gmail.com

 

 
Leave a comment

Posted by on August 26, 2008 in Best of Flex Utillity

 

Tags: , ,

 
Follow

Get every new post delivered to your Inbox.