RSS

Category Archives: Best of Flex Utillity

All Project related utility in FLEX

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

 
 

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

Hyperlinking In FLEX

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 a hyperlink in the Htmltext property.

 

About link Event :

 

link : Dispatched when a user clicks a hyperlink in an HTML-enabled text field, where the URL begins with "event:".

 

To generate the link event, prefix the hyperlink destination with event:

 

 As the following example shows

 

<?xml version=”1.0″?>

 

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”

    borderStyle=”solid”

    backgroundGradientColors=”[#FFFFFF, #FFFFFF]“>

   

    <mx:Script>

        <![CDATA[

            import flash.events.TextEvent;

 

            public function linkHandler(event:TextEvent):void {

                myLabel.text="link occured.";

                // Open the link in a new window.

                navigateToURL(new URLRequest(event.text), '_blank');

            }

        ]]>

    </mx:Script>

   

    <mx:Label selectable=”true” link=”linkHandler(event);”>

        <mx:htmlText><![CDATA[<a href='event:http://www.adobe.com'>Adobe</a>]]></mx:htmlText>

    </mx:Label> 

 

    <mx:TextArea id=”myLabel”/>

</mx:Application>

 

 

Thanks and regards

 

Shashank Kulkarni

 

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

 
 

Tags: ,

Sample Full Screen Application in Flex

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 your new project goto your HTML wrapper i.e.

index.template.html . Now

Step 1.

In the script section add comman (,) in last property of AC_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.

Step 2. Add the following code

private var flag:Boolean = false;

private function clickHandler(e:Event):void

{

if(flag==false)

{

flag=true;

stage.displayState = StageDisplayState.FULL_SCREEN;

}

else if(flag==true)

{

flag=false;

stage.displayState = StageDisplayState.NORMAL;

}

}

Now Stage Class:– The Stage class represents the main drawing area. i.e it represents the entire area where Flash content is shown.

Also important thing is that

We don’t create object of this class as obj:Stage=new Stage();

The Stage object is not globally accessible. You need to access it through the stage property of a DisplayObject instance

Most importantly we use

displayState : A value from the StageDisplayState class that specifies which display state to use . so this is how it should look as below

This is small code of sweet Fulscreen Player Application sample application… Do check it its muska…Really J

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” backgroundColor=”#000000″>

<mx:Script>

<![CDATA[

import mx.collections.ArrayCollection;

[Bindable]

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'}])

private var flag:Boolean = false;

private function clickHandler(e:Event):void

{

if(flag==false)

{

flag=true;

stage.displayState = StageDisplayState.FULL_SCREEN;

}

else if(flag==true)

{

flag=false;

stage.displayState = StageDisplayState.NORMAL;

}

}

]]>

</mx:Script>

<mx:LinkButton label=”Full Screen” id=”btnTest” click=”clickHandler(event)” y=”0″ height=”16″ fontSize=”13″ color=”#ffffff” width=”109″/>

<mx:VideoDisplay id=”vduSong” x=”0″ y=”24″  width=”100%” height=”100%” source=”{cmbSongList.selectedItem.Path}”/>

<mx:ComboBox id=”cmbSongList” x=”259″ y=”-1″ dataProvider=”{arrList}” labelField=”Label”></mx:ComboBox>

<mx:Label x=”120″ y=”-1″ text=”Currently Playing ” color=”#ffffff” fontSize=”14″/>

</mx:Application>

Thanks and Regard

Shashank Kulkarni

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

 
 

Validation for stopping wrong file Upload at Browsing time

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

Best Luck :)

<?xml version="1.0" encoding="utf-8"?>
 <mx:Application xmlns:mx="<a href="http://www.adobe.com/2006/mxml">http://www.adobe.com/2006/mxml</a>"  pageTitle="Upload Functionality Usage And Validation" layout="absolute">
 <mx:Script>
 <![CDATA[
 import mx.utils.StringUtil;
 /**
 * 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>

Best Luck )

Thanks and regards

Shashank Kulkarni

 
3 Comments

Posted by on April 28, 2008 in Best of Flex Utillity

 

Tags: , ,

Changing the layout of container dynamically at runtime

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

<?xml version="1.0" encoding="utf-8"?>

<mx:application mx=<a href="http://www.adobe.com/2006/mxml">http://www.adobe.com/2006/mxml</a> pageTitle="Changing Layout Dynamically" layout="absolute" creationComplete="initCombo()">

<mx:script> <![CDATA[
 import mx.utils.StringUtil;
 import mx.controls.Alert;
 import mx.controls.Image;
 import mx.collections.ArrayCollection;
 [Bindable]

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";
 }

private function  changeSize():void
 {
 if(StringUtil.trim(txi.text)!=null && txi.length>3)
 {
 bx.direction="vertical";
 }
 else
 {
 bx.direction="horizontal";
 }
 }

]]>  </mx:Script>

<mx:box id="bx" x="76" y="231" width="500" height="100">
 <mx:textinput id="txi" change="changeSize()">
 <mx:combobox id="cmbTest" dataprovider="{prefixArray}" labelfield="Item">

</mx:Box>

</mx:Application>

Say Cheese :)
Thanks and regards
Shashank Kulkarni.

 
Leave a comment

Posted by on April 28, 2008 in Best of Flex Utillity

 

Tags: , ,

Solution To Remove Alerts Without commenting it at Release time

Hi,

We all know When we use Alert.show(“Alert Popped”); If this kind of statement remains uncommented then it creats major problem into the application while deploying it on live server.

Not only this but It also becomes hectic to find and remove all the unwanted Alerts coming out there in the Application specially in large projects. So to avoid such mess I have tried to create the small utility which allows us to avoid such mess.

To Download the application use the following path

http://www.esnips.com/doc/d6cc0890-7c70-495d-b621-23a8e39c8808/DebugUtility

If u likes it, Please reply,

Thanks

Shashank Kulkarni

feel free to mail me :)

 
2 Comments

Posted by on April 24, 2008 in Best of Flex Utillity

 

Tags: ,

 
Follow

Get every new post delivered to your Inbox.