Wednesday, March 18, 2009

Stack Component in Flex /AIR / AS3

While working on a auditors project i had a scenario where i was to upload files on every object of the for loop and i was to upload the file on the server with a returning id from the previous action , so that the coming files will be uploaded as the child of the previous files(As in the tree structure). I had to create a Stack class which solved my problem. The function defined are pop(), push() and peek().
I will be adding Linked List Component shortly......

Here is the Code :-

a) Stack Class

package
{

public class Stack
{
private var first : Node;

public function isEmpty ():Boolean
{
return first == null;
}

public function push (data : Object):void
{
var oldFirst : Node = first;
first = new Node ();
first.data = data;
first.next = oldFirst;
}

public function pop () : Object
{
if (isEmpty ())
{
trace ("Error: \n\t Objects of type Stack must containt data before you attempt to pop");
return null;
}
var data:Object = first.data;
first = first.next;
return data;
}

public function peek () : Object
{
if (isEmpty ())
{
trace ("Error: \n\t Objects of type Stack must containt data before you attempt to peek");
return null;
}
return first.data;
}
}
}

b)
Node Class as the store house object used in Stack Class
package
{

public class Node
{
public function Node()
{
}

public var next : Node;
public var data : Object;
}
}

Cheers

Varun Rathore

Tuesday, February 10, 2009

Hash Map in Flex / AIR / AS3



A HashMap lets you look up values by exact key (always case-sensitive). It is very much like a Hashtable, except that it is faster and not thread-safe. There are some minor other differences:

* HashMaps work with Iterators where the older Hashtables work with Enumerations
* Hashtables work best with capacities that are prime numbers. HashMaps round capacities up to powers of two.
In Flex we dont have such a facility to look up values by exact key , so i tried to create a HashMap Class which have almost all the typical function needed to be used in the application, i have created a custom Stack Class too and will be sharing the code for that too soon.

Here goes the code :-

package
{
public class HashMap
{
public var keys:Array;
public var values:Array;
//
public function HashMap()
{
super();
this.keys = new Array();
this.values = new Array();
}

public function containsKey(key:Object):Boolean
{
return (this.findKey(key) > -1);
}
public function containsValue(value:Object):Boolean
{
return (this.findValue(value) > -1);
}
public function getKeys():Array
{
return (this.keys.slice());
}
public function getValues():Array
{
return (this.values.slice());
}
public function get(key:Object):Object
{
return (values[this.findKey(key)]);
}
public function put(key:Object, value:Object):void
{
var oldKey;
var theKey = this.findKey(key);
if (theKey < 0)
{
this.keys.push(key);
this.values.push(value);
}
}
public function putAll(map:HashMap):void
{
var theValues = map.getValues();
var theKeys = map.getKeys();
var max = keys.length;
for (var i = 0; i < max; i = i - 1)
{
this.put(theKeys[i], theValues[i]);
}
}
public function clear():void
{
this.keys = new Array();
this.values = new Array();
}
public function remove(ikey:Object):Object
{
var theiKey = this.findKey(ikey);
if (theiKey > -1)
{
var theValue = this.values[theiKey];
this.values.splice(theiKey, 1);
this.keys.splice(theiKey, 1);
return (theValue);
}
}
public function size():int
{
return (this.keys.length);
}
public function isEmpty():Boolean
{
return (this.size() < 1);
}
public function findKey(key:Object):Object
{
var index = this.keys.length;
while(this.keys[--index] !== key.toString() && index > -1)
{
}
return(index);
}
public function findValue(value:Object):Object
{
var index = this.values.length;
while(this.values[--index] !== value && index > -1)
{
}
return (index);
}

}
}

Cheers

Varun Rathore

Monday, February 9, 2009

How To Call Methods from a External SWF (Reflection in Flex )

While loading the swf from a external source , we are always wondering what all methods it may have , the developers have to seek help from the swf coders to get the methods and commnets for the methods which they have created, sometimes the developers provide the swf but fail to provide a meaningful API with which you can interact with the swf.

The Phenomenon of seeing the properties and methods of the class is know as 'reflection', to achieve this in flex we need to use the SWF loader to load the swf into the application as follows

var swfUrl : String = "www.varunrathore.co.cc";// path to your swf
var req: URLRequest = new URLRequest(swfUrl);
var loader : URLLoader = new URLLoader(req);

Now we will be using the class to get the remote objects .Once you have the class names it was a matter of the actual introspection to see the available methods. To do this you can use the getDefinition method of the ApplicationDomain class in Flex
var classUsed:Class = loader.contentLoaderInfo.applicationDomain.getDefinition(className) as Class;


Here we get a XMl with all the methods and variables ...
var remoteSWF:Object = loader.content as Object;

Just call the method you wish to call from the SWF
remoteSWF.methodToBeCalled(); // calling the desired method with its name



Cheers

Varun Rathore

How to escape characters while Saving Data in SQLITE database

I have used the following function while saving data to sqllite if the data had some characters which needed to be escaped passing the string to the function returns the escapes string .

private static function SQLSafe(strTemp:String):String
{
var i:Number = 0;
var iOld:Number = 0;
var firstQuote:Boolean = false;
var strNew:String = "";
strTemp = StringUtil.trim(strTemp);
while (i != -1){
i = strTemp.indexOf("'", i);
if (i != -1){
if ((strNew != "") || (firstQuote)){
strNew += "'" + strTemp.substring(iOld, i);
}
else if (i != 0) {
strNew = strTemp.substring(iOld, i);
}
else {
firstQuote = true;
}
iOld = i;
i++;
}
}
if (iOld <= strTemp.length){
if (strNew != ""){
strNew += "'" + strTemp.substring(iOld, strTemp.length);
}
else {
strNew = strTemp.substring(iOld, strTemp.length);
}
}
return (strNew);
}


Cheers

Varun Rathore

Sunday, February 8, 2009

Debugging the Flex / Flash / AIR from outside the flex builder


Arthropod is an external Debug trace window for Flash/Flex/AIR. Drop a simple class into your project and it will accept logging from the application/swf.
You can download the sample application from :-
http://arthropod.stopp.se/


Cheers Varun Rathore

Tuesday, December 23, 2008

Determining Inactivity in Flex (FlexEvent.IDLE)

A FlexEvent.IDLE event is dispatched every 100 milliseconds when there is no keyboard or mouse activity for 1 second.

In order to use the following event we need to import the following classes.
1. import mx.managers.SystemManager;
2. import mx.events.FlexEvent;
3. import mx.core.mx_internal;

You’ll need to tell your program that you want to use mx_internal as a namespace to access those properties within the SystemManager class. SytemManager has an “idleCounter” property which is super useful to access- but it is scoped to mx_internal and is not normally accessible. Trying to access it without these steps will throw an error:

1. use namespace mx_internal;

SystemManager is automatically instantiated as a part of every Flex app, so we do not need to do this manually. We will, however, need to add an event listener for FlexEvent.IDLE:

1. this.systemManager.addEventListener(FlexEvent.IDLE, userIdle);

Construct the callback method. One minutes is equal to 60000 milliseconds… divided by 100 ticks and the number we need to check against is 600. Of course, you’ll probably want something a little shorter in duration for testing:


private function userIdle(e:FlexEvent):void {
if(e.currentTarget.mx_internal::idleCounter == 600){
//do something!
}
}

Note that we prefix the idle Counter property with the mx_internal namespace.

That’s it! Now we have a sweet little activity monitor in our app. When activity is detected, idle Counter will automatically reset as well.

Sunday, December 7, 2008

Ribbit - Integrate Voice and Rich Communication


Ribbit - An open platform for multi-protocol communication for creating cool voiceware applications.
The Ribbit API's are simple and gives the opportunity to create new communication solutions for all sort of demands.
It enables developer to bring richness of voice calling and Web 2 Experience. You can add voice and Messaging service to your application without any traditional mobile phone intervention.
One thing that i found really good in Ribbit API is that Voice and Message can be delivered and received on multiple devices in multiple location across any sort of network.

Sunday, August 10, 2008

Modern programming languages provide a mixture of primitives for composing programs. Most notably Scheme, Smaltalk, Ruby, and Scala have direct language support for parameterized delayed-execution blocks of code, variously called lambda, anonymous functions, or closures. These provide a natural way to express some kinds of abstractions that are currently quite awkward to express in Java. For programming in the small, anonymous functions allow one to abstract an algorithm over a piece of code; that is, they allow one to more easily extract the common parts of two almost-identical pieces of code.

Closure Literals

We introduce a syntactic form for constructing an anonymus function value:

Primary:
ClosureLiteral
ClosureLiteral:
{ FormalParametersopt => BlockStatementsopt Expressionopt }

Evaluating the closure literal expression results in a closure instance . A closure instance is converted to some object type by a closure conversion. In the nominal version of the specification, it is a compile-time error if a closure literal appears in a context where it is not subject to a closure conversion. In the functional version of the specification, if a closure literal is not subject to a closure conversion it is converted to the corresponding function type of the closure literal, which is the function type with: identical argument types; a return type that is the type of the final expression, if one exists, or java.lang.Unreachable if the closure literal's body cannot complete normally, or void otherwise; and a throws type list corresponding to the checked exception types that can be thrown from the body of the closure literal. The conversion, in either case, occurs entirely at compile-time.

A closure literal captures a block of code - the block statements and the expression - parameterized by the closure literal's formal parameters. All free lexical bindings - that is, lexical bindings not defined within the closure literal - are bound at the time of evaluation of the closure literal to their meaning in the lexical context in which the closure literal appears. Free lexical bindings include references to variables from enclosing scopes, and the meaning of this, break, continue, and return. Evaluating the closure literal does not cause the statements or expression to be evaluated, but packages them up at runtime with a representation of the lexical context to be invoked later.

At runtime, if a break statement is executed that would transfer control out of a statement that is no longer executing, or is executing in another thread, the VM throws a new unchecked exception, UnmatchedNonlocalTransfer. Similarly, an UnmatchedNonlocalTransfer is thrown when a continue statement attempts to complete a loop iteration that is not executing in the current thread. Finally, an UnmatchedNonlocalTransfer is thrown when a return statement is executed if the method invocation to which the return statement would transfer control is not on the stack of the current thread.


Cheers

Varun Rathore

Saturday, August 9, 2008

Cairngorm Is Open Source Now



This week Adobe announced that Cairngorm has been moved to from Labs to opensource.adobe.com.

So what does this mean for you, as a developer, building RIAs targeting the Adobe Flex platform on top of Cairngorm?

It means a lot.

The most significant being that Cairngorm now has a formal community based initiative. This in itself facilitates positive growth as it encourages community feedback and collaboration. It allows the community to have an open pool for discussion, collaboration and most important, knowledge sharing.

R u willing to contribute?
To begin, start by signing up as a member and sharing your thoughts and experiences. Get involved; engage in conversations with the rest of the community. Take a look under the stage; get to know Cairngorm internals (if you don’t already).

Expect Good Things To Come Now..

Cheers

Varun Rathore

Friday, August 8, 2008

dpHibernate - Hibernate lazy loading with Adobe BlazeDS

One of the biggest problems with working with data in a RIA/Flex application is that it's all or nothing. You either need to get all of the data or write a lot of code to return the data in multiple requests. The problem is that good design means that we want to design our data object to match the data, not the UI. For instance a User might have an array of Orders which each have an array of Items. Seems simple enough, right. The problem is that this is a large complex objects which could require a query that joins multiple tables when returning data to your application. No big deal if you want to display all of the data. But if you are just trying to output the users name and email in a search result screen then this is a huge performance hit.

Luckily there is a solution, It is called lazy loading. JSP developers, which use the java hibernate framework, have been able to use lazy loading for years. But until now this did not work with remote client applications like Flex. For those of you who have tried, I'm sure your familiar with the dreaded LazyLoadingException. Frustrating huh. Lazy loading let's your define a complete object model, such as a User with an array of Orders. But only return the data you are actually using in your presentation layer (Flex). Avoiding that all or nothing data problem that is so common.

I'm happy to announce a new Digital Primates open source project. dpHibernate, add support to BlazeDS for Hibernate lazy loading. You can find both the java and the ActionScript parts of the project here:
If you're not familiar with hibernate, check out http://www.hibernate.org. At a real high level, Hibernate is a java ORM tool, which lets you map java beans to a relation database. Hibernate does all of the sql work for you.

So how do dpHibernate work? dpHibernate is actually a combination of two code bases. First, there is a custom java adapter for the BlazeDS server. This HibernateAdapter understands the hibernate proxy objects and knows how to convert them into a special dpHibernate proxy which the AMF serializer will ignore and not try to initialize. This is how the proxy objects are able to go back to the client without getting the LazyLoadingException.

The second part of dpHibernate is an ActionScript library which gives your application the code it needs to understand these dpHibernate proxy objects. This AS library has the code to manage your ActionScript beans and knows how to call back to the server to load a proxy once that object has been touched, usually with a binding expression.

In case your wondering, how does dpHibernate differ from the hibernate support in LiveCycle Data Services ES? For one dpHibernate doesn't require LCDS it works with the open source BlazeDS server. The other big difference is that hibernate support in LCDS requires you to duplicate the lazy associations in the services-config.xml and you need to use an Assembler class to get the hibernate objects. dpHibernate let's you call any java method and return any hibernate object.

So check it out, if you can use it I'd love to hear about it. If it doesn't work for you I want to know about that too. And as with all open source projects this one can use as many eyes as possible on it too. If you find any hibernate configurations that don't work let me know. Or better yet, send me a test case with the right hibernate mapping files to recreate the issue.

About Me