How to create a Ranking Array from a Numeric Array?

Say you have an array of numbers [2,7,1,4,5,9,7] and you need to find a rank array for this like [5,1,6,4,3,0,2]. This array represents the rank of each item in the original array starting from 0, which represents the largest number in the array. Actionscript doesn’t provide a method to do this. But this can be done by using the sort method available in the Array class.

var originalArray:Array = [2,7,1,4,5,9,7];
var sortArrayIndex:Array = originalArray.sort(Array.NUMERIC | Array.DESCENDING | Array.RETURNINDEXEDARRAY);
var resultOrder:Array = new Array();
for (var f:int = 0; f < originalArray.length;f++)
{
resultOrder[sortArrayIndex[f]] = f;
}
 trace(resultOrder); //5,1,6,4,3,0,2

If the array needs to be sorted ascending then the second line can be replaced with

var sortArrayIndex:Array = originalArray.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY);

FluorineFx

FluorineFX Logo

A .net based media server supports the following features:

  • Flex, Flash Remoting (RPC), Flex AMF Polling.
  • Flex Messaging
  • Flex Data Services (partial)
  • Supports AMF0, AMF3 and RTMP, RTMPT protocols
  • Service Browser
  • Template based code generator (ASP.NET like syntax)
  • Real-time Messaging, Remote SharedObject support, Video streaming
  • MSMQ integration
  • Easily integrate rich Internet applications with .NET backend
  • Easily integrate with Adobe Integrated Runtime (Adobe AIR™)

Above all this is opensource :)

Check it out
http://fluorinefx.com/

Top CEOs Advocate for Adobe Flash

Check out what top CEO’s have to say about flash

A simple chat application using Adobe Stratus and Flex

I thought of putting a tutorial on how I created a simple chat application which is possible using flash player 10 onwards. Believe me this does not require a costly media server to implement. Its very fast and communicates using Peer 2 Peer mechanism(P2P).

So what actually happens here is two flash player’s can communicate with each other directly. As shown in the picture below:

The above scenario would possibly erupt a volcano of ideas which can be possible with this kind of communication. Well I have already got many ideas related to developing an instant messenger or a multi player game etc. etc..

So I would just like to show how I developed a simple chat application which didn’t even took 15 minutes of my time to develop. So instead of wasting time reading this lets get into developing a chat application on the above technology.

Requirements:

Before we continue I would like you to see what we are going to develop

You can find two instances of flash player below which from now onwards will be referred as FP 1 and 2 respectively. Enter the nick name [Textfield] in FP 1 and 2. My id will be a long string of alpha numeric characters. Copy and paste the my id of FP1 to FP2 send message to id text field. In the same way copy the my id of FP2 and paste it in the send message to id text field of FP 1. Press connect buttons in both FP1 and FP2. After few milliseconds the controls like message box, send textfield and send button will get enabled.

Now type some message in FP1  and press send, thats it messages will get transfered from FP1 to FP2.  mmm.. a text chat application starts working.

FP 1

Get Adobe Flash player

FP 2

Get Adobe Flash player

Now lets see what happens inside. The code is well commented to make things clear

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">

      <mx:Script>
            <![CDATA[
            	import mx.controls.Alert;
                  //The url to adobe stratus
                  private var mRtmfp_url:String="rtmfp://stratus.adobe.com";
                  private var mDeveloperKey:String=YOUR DEVELOPER KEY GOES HERE;
                  // Object of Net connection
                  private var mNetConnection:NetConnection;
                  //The client id generated by stratus is store in the bindable variable mId
                  [Bindable]
                  private var mId:String;
                  //The net stream for sending data
                  private var mSendStream:NetStream;
                  // The net stream for receiving data
                  private var mRecStream:NetStream;

                  public function init():void
                  {

                        connect_btn.addEventListener(MouseEvent.MOUSE_UP, connectPeer);
                        send_btn.addEventListener(MouseEvent.MOUSE_UP, sendMessage);

                        mNetConnection = new NetConnection();
                        mNetConnection.addEventListener(NetStatusEvent.NET_STATUS, netConnectionHandler);
                        mNetConnection.connect(mRtmfp_url+"/"+mDeveloperKey);
                  }

                  private function netConnectionHandler(vEvent:NetStatusEvent):void
                  {
                       if(vEvent.info.code=="NetConnection.Connect.Success")
                       {
                       		mId=mNetConnection.nearID;

                       		mSendStream=new NetStream(mNetConnection, NetStream.DIRECT_CONNECTIONS);
                       		mSendStream.addEventListener(NetStatusEvent.NET_STATUS,onSendStreamHandler);
          					mSendStream.publish("mystream");
                       }

                  }

                  private function sendMessage(vEvent:MouseEvent):void
                  {
                  	if(send_message_txt.text=="")
                  	{

                  	}
                  	else
                  	{
                  		var message_to_send:String="<b>"+myname_txt.text+": </b>"+send_message_txt.text+"<br/>";
                  		mSendStream.send("reciveMessage", message_to_send);
                  		message_box_txt.htmlText+=message_to_send;
                  		send_message_txt.text="";
                  	}
                  }

                  public function reciveMessage(vMessage:String):void
                  {
                  	message_box_txt.htmlText+=vMessage;
                  }

                  private function connectPeer(vEvent:MouseEvent):void
                  {
                  	if(send_id_txt.text=="")
                  	{
                  		Alert.show("Peer id cannot be empty!");
                  	}
                  	else
                  	{
                  		mRecStream = new NetStream(mNetConnection,send_id_txt.text);
					    mRecStream.addEventListener(NetStatusEvent.NET_STATUS,onReceiveStreamHandler);
					    mRecStream.play("mystream");
					    mRecStream.client = this;
                  	}

                  }

                  private function onSendStreamHandler(vEvent:NetStatusEvent):void
                  {

                  }

                  private function onReceiveStreamHandler(vEvent:NetStatusEvent):void
                  {
                  	if(vEvent.info.code=="NetStream.Play.Start")
                  	{
                  		message_box_txt.enabled=true;
                  		message_box_txt.alpha=1;

                  		send_message_txt.enabled=true;
                  		send_message_txt.alpha=1;

                  		send_btn.enabled=true;
                  		send_btn.alpha=1;
                  	}
                  }

            ]]>
      </mx:Script>

    <mx:VBox paddingLeft="10" paddingTop="10" paddingRight="10" paddingBottom="10" width="100%" height="100%">
    	<mx:Label text="Stratus demo text chat application"/>
    	<mx:HBox width="100%">
    		<mx:Label text="Nick name:"/>
    		<mx:TextInput id="myname_txt" width="50%" />
    	</mx:HBox>
    	<mx:HBox width="100%">
    		<mx:Label text="My id is"/>
    		<mx:Label text="{mId}" selectable="true"/>
    	</mx:HBox>
    	<mx:HBox width="100%">
    		<mx:Label text="Send message to id"/>
    		<mx:TextInput id="send_id_txt" width="70%" />
    		<mx:Button id="connect_btn" label="Connect" />
    	</mx:HBox>
    	<mx:TextArea id="message_box_txt" enabled="false" alpha="0.5" width="100%" height="60%"/>
    	<mx:HBox width="100%">
    		<mx:TextInput width="70%" enabled="false" alpha="0.5" id="send_message_txt" />
    		<mx:Button label="send" enabled="false" alpha="0.5"  id="send_btn"/>
    	</mx:HBox>
    </mx:VBox>

</mx:Application>

Test Driven Development in FB4

Flash Platform lacked a proper TDD development tool for a long time. Adobe has taken this seriously and integrated it with the Flex Builder 4. See tutorial at the below given link.

http://www.adobe.com/devnet/flex/articles/flashbuilder4_tdd.html

P2P in FP 10.1

New generation of  P2P is getting ready at the following location

http://labs.adobe.com/technologies/stratus/

P2P on FP10 is available in this location http://www.flashrealtime.com/tuts/p2p-in-flash.html.

As3 Resize an image with constrain proportions

The below function can resize an image with constrain proportions. Always I search for it when I have that requirement. So added it here.

function resizeThumb(mc:MovieClip, maxW:Number, maxH:Number = 0, constrainProportions:Boolean = true):void
{
	maxH = maxH == 0 ? maxW : maxH;
	mc.width = maxW;
	mc.height = maxH;
	if (constrainProportions)
	{
		mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;
	}
}

Namespace in as3

Namespace in actionscript3 is entirely a new concept. Actionscript2 came with built-in namespaces, public and private, which was extended to protected and internal in actionscript3. Along with predefined namespaces, we can have user-defined namespaces too in as3.

Adobe documentation : Namespaces are outfitted with a Universal Resource Identifier (URI) to avoid collisions, and are also used to represent XML namespaces when you work with E4X. This means, Namespaces are similar to packages and it provide a way to separate code in to separate “space”. Packages allow you to have different classes with the same name(different packages), namespaces allow you to have different methods with the same name in one class (with different namespaces).

Now let us see how namespace are used with an example.

// class
package {

    //package level namespace
    public namespace np = "www.44actions.com";

    public class UseNamespace {

        // class level namespace declaration
        public namespace n1;
        public namespace n2 = "www.browzor.com";

        // property declared with different namespace
        n1 var value:String = "namespace1";
        n2 var value:String = "namespace2";
        np var value:String = "namespace_package";

         //method declared with different namespace
        n1 function displayValue():String {
                return n1::value;
        }
        n2 function displayValue():String {
                return n2::value;
        }
        np function displayValue():String{
                return np:value;
        }

        //method
        public function showAll():String{
                return n1::displayValue() +" and "+n2::displayValue()+" and "+np::displayValue();
        } 

        //constructor
        function useNamespace(){
                trace(showAll());
        }
    }
}
// class
package{
    public  class CallNamespace{

        //construcator
        public callNamespace(){
            var newObject:UseNamespace = new UseNamespace(); // trace : "namespace1 and namespace2 and namespace_package"
            //call method at package level namespace successfully
            trace(newObject.np::displayValue()); // trace : "namespace_package"
        }
    }
}

Let me try to explain this :) .

Declaring namespace – Namespace are declared same as any other class members with a keyword namespace. But if u need to access namespace outside class you need to declare it as package level. See the above example where I have both class level and package level namespace declaration. Here np is a package level namespace and n1 and n2 are class level.
You can either define a namespace with an explicit URI, as you would define an XML namespace, or you can omit the URI. np & n2 are namespaces with explicit URI but n1 is not. If you omit the URI, the compiler will create a unique internal identification string in place of the URI.
Using namespace – Functions, variable and constants can be placed into a custom namespace. Classes cannot be!. Now see in above example how variable and methods declared into custom namespace. Though they have conflicting names, since they are in different namespace they can exist in same classes. (seems something similar to overloading – funny). Also keep in mind that cannot apply more than one namespace to one declaration which include build-in namespace too.
Referencing namespace – You can reference namespaces with the use namespace directive or you can qualify the name with the namespace using the name qualifier (::) punctuator. Only if the namespace is declared at package level, it can be referred outside its classes.

Flex ActionScript 3(AS3) questions and answers

I would like to list out few technical questions and answers which technical guys like me can phase at any stage in life. May be during an interview or questions you may check with people whom you are recruiting.

If you find any questions which you think should be listed here please comment it, if they are worth I will make sure they get added to the list below:

  1. Is it possible to make httpService Requests synchronous?
    Ans: No.
  2. I need to load an image from flickr into my application. Do I need a crossdomain.xml file on flickr?
    Ans: No. Flickr has already given a public access to its picture collection.You can find that file here http://api.flickr.com/crossdomain.xml. The only think we have to do is register an account with flickr and get API key. For more details visit http://www.flickr.com/services/apps/create/
  3. How do you generate random numbers within a given limit with actionscript?
    Ans:

    function randomNumbers(min:Number,max:Number)
    {
    var results:Number=Math.floor(Math.random()*max)+min;
    return results;
    }
  4. Have you built any components with actionscript? If so explain how you did it? Ans: When you define a simple component in ActionScript, you do not create a component, but you modify the behavior of an existing component. In the following example you create a subclass of the ComboBox class to create a custom ComboBox called CountryComboBox that is prepopulated with a list of countries. AS3 CODE:
    package components
    {
    import mx.controls.ComboBox;
     
    public class CountryComboBox extends ComboBox
    {
     
    public function CountryComboBox()
    {
    dataProvider = [ "India", "Sri Lanka" ];
    }
     
    }
    }

    MXML Usage of the above class:

  5. How do you call javascript from Flex?
    Ans
    : Very simple import this

    import flash.external.*;

    This is the code below to call a javascript method from flex

    if (ExternalInterface.available)
    {
    ExternalInterface.call("javascriptMethod", "this is one parms");
    }

    Javascript method is as below

     function javascriptMethod(vMessage)
    {
    alert(vMessage);
    }
  6. What is the difference between sealed class and dynamic classes? Ans:An instance of a sealed can have only properties and method which are already declared in that classes, but it is possible to add properties and methods programmatically at runtime for dynamic classes.
  7. What is state? what is the difference between states and ViewStack? Ans:ViewStack is to switch between different container for a single view but States change is to change view of single container itself. In ViewStack different views are switched by setting visibility true to only one container at a time, thus content containers are untouched.
  8. What keyword allows you to refer to private variables of a class? Ans: Private variables cannot be referred outside the class. “this” keyword can be used to refer private variable within a class.
  9. How polymorphism works on actionscript? Ans: Polymorphism describes multiple possible states for a single property. Another way of expressing this in OOPs is, different classes implementing the same method names. Polymorphism is achieved in actionscript with keyword Override.
  10. How do you overload functions in action script? Ans:Overloading is not supported in actionscripts current version(as3). Workaround for this is to declared method with wildcard data-type and handling it logically inside as show below.
    function functionName(parm:*):void
    {
    If(parm is String)
    {
    //do string operation..
    } else if(parm is Number)
    {
    //do number operation..
    } else if ….
    {
    //do required specific operations…
    }else
    {
    throw new customError(“datatype not supported”)
    }
    }
  11. What is dynamic keyword used for?
    Ans:In actionscript by making a class dynamic, it is possible to add properties and methods programmatically at runtime. A class can be declared dynamic by adding keyword “dynamic” to the class definition.

    dynamic class ClassName {
    //class definition…
    }
  12. What are sealed classes ?
    Ans:Actionscript classes that are not declared as dynamic are called sealed classes. So normally all classes are sealed by default.
    Technically speaking, an instance of a sealed can have only properties and method which are already declared in that classes.
  13. What keyword allows you to implement abstraction better?
    Ans:There is no keyword in as3 to implement abstraction directly, but there are workaround available for this. One of the best followed way is runtime enforcement of abstract classes.
  14. What’s the difference between Java and AS3 getters and setters?
    Ans:In Java there is no keyword for declaring setters and getters. A prefix set & get is added with property name for declaring setters and getters according to java standards.
    In actionscript “get” and “set” keywords are used for declaring getters and setters respectively.

Actionscript API reference

API reference that is provided as livedocs by Adobe is very slow most of the times. GotAPI is a site which provides Actionscript API documentation which is very fast. This site also provides API documentation for other programming languages as well. Try it and see the difference.

Update: A new beta version is available here. This has got improved user interface and more powerful search.