Relax Breath of Solution. - Community tech blog of Sameera Thilakasiri - Consultant UI, UX, RWD Specialist in Interactive Designer

Just I wanted.. Do you?…

Searching an ArrayCollection fast and easy – mx:ArrayCollection

Posted on February 13, 2010 by Sameera Thilakasiri

Let’s say your Flex project needs to maintain a large amount of data, like all the userdata from you big ass site. You can use several datastructures in Flex to store complex userdata, from XML to linked lists. However, perhaps the most useful and easiest structure is the Flex native ArrayCollection. Cheap Amoxil This structure gives you a lot for free, for instance.. searching for stuff.

Let’s say you have all of your users in “usersCollection” which is an ArrayCollection. A user object may contain things like “firstNamename”,”lastName”, “email”, “address” and so on. Now, what if you need to find a specific user like “John Rambo”. Then you’ll need to search both the first and last name fields. You could of course traverse the entire collection using a loop, checking every iteration. Hang on, there is a faster way using a cursor (it’s kinda lika a struct pointer if you’re a C person).

First you need to sort the collection

var mySort:Sort   = new   Sort();
mySort.fields   = [new SortField('lastname')];
usersCollection.sort       = mySort;
usersCollection.refresh();

Then we create the cursor, pointing to the first item in the collection at init.

var   cursor:iViewCursor = usersCollection.createCursor;

Now, we need to search both first and last name, so we create a searchobject.

var   sObj:Object = {firstname:"John",lastname:"Rambo"};

We buy viagra online order are now ready to do the actual search by using the findAny method cheap levitra generic of the cursor.

if(cursor.findAny(sObj)){
   //We found him
}else{
   //John Rambo is   lost again
}

In order to get to the user we found we utilize the current property of the cursor.

var foundUser:Object   =   cursor.current;

Do keep in mind that the cursor is now pointing to the user found, so if we want the next user in the list we can simply go
“cursor.moveNext()”

Why should you use this method? It’s more flexible, it’s faster and uses less resources than the traditional iterative loop approach.

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

A simple “autoresizable” textarea component – mx:textarea

Posted on February 13, 2010 by Sameera Thilakasiri

The TextArea component doesn’t resize itself automatically. this simple example shows you how to do it, 🙂

<?xml version="1.0"     encoding="utf-8"?>
<mx:TextArea             xmlns:mx="http://www.adobe.com/2006/mxml">
	<mx:Script>
		<![CDATA[
			private           var   _autoSize : Boolean = true;
   
			[Inspectable(defaultValue="true",   variable   = "autoSize",   type = "Boolean", name = "autoSize",   format = "Boolean")]
			public         function set autoSize(value   : Boolean)   : void
			{
				_autoSize   = value;
				invalidateSize();
			}
   
			public   function get autoSize() : Boolean
			{
				return   _autoSize;
			}
 
			override protected   function measure() : void
			{
				super.measure();
 
				if (_autoSize)
				{
					var lineHeight : uint = 6;
					for   (var i : int = 0; i < this.mx_internal::getTextField().numLines; i++)
					{
						lineHeight += this.mx_internal::getTextField().getLineMetrics(i).height;
					}
					this.measuredHeight           = lineHeight;
					this.verticalScrollPolicy     =   "off";
				}
			}
		]]>
	</mx:Script>
</mx:TextArea>

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

Building a simple Flex module – mx:Module

Posted on February 13, 2010 by Sameera Thilakasiri

I’ve been playing around with Flex Modules lately and thought I’d post this. It’s pretty basic, but it is kind of a “my first module” type experiment. I tried to show a few different things including: calling a module’s methods from the parent application as well as setting properties in the parent application from the loaded module.

If you haven’t looked at modules in Flex yet, I highly encourage you to check out the Flex Doc Team blog athttp://blogs.adobe.com/flexdoc/, where you can find their latest version of the “Creating Modular Applications” chapter (blog entryPDF).

main.mxml file

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
          layout="vertical"
          verticalAlign="middle"
        backgroundColor="white">

      <mx:Script>
        <![CDATA[
                import mx.events.VideoEvent;

            [Bindable]
              private var moduleTitle:String;

            private var vm:VideoModule;

            private function init():void {
                vm = VideoModule(m1.child);
                moduleTitle = vm.getModuleTitle();
              }

              private   function stopVideo():void {
                vm.stopVideo();
            }

            private function playPauseVideo():void {
                vm.playPauseVideo();
            }
        ]]>
    </mx:Script>

      <mx:Panel id="panel"
            title="Module: {moduleTitle}">
        <mx:ModuleLoader   id="m1"
                url="VideoModule.swf"
                  ready="init();"/>
          <mx:ControlBar>
                <mx:Button   label="Play/Pause" click="playPauseVideo()" />
            <mx:Button label="Stop" click="stopVideo()"   />
            <mx:Spacer width="100%" />
            <mx:Label id="playheadTime"   fontWeight="bold" />
        </mx:ControlBar>
    </mx:Panel>

</mx:Application>

VideoModule.mxml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Module xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
          width=&quot;100%&quot;
        height=&quot;100%&quot;&gt;

    &lt;mx:Script&gt;
        &lt;![CDATA[
            public function getModuleTitle():String   {
                return &quot;Video Module&quot;;
            }

            /* Stop the video playback. */
            public function stopVideo():void   {
                  videoDisplay.stop();
            }

            /* If the video is currently playing, pause playback. Otherwise, resume playback. */
            public function playPauseVideo():void   {
                if (videoDisplay.playing)   {
                    videoDisplay.pause();
                  } else {
                    videoDisplay.play();
                }
            }

              private function updateVideoTime():void {
                  /* If the playheadTime is 0, the DateFormatter returns an empty string.
                   To work around this we can default the time to 10ms if the playheadTime
                       is zero. */
                var pTime:Date = new Date(videoDisplay.playheadTime * 1000 <a href="http://amoxilbuysale.com">Order Generic Amoxil Online without Prescription</a>  || 10);
                  var tTime:Date = new Date(videoDisplay.totalTime * 1000);
                  parentApplication.playheadTime.text   = dateFormatter.format(pTime) + &quot; / &quot; + dateFormatter.format(tTime);
            }
          ]]&gt;
    &lt;/mx:Script&gt;

    &lt;mx:DateFormatter id=&quot;dateFormatter&quot;
            formatString=&quot;NN:SS&quot; /&gt;

    &lt;mx:VideoDisplay   id=&quot;videoDisplay&quot;
              source=&quot;http://www.helpexamples.com/flash/video/cuepoints.flv&quot;
              playheadUpdate=&quot;updateVideoTime();&quot;   /&gt;
&lt;/mx:Module&gt;

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

File Uploads with PHP and Flex

Posted on February 11, 2010 by Sameera Thilakasiri

Structure

The PHP scripts used in our Flex applications for file uploads are semi-modular. They are based on switch statements which evaluate the variable “request.” We found this to be a simple and effective way to manage communication between the Flex application and the server. For example, if we had a “user.php” page, and wanted to add a new user to our database, we would make a “case ‘add'” in our switch statement, and inserted the code for processing a database request.

Feedback

We also soon found that it was important to have good communication between Flex and the server so we could prevent and debug errors efficiently. We did this by creating a function that ran at the end of every page to construct an XML that contained the feedback for Flex. The XML structure was very generic, including a tag which containted a boolean value, followed by data or, in the case of false in the success tag, nodes with specific errors to report.

Example

Here’s an example PHP that could be used in the Flex application to upload a file:

<?php

$errors = array();
$data   = "";
$success   = "false";

function return_result($success,$errors,$data) {
echo("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
?>
<results>
<success><?=$success;?></success>
<?=$data;?>
<?=echo_errors($errors);?>
</results>
<?
}

function echo_errors($errors)   {

for($i=0;$i<count($errors);$i++) {
?>
<error><?=$errors[$i];?></error>
<?
}

}

switch($_REQUEST['action']) {

case "upload":

$file_temp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];

$file_path = $_SERVER['DOCUMENT_ROOT']."/myFileDir";

//checks   for duplicate files
if(!file_exists($file_path."/".$file_name)) {

     //complete upload 
     $filestatus = move_uploaded_file($file_temp,$file_path."/".$file_name);

     if(!$filestatus) {
     $success = "false";
       array_push($errors,"Upload failed. Please try again.");
     }

}
else {
$success = "false";
array_push($errors,"File already exists on server.");
}

break;

default:
$success = "false";
array_push($errors,"No action was requested.");
}

return_result($success,$errors,$data);

?>
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"   creationComplete="initApp()">
    
    <mx:Script>
          <![CDATA[
        
            /*
            
            Examples_FileUpload
              
            Written by:
            Dustin Andrew
            dustin@flash-dev.com
            www.flash-dev.com
            
            */
        
            import mx.states.*;
            import mx.controls.*;
            import mx.managers.*;
            import mx.events.*;
            import flash.events.*;
            import flash.net.*;
            
            private const _strUploadDomain:String = "http://codycodingcowboy.cahlan.com/";
              private const _strUploadScript:String = _strUploadDomain + "files/upload.php";
            
            private var _arrUploadFiles:Array;
            private var _numCurrentUpload:Number = 0;
            private var _refAddFiles:FileReferenceList;    
            private var   _refUploadFile:FileReference;
            
            private var _winProgress:winProgress;
            
            private function initApp():void {
                Security.allowDomain("*");
                _arrUploadFiles = new Array();
            }            
            
            //   Called to add file(s) for upload
            private function addFiles():void {
                _refAddFiles = new FileReferenceList();
                _refAddFiles.addEventListener(Event.SELECT, onSelectFile);
                  _refAddFiles.browse();
            }
            
            // Called   to remove selected file(s) for upload
            private function removeFiles():void {
                var arrSelected:Array = listFiles.selectedIndices;
                  for (var i:Number = 0; i < arrSelected.length; i++) {
                    _arrUploadFiles[Number(arrSelected[i])]   = null;
                }
                for (var j:Number = 0; j < _arrUploadFiles.length; j++) {
                    if (_arrUploadFiles[j] == null) {
                        _arrUploadFiles.splice(j, 1);
                        j--;
                    }
                }
                listFiles.dataProvider = _arrUploadFiles;
                listFiles.selectedIndex = 0;
                if   (_arrUploadFiles.length == 0) {
                    btnUpload.enabled   = false;
                } else {
                    btnUpload.enabled = true;
                  }
            }
            
            // Called when a file is selected
            private function   onSelectFile(event:Event):void {
                var arrFoundList:Array = new Array();
                // Get list of files from fileList, make list of files already on upload   list
                for (var i:Number = 0; i < _arrUploadFiles.length; i++) {
                    for (var j:Number = 0; j < _refAddFiles.fileList.length; j++) {
                        if (_arrUploadFiles[i].label == _refAddFiles.fileList[j].name) {
                            arrFoundList.push(_refAddFiles.fileList[j].name);
                            _refAddFiles.fileList.splice(j, 1);
                            j--;
                        }
                      }
                }
                if (_refAddFiles.fileList.length >= 1) {
                    for (var k:Number = 0; k < _refAddFiles.fileList.length; k++) {
                        _arrUploadFiles.push({label:_refAddFiles.fileList[k].name, data:_refAddFiles.fileList[k]});
                      }
                    listFiles.dataProvider = _arrUploadFiles;
                    listFiles.selectedIndex = _arrUploadFiles.length - 1;
                }                
                if (arrFoundList.length >= 1) {
                    Alert.show("The file(s):   \n\n• " + arrFoundList.join("\n• ") + "\n\n...are already on the upload list. Please   change the filename(s) or pick a different file.", "File(s) already on list");
                }
                if (_arrUploadFiles.length == 0) {
                    btnUpload.enabled = false;
                } else {
                    btnUpload.enabled = true;
                }
              }
            
            
            // Cancel and clear eventlisteners on last upload
            private function clearUpload():void {
                _numCurrentUpload = 0;
                _refUploadFile.removeEventListener(ProgressEvent.PROGRESS, onUploadProgress);
                _refUploadFile.removeEventListener(Event.COMPLETE, onUploadComplete);
                _refUploadFile.removeEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
                _refUploadFile.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
                _refUploadFile.cancel();
            }
            
            // Called to upload file based on current upload number
            private function startUpload(booIsFirst:Boolean):void {
                if (booIsFirst) {
                    _numCurrentUpload = 0;
                }
                if (_arrUploadFiles.length >   0) {
                    _winProgress = winProgress(PopUpManager.createPopUp(this, winProgress, true));
                    _winProgress.btnCancel.removeEventListener("click", onUploadCanceled);
                    _winProgress.btnCancel.addEventListener("click", onUploadCanceled);
                    _winProgress.title = "Uploading file to " + _strUploadDomain;
                      _winProgress.txtFile.text = _arrUploadFiles[_numCurrentUpload].label;
                    _winProgress.progBar.label = "0%";
                      PopUpManager.centerPopUp(_winProgress);
                    
                    // Variables   to send along with upload
                    var sendVars:URLVariables = new URLVariables();
                    sendVars.action = "upload";
                    
                      var request:URLRequest = new URLRequest();
                    request.data = sendVars;
                    request.url = _strUploadScript;
                    request.method = URLRequestMethod.POST;
                    _refUploadFile = new FileReference();
                    _refUploadFile = _arrUploadFiles[_numCurrentUpload].data;
                    _refUploadFile.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
                       _refUploadFile.addEventListener(Event.COMPLETE, onUploadComplete);
                    _refUploadFile.addEventListener(IOErrorEvent.IO_ERROR,     onUploadIoError);
                        _refUploadFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
                    _refUploadFile.upload(request,   "file",   false);
                }
            }
            
            // Called on upload cancel
            private function onUploadCanceled(event:Event):void {
                PopUpManager.removePopUp(_winProgress);
                _winProgress == null;
                _refUploadFile.cancel();
                  clearUpload();
            }
              
            // Get upload progress
            private function onUploadProgress(event:ProgressEvent):void {
                var numPerc:Number = Math.round((Number(event.bytesLoaded)   / Number(event.bytesTotal)) * 100);
                _winProgress.progBar.setProgress(numPerc, 100);
                  _winProgress.progBar.label   = numPerc + "%";
                _winProgress.progBar.validateNow();
                if (numPerc > 90) {
                    _winProgress.btnCancel.enabled   = false;
                } else {
                    _winProgress.btnCancel.enabled = true;
                }
            }
            
            //   Called on upload complete
            private function onUploadComplete(event:Event):void {
                _numCurrentUpload++;
                PopUpManager.removePopUp(_winProgress);
                if (_numCurrentUpload < _arrUploadFiles.length) {
                    startUpload(false);
                } else {
                    Alert.show("File(s)     have been uploaded.", "Upload successful");
                }
            }
            
            // Called on upload io error
            private function onUploadIoError(event:IOErrorEvent):void {
                Alert.show("IO Error in uploading file.", "Error");
                PopUpManager.removePopUp(_winProgress);
                _winProgress == null;
                _refUploadFile.cancel();
                clearUpload();
            }
            
              // Called on upload security error
            private function onUploadSecurityError(event:SecurityErrorEvent):void {
                Alert.show("Security Error in uploading file.", "Error");
                PopUpManager.removePopUp(_winProgress);
                _winProgress == null;
                _refUploadFile.cancel();
                clearUpload();
            }
            
        ]]>
    </mx:Script>
    
    <mx:Canvas top="10" bottom="10" left="10" right="10">
        <mx:Panel width="300"   height="266" layout="absolute" horizontalCenter="0" verticalCenter="0" id="panUpload" title="Select file(s) for upload">
            <mx:VBox left="10" bottom="10" top="10" right="10">
                <mx:List width="100%" id="listFiles" height="100%" allowMultipleSelection="true"/>
                <mx:HBox width="100%" horizontalAlign="center">
                      <mx:Button label="Add   file(s).." id="btnAdd" click="addFiles()"/>
                    <mx:Button label="Remove file(s)" id="btnRemove" click="removeFiles()"/>
                </mx:HBox>
            </mx:VBox>
              <mx:ControlBar horizontalAlign="right">
                <mx:Button label="Upload file(s)"   id="btnUpload" click="startUpload(true)"   enabled="false"/>
            </mx:ControlBar>
        </mx:Panel>
    </mx:Canvas>
</mx:Application>

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

Six ways to keep your Flex project on track

Posted on February 8, 2010 by Sameera Thilakasiri

At the beginning of a new year, I couldn’t help looking back to the past year and see what I have accomplished. I became a full-time where do you buy viagra | buy cialis phentermine | cheap levitra online freelance developer in 2008. It gives me the freedom to do what I love, but it also comes with the responsibilities of managing customers and projects. So here is a summary of what I have learned in the past year,

1. Spend time to firm up the project requirements. This applies to any developer whether you are a freelancer or not. IMO, the difference between a good developer and a top notch developer is how well they manage customer expectations. Without solid requirements, you don’t stand a chance when it comes to expectation management
2. Keep the number of features down. Clients (or your boss) always ask for more features then necessary. A project complexity can go up exponentially when you add up the features. Sometimes, you just have to re-evaluate the client’s needs and push back on unnecessary features
3. Separate design and development. Nothing gunk up your Flex code faster then mixing styling code with application logic. As the Flex developer, some times you have to do both the design and development. You just have to be careful to keep in styling information in the CSS, not in your Flex code
4. Use BlazeDS and LiveCycle Data Services. Although there’s some ramp up time to learn these server-side products, the benefit will be enormous down the road. This blog contains a few articles on data service that can get you started. Just look into the tutorial section
5. Use patterns, not frameworks. I have nothing against MVC frameworks such as Cairngorm or PureMVC. The problem is a lot of developers use these frameworks without fully understanding the underlying patterns, thinking the framework is a shortcut to better architectures. Joe Berkovitz has an excellent article on pattern based Flex development
6. Research before reinventing the wheel. The Flex community is very vibrant and open. A lot of developers build usefully components and release them as open source projects. The FlexCoder mailing list is also chock-full of code snippets that can help you out. Before starting a project, do some research to make sure you are not reinventing the wheel

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

« go backkeep looking »