Pages

Wednesday, December 19, 2012

PHP: A webservice to query MySQL database via JSON


Here is a very basic webservice to query mysql database via GET or POST methods. It will return the result in json format.
<?php
/**
 * @filename service.php
 * @author Abhishek Kumar
**/

include 'config.php';

function db_query($iQuery, $iReturn)
{
 $output = array();
 if($connection = mysql_connect(DB_HOST, DB_USER, DB_PASS))
  if($database = mysql_select_db(DB_SCHEMA))
   if($result = mysql_query($iQuery))
   {
    if($iReturn)
    {
     while ($data[] = mysql_fetch_array($result, MYSQL_ASSOC));
     mysql_free_result($result);
     $output['success'] = $data;
    }
    else
     $output['success'] = $result;
    mysql_close($connection);    
   }
   else
    $output['failure'] = mysql_error();  
  else
   $output['failure'] = mysql_error();
 else
  $output['failure'] = mysql_error();
 
 return $output;
}

$query = (!isset($_REQUEST['query']))? NULL : $_REQUEST['query'];
$type = (!isset($_REQUEST['type']))? 0 : $_REQUEST['type'];

$output = db_query($query, ($type == 1));

print json_encode($output);
 
?>

<?php
/**
 * @filename config.php
 * @author Abhishek Kumar
**/

$isRemote = false;

if($isRemote)
{
 define('DB_HOST','www.domain.com');
 define('DB_USER','admin');
 define('DB_PASS','xyz');
}
else
{
 define('DB_HOST','127.0.0.1');
 define('DB_USER','root');
 define('DB_PASS','');
}

define('DB_SCHEMA','test');

?>
We can also make the service.php as class. See below:
<?php
/**
 * @filename dbagent.php
 * @author Abhishek Kumar
**/

include 'config.php';

class dbagent
{
    public static function query($iQuery, $iReturn)
    {
        $output = array();
        if ($connection = mysql_connect(DB_HOST, DB_USER, DB_PASS)) {
            if ($database = mysql_select_db(DB_SCHEMA)) {
                if ($result = mysql_query($iQuery)) {
                    if ($iReturn) {
                        $output['num_rows'] = mysql_num_rows($result);
                        while ($data[] = mysql_fetch_array($result, MYSQL_ASSOC));
                        mysql_free_result($result);
                        $output['success'] = $data;
                    } else {
                        $output['affected_rows'] = mysql_affected_rows();
                        $output['insert_id']     = mysql_insert_id();
                        $output['success']       = $result;
                    }
                    mysql_close($connection);
                } else
                    $output['failure'] = mysql_error();
            } else
                $output['failure'] = mysql_error();
        } else
            $output['failure'] = mysql_error();
        
        return $output;
    }
}
 
?>

Tuesday, December 11, 2012

How to enable/disable directory browsing on Red5?

To enable/disable directory browsing on Red5, follow the steps given below:
  1. Open the folder where Red5 is installed.
  2. Go inside the conf folder.
  3. Open the web.xml file.
  4. Search for the key string listings in the xml. As show below,
  5. Edit it's value as: 
    • true - to enable directory listings
    • false - to disable directory listings
  6. Save the xml file.
  7. Restart the Red5 server.
  8. Try to access the path like http://localhost:5080/live/, if you get HTTP Status 404 then directory listings is disabled otherwise it is enabled.
  9. After verification, you're done!

Thursday, December 6, 2012

How to setup OpenMeetings?

Recently, I got a requirement for which I have to install an Apache OpenMeetings on the Windows 7 server. So here I am sharing some of my experience that could be beneficial for readers who may use it as notes or guidelines.

Apache OpenMeetings is a web-based application that is developed using OpenLaszlo and Red5 Media Server. Here, OpenLaszlo is alternate to flex-sdk that takes xml files as input, compile them and return swf as output; while Red5 Media Server is alternate to Flash Media Server or Adobe Media Server. That means, every bit of this product is open-source.

Now to start with, you need to download Apache OpenMeetings from here.

According to the Latest Official ReleaseApache OpenMeetings Incubating 2.0 comes integrated with Red5. So you won't have to download it separately. But they're saying that future release of OpenMeetings will be independent of Red5. Which means user would get the flexibility to use OpenMeetings with any Red5 version.

Note: You need to have JRE 6 for OpenMeetings v2.

After you have downloaded the zip/tar file, unpack it. Copy the OpenMeetings folder in a program folder or any other desired location. Then execute red5-debug.bat.

A command-prompt window will popup that will run the OpenMeetings. When OpenMeetings starts running successfully, then try to access this link http://localhost:5080/. If no error shows up that means Red5 is working fine. Now you can proceed towards installation of OpenMeetings via accessing this link http://localhost:5080/openmeetings/install. The OpenMeetings - Installation page will appear. Select the Continue with STEP 1 link. Fill up the form. Here you need to see if you have any email client available. If you don't have it then select No for the field New Users need to verify their EMail. Otherwise, you won't be able to register. Since there is no email client, no email will be send for verification and OpenMeetings won't allow new user without verification. So it will be a deadlock. To avoid this, you may follow as the snapshot given below.


After filling up the required or available fields in the form, scroll down at the bottom and click on the INSTALL button.

For the first time, it will few minutes to setup database for OpenMeetings. After which you'll see the OpenMeetings - Installation Complete! page. Now click on Enter the Application link to proceed.

Enter the username and password that you entered in the form to login as administrator. Click on the Sign in button to enter in the OpenMeetings.

Now you might want to customize it. So you can change atleast 2 things: 
  1. The favicon; that is located at ..\apache-openmeetings\webapps\openmeetings\favicon.ico, that you can replace. 
  2. The title; that can be changed by replacing the text inside config.xml which is located at  ..\apache-openmeetings\webapps\openmeetings\config.xml. So open this config.xml and search for currentappname tag. When you find this tag, then replace the text with your desired one.
I hope, this tutorial will save your time.

Thursday, November 29, 2012

Allow full access to a local swf file

To allow full access to a local swf file, you need to follow these steps:
  1. Right click on flash player
  2. A vertical menu will appear
  3. Click on Global settings...
  4. A Flash Player Settings Manager will popup
  5. Go to Advanced tab
  6. Scroll down to Developer Tools section
  7. Click on Trusted Location Settings... button
  8. A Trusted Location Settings will popup
  9. Click on Add... button
  10. An Add Site will popup
  11. Click on Add Folder... button
  12. A Browse For Folder appears
  13. Select the required Drive/Folder
  14. Click on Ok button
  15. Browse For Folder disappears
  16. Click on Confirm button
  17. Add Site will disappear
  18. Click on Close button
  19. Trusted Location Settings will disappear
  20. Close the Flash Player Settings Manager popup

Friday, November 23, 2012

App: Vcam - video recorder cum player

Here is a video recorder cum player, i.e., named as vcam that I have developed for one of my client. It can be controlled either internally via provided buttons or externally via javascript. Currently it is showcased as internally controlled. So if anybody required similar solution, please drop me a comment/email.



To get the recorded video file link, please click on the Publish button after recording.

Note: Since the recorded videos didn't got saved for any useful purpose, so it will be deleted automatically after 2 hours from the time of recording.

Thursday, November 22, 2012

Openmeetings Widget Wordpress Plugin

One of my client asked me to create a Wordpress plugin, so the first thing I did was to search for any existing plugin on which I can work on. Luckily I found one. It was developed by Shuki Vaknin. You can visit his plugin at: http://wordpress.org/extend/plugins/openmeetings-integration-plugin-widget/

But I had little different requirement. So I modified the Shuki Vaknin's plugin.

The modification is that every session has a unique username. I choose guest as default name while adding a timestamp along with guest keyword like guest34578689.

Download

Link: openmeetings-integration-plugin-widget.zip

Tuesday, November 13, 2012

App: Numerologia

Please enter the required information about yourself to get your personalized prediction based on science of numerology.



Friday, October 26, 2012

App: Flash to HTML live communication without using Javascript

This is a demo in which by using flash we can create a dynamic text web-page. You're going to see it's application in my future blogs. We can create flash applications in which the swf will take care of calculations, etc. and the webpage text would get updated from inside.

Demo:

This text will get re-written over here by using id="fl2htmltop" and clicking on the provided button.



Similarly, this text will also get re-written by using id="fl2htmlbottom".

Note:
  1. <param name="allowscriptaccess" value="always" />
  2. <div id="fl2htmltop">Sample text to re-written over here.</div>
  3. <div id="fl2htmlbottom">Sample text to re-written over here.</div>

Thursday, October 25, 2012

App: Number Base Converter

This program is a number base converter. It's working is described below:

Number (in base aà Change base from base a to b à Number (in base b)
or
Na à Change base à Nb

where,
  • Na = Number (in base a)
  • Nb = Number (in base b)

Enter the input Number & it's Base and enter the ouput Number & it's Base. Then press convert button.

App: Net Connection Checker

I have developed this net connection checker utility tool to check the net connection at real-time. It is of great help while developing or testing FMS or Red5 based application. The user is only required to put the URL of that media server.



Note
  • FMS stands for Adobe's Flash Media Server
  • RED5 is a name of an open source media server

Thursday, October 18, 2012

Android: How to install Adobe AIR on Android emulator?

To install Adobe AIR run-time on Android emulator, follow this format for creating the batch file:

Format:

$ [drive-name]:
$ cd "[path-to-android-sdk]\android-sdk-windows\platform-tools"
$ adb -e install -r "[path-to-AIR-runtime-apk-file]"


Sample for Adobe Flash CS5.5:

$ d:
$ cd "D:\Programs\android-sdk_r15-windows\android-sdk-windows\platform-tools"
$ adb -e install -r "C:\Program Files (x86)\Adobe\Adobe Flash CS5.5\AIR2.6\runtimes\air\android\emulator\Runtime.apk"


Sample for Adobe Flash Builder 4.5:

$ d:
$ cd "D:\Programs\android-sdk_r15-windows\android-sdk-windows\platform-tools"
$ adb -e install -r "C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.5\sdks\4.5.0\runtimes\air\android\emulator\Runtime.apk"


Note: The system should have Adobe Flash CS5.5 installed prior to running this batch file.

Android: How to install application on Emulator via command-line?

To install an Android application file (*.apk) on Emulator, follow these steps:

Step-1: Create a blank batch file.
Step-2: Open the file in editor.
Step-3: Copy the format:

$ [drive-name]:
$ cd "[actual-path-to-android-sdk-folder]\android-sdk-windows\platform-tools"
$ adb -e install -r "[actual-path-to-apk-file]"

Step-4: Paste it in the file.
Step-5: Replace the instruction-text inside square-bracket with the actual paths.
Step-6: Verify it, if it looks similar to the sample given below:

$ d:
$ cd "D:\Programs\android-sdk_r15-windows\android-sdk-windows\platform-tools"
$ adb -e install -r "D:\Workshop\Flash\ANDROID\test1\test1.apk"

Step-7: Save the file.

Now double-click the batch file to install the app in android emulator.

Note: This method can be used while development when the developer need to install the *.apk file again and again.

Android: How to start Emulator from command-line?

To create the batch file to open the emulator via command-line, follow the steps given below:

Step-1: Create a blank batch file.
Step-2: Copy this format:

$ [drive-name]:
$ cd [path-to-android-sdk]\android-sdk-windows\tools
$ emulator -avd [android-emulator-name]


Step-3: Paste it in the batch file.
Step-4: Edit the instruction-text inside square-bracket accordingly.
Step-5: Verify the modified text, if it looks similar to the one given below:

$ d:
$ cd D:\Programs\android-sdk_r15-windows\android-sdk-windows\tools
$ emulator -avd AndroidSimulator


Step-6: Save the file.

Now the batch file is ready to be used. Just double-click on the batch-file to run the emulator.

Wednesday, October 17, 2012

AS3: Custom Tab-bar Controller


Flash movieclip architecture:
<movieclip name="tab_mc">
 <frameset>
  <frame name="normal">
   <textfield name="caption" framespan="4"></textfield>
   <graphics color="#333333"></graphics>
  </frame>
  <frame name="over">
   <graphics color="#666666"></graphics>
  </frame>
  <frame name="down">
   <graphics color="#999999"></graphics>
  </frame>
  <frame name="disabled">
   <graphics color="#333333" alpha="0.7"></graphics>
  </frame>  
 </frameset>
</movieclip>

<movieclip name="tabbar_mc">
 <frameset>
  <frame>
   <movieclip name="tab1" instanceof="{tab_mc}"></movieclip>
   <movieclip name="tab2" instanceof="{tab_mc}"></movieclip>
   <movieclip name="tab3" instanceof="{tab_mc}"></movieclip>
  </frame>
 </frameset>
</movieclip>

Class source-code:
package engine.ui 
{
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 import flash.text.TextField;
 /**
  * ...
  * @author Abhishek Kumar
  */
 public class CTabBar 
 {
  private var Container:MovieClip;
  
  private var proceed:Function;
  
  private var activeTab:String;
  
  public function CTabBar(mc:MovieClip) 
  {
   Container = mc;
   
   defaultState();
  }
  
  private function defaultState():void
  {
   for (var o:* in Container)
   {
    Container[o].gotoAndStop('normal');
    Container[o].buttonMode = true;
    Container[o].mouseChildren = false;
   }
   
   activeTab = Container.tab1.name;
   Container.tab1.gotoAndStop('down');
  }
  
  public function setLabels(list:Array):void
  {
   for (var i:int = 0, len:int = Container.numChildren; i < len; i++)
    TextField(Container['tab' + Number(i + 1)].caption).text = list[i];
  }
  
  public function getActiveTabIndex():int
  {
   return  Number(activeTab.substr(activeTab.length - 1));
  }
  
  public function attachListeners(callback:Function):void
  {
   proceed = callback;
   
   for (var o:* in Container)
   {
    Container[o].addEventListener(MouseEvent.MOUSE_UP, onClick_Tab);
    attachEffects(Container[o]);
   }
  }  
  
  private function onClick_Tab(me:MouseEvent):void
  {
   activeTab = MovieClip(me.currentTarget).name;
   
   for (var o:* in Container)
   {
    if(Container[o].name != activeTab)
     Container[o].gotoAndStop('normal');
   }
   
   var tabIndex:int = getActiveTabIndex();
   proceed(tabIndex);
  }
  
  private function attachEffects(mc:MovieClip):void
  {
   mc.addEventListener(MouseEvent.MOUSE_OVER, onOver_Container);
   mc.addEventListener(MouseEvent.MOUSE_OUT, onOut_Container);
   mc.addEventListener(MouseEvent.MOUSE_DOWN, onDown_Container);
  }
  
  private function detachEffects(mc:MovieClip):void
  {
   mc.removeEventListener(MouseEvent.MOUSE_OVER, onOver_Container);
   mc.removeEventListener(MouseEvent.MOUSE_OUT, onOut_Container);
   mc.removeEventListener(MouseEvent.MOUSE_DOWN, onDown_Container);
  }
  
  private function onOver_Container(me:MouseEvent):void
  {
   MovieClip(me.currentTarget).gotoAndStop('over');
  }
  
  private function onOut_Container(me:MouseEvent):void
  {
   if(activeTab == MovieClip(me.currentTarget).name)
    MovieClip(me.currentTarget).gotoAndStop('down');
   else
    MovieClip(me.currentTarget).gotoAndStop('normal');
  }
  
  private function onDown_Container(me:MouseEvent):void
  {
   MovieClip(me.currentTarget).gotoAndStop('down');
  }
  
 }

}

AS3: Sliding Toggle Switch like iPhone


The movieclip format would be like this:
<movieclip name="controller_mc" width="200">
 <frameset>
  <frame name="left">
   <movieclip name="slider_mc" x="0" width="100"></movieclip>
   <graphics framespan="2">
    <textfield name="caption1">ON</textfield>
    <textfield name="caption2">OFF</textfield>
   </graphics>
  </frame>
  <frame name="right">
   <movieclip name="slider_mc" x="100" width="100"></movieclip>
  </frame>
 </frameset>
</movieclip>
The source code of the class is given below:
package engine.ui 
{
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 /**
  * ...
  * @author Abhishek Kumar
  */
 public class CToggleSwitch 
 {
  private var Container:MovieClip;
  private var proceed:Function;
  
  private var toggle:int;
  
  public function CToggleSwitch(mc:MovieClip) 
  {
   Container = mc;
  }
  
  public function initiate():void
  {
   Container.buttonMode = true;
   Container.mouseChildren = false;
   
   toggle = 1;
   toggleState(toggle);
  }
  
  public function setLabels(list:Array):void
  {
   Container.caption1.text = list[0];
   Container.caption2.text = list[1];
  }
  
  public function attachListeners(callback:Function):void
  {
   proceed = callback;
   Container.addEventListener(MouseEvent.CLICK, onClick);
  }
  
  public function detachListeners():void
  {
   Container.removeEventListener(MouseEvent.CLICK, onClick);
  }
  
  private function onClick(me:MouseEvent):void
  {
   toggle = (toggle == 1)?2:1;
   toggleState(toggle);   
   
   proceed(toggle);
  }
  
  private function toggleState(state:int):void
  {
   switch (state)
   {
    case 1: Container.gotoAndStop('right');
     break;
    case 2: Container.gotoAndStop('left');
     break;
   }
  }
  
 }

}

AS3: Grid Algorithms


Algorithm-1

Is is using horizontal and vertical lines to create grid.
public function main(maxRows:int, maxColumns:int):void
{
 var containerWidth:Number = Container.width - 1;
 var containerHeight:Number = Container.height - 1;
 
 var cellWidth:Number = containerWidth / maxRows;
 var cellHeight:Number = containerHeight / maxColumns;
 
 var sprite:Sprite = drawGrid(maxRows, maxColumns, cellWidth, cellHeight, containerWidth, containerHeight);
 sprite.name = 'grid';
 Container.addChild(sprite);
}

public function destroy():void
{
 Container.removeChild(Container.getChildByName('grid'));
}

private function drawGrid(rowCount:Number, colCount:Number, rowGap:Number, colGap:Number, rowLen:Number, colLen:Number):Sprite
{
 var sprite:Sprite = new Sprite();
 var position:Number;
 
 var shapeRow:Shape = new Shape();
 for (var i:int = 0; i <= rowCount; i++)
 {
  position = rowGap * i;
  shapeRow = drawLine(position, 0, position, colLen);
  sprite.addChild(shapeRow);
 }
 
 var shapeCol:Shape = new Shape();
 for (var j:int = 0; j <= colCount; j++)
 {
  position = colGap * j;
  shapeCol = drawLine(0, position, rowLen, position);
  sprite.addChild(shapeCol);
 }
 
 return sprite;
}

private function drawLine(x1:Number, y1:Number, x2:Number, y2:Number):Shape
{
 var shape:Shape = new Shape();
 shape.graphics.moveTo(x1, y1);
 shape.graphics.lineStyle(1, COLOR_BORDER);
 shape.graphics.lineTo(x2, y2);
 return shape;
}

Algorithm-2

It is using series of rectangles in horizontal and vertical direction to make a grid.
public function main(maxRows:int, maxColumns:int):void
{
 var containerWidth:Number = Container.width - 1;
 var containerHeight:Number = Container.height - 1;
 
 var cellWidth:Number = containerWidth / maxRows;
 var cellHeight:Number = containerHeight / maxColumns;
 
 var sprite:Sprite = drawGrid(maxRows, maxColumns, cellWidth, cellHeight);
 sprite.name = 'grid';
 Container.addChild(sprite);
}

public function destroy(maxRows:int, maxColumns:int):void
{
 // to avoid memory leakage first remove all the child elements
 var o:* = Container.getChildByName('grid');
 for (var i:int = 0; i < maxRows; i++)
  for (var j:int = 0; j < maxColumns; j++)
   o.removeChild(o.getChildByName('c' + i + j));
 // then remove the parent container
 Container.removeChild(o);
}

private function drawGrid(rowCount:Number, colCount:Number, cellWidth:Number, cellHeight:Number):Sprite
{
 var subcontainer:Sprite = new Sprite();
 for (var i:int = 0; i < rowCount; i++)
 {
  for (var j:int = 0; j < colCount; j++)
  {
   var sprite:Sprite = createCell(cellWidth, cellHeight);
   sprite.x = cellWidth * i;
   sprite.y = cellHeight * j;
   sprite.name = 'c' + i + j;
   subcontainer.addChild(sprite);
  }
 }
 return subcontainer;
}

private function createCell(w:Number, h:Number):Sprite
{
 var sprite:Sprite = new Sprite();
  var shape:Shape = new Shape();
  shape.graphics.beginFill(COLOR_DEFAULT);
  shape.graphics.lineStyle(1, COLOR_BORDER);
  shape.graphics.drawRect(0, 0, w, h);
  shape.graphics.endFill();
 sprite.addChild(shape);
 return sprite;
}

Ways of representing Flash Movieclip architecture as pseudo-code


Way-1: JSON
Here is a representation of a Movieclip architecture in JSON format.
{
  movieclip: {
    name: 'controller_mc',
    data: {
      frame: [
        {
          name: 'normal',
          data: {
            textfield: {
              name: 'caption',
              framespan: '4'
            },
            graphics: {
              color: '#333333'
            }
          }
        },
        {
          name: 'over',
          data: {
            graphics: {
              color: '#666666'
            }
          }
        },
        {
          name: 'down',
          data: {
            graphics: {
              color: '#999999'
            }
          }
        },
        {
          name: 'disabled',
          data: {
            graphics: {
              color: '#333333',
              alpha: '0.7'
            }
          }
        }
      ]
    }
  }
}
The same pseudo-code can be shown in a more compact manner.
{
  movieclip: {
    name: 'controller_mc',
    data: {
      frame: [
        {
          name: 'normal',
          layer: {
            textfield: { name: 'caption', framespan: '4' },
            graphics: { color: '#333333' }
          }
        },
        {
          name: 'over',
          layer: {
            graphics: { color: '#666666' }
          }
        },
        {
          name: 'down',
          layer: {
            graphics: { color: '#999999' }
          }
        },
        {
          name: 'disabled',
          layer: {
            graphics: { color: '#333333', alpha: '0.7' }
          }
        }
      ]
    }
  }
}
Way-2: XML
It can be also represented as XML tags that seems more sleek & compact.
<movieclip name="controller_mc">
 <frameset>
  <frame name="normal">
   <textfield name="caption" framespan="4"></textfield>
   <graphics color="#333333"></graphics>
  </frame>
  <frame name="over">
   <graphics color="#666666"></graphics>
  </frame>
  <frame name="down">
   <graphics color="#999999"></graphics>
  </frame>
  <frame name="disabled">
   <graphics color="#333333" alpha="0.7"></graphics>
  </frame>  
 </frameset>
</movieclip>

AS3: Custom Button Controller - 2


Here is the pseudo code for the flash application architecture of custom-button movieclip.
<movieclip name="controller_mc">
 <frameset>
  <frame name="normal">
   <textfield name="caption" framespan="4"></textfield>
   <graphics color="#333333"></graphics>
  </frame>
  <frame name="over">
   <graphics color="#666666"></graphics>
  </frame>
  <frame name="down">
   <graphics color="#999999"></graphics>
  </frame>
  <frame name="disabled">
   <graphics color="#333333" alpha="0.7"></graphics>
  </frame>  
 </frameset>
</movieclip>
The controller class of the custom button.
package engine.ui 
{
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 /**
  * ...
  * @author Abhishek Kumar
  */
 public class CButton 
 {
  private var Container:MovieClip;
  private var proceed:Function;
  
  public function CButton(mc:MovieClip) 
  {
   Container = mc;
  }
  
  public function initiate():void
  {
   Container.mouseChildren = false;
   Container.buttonMode = true;
   Container.gotoAndStop('normal');
  }
  
  public function setLabel(label:String):void
  {
   Container.caption.text = label;
  }
  
  public function attachListener(callback:Function):void
  {
   proceed = callback;
   Container.addEventListener(MouseEvent.MOUSE_UP, onUp);
   Container.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
   Container.addEventListener(MouseEvent.MOUSE_OVER, onOver);
   Container.addEventListener(MouseEvent.MOUSE_OUT, onOut);
  }
  
  public function detachListener():void
  {
   Container.removeEventListener(MouseEvent.MOUSE_UP, onUp);
   Container.removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
   Container.removeEventListener(MouseEvent.MOUSE_OVER, onOver);
   Container.removeEventListener(MouseEvent.MOUSE_OUT, onOut);
  }
  
  private function onUp(me:MouseEvent):void
  {
   Container.gotoAndStop('normal');   
   proceed();
  }

  private function onOver(me:MouseEvent):void
  {
   Container.gotoAndStop('over');
  }

  private function onOut(me:MouseEvent):void
  {
   Container.gotoAndStop('normal');
  }

  private function onDown(me:MouseEvent):void
  {
   Container.gotoAndStop('down');
  }

 }

}

App: Interact - Multiplication of Proper/Improper fractions

This application was made for demo purpose that by using flash technologies the understanding of the concept can be made a lot easier for the learner.

App: Cryptographer - Blowfish

The application can encrypt or decrypt a message based on the provided key. It is using Blowfish algorithm to do so.

Software: Compiler Agent

The Compiler Agent is a GUI based desktop application to work on top of command-line. It can speed-up your command-line repetitive work, like compiling a program again and again. To use this application, user can set a template for command-line parameters. Then browse & select files/folders to insert the path in the template.

Download Link: CompilerAgent_v3.3.zip

The screen-shots of the application are given below:





Tuesday, October 9, 2012

Mobilesite: Thomas H. Heist Insurance Agency

Let me share my experience of creating a mobile-site using using jQuery Mobile for one of my client heistinsurance.com.

They already have the website for desktops. It is based on WordPress. Now they want a mobile-site for the same. And they choose to use the same database for the form submission, so that there will be a single point of reference.

Though it was a bit tricky but somehow I had successfully completed the project. Here is the snapshot.

Link: http://heistinsurance.com/m/

Since I was using jquery-mobile for mobilesite development but the main website was based on WordPress  So it became very difficult to merge these technologies & platforms. The jquery-mobile is a JavaScript based client-side framework while WordPress is php based server-side framework.

So the major challenge I had faced was to merge these technologies.

One way is to write a script that can insert the submitted form-data directly into the database. But it is not that easy in WordPress because the forms were made dynamically, so if there is 5 fields in a form then after submission you will see the 5 entry in the database that will contain 1 field entry per row. Since it is sharing a common id as a key to extract it back. It seems too complicated to make that plugin which can bypass the flow. As I was not in a mood to change the server-side scripts, so I chose to hack around it.

Then, I thought if there is a form on jquery-mobile then it can submit the data to the database via the main website form. So I had extracted the link where the main website form is submitting data, and modified that relative link into absolute one and put it in my jquery-mobile form. Then tested it ... voila ... it worked! The only hitch was that after submission it re-directs the mobile-site to the website. Now I need to stop this redirection. Then, AJAX came to me as life-saver. Though finding a way to use it perfectly was too tricky. But after banging my head for few days or may be a week got me through it. I swear, this was the biggest challenge in this project. But as I got through the form submission, the validation was also happening for free. It is happening because the serve-side script was handling that. So now I have to just catch those messages and put them at there respective places. That's it!

Now this mobile-site is running successfully at http://heistinsurance.com/m/.

Tuesday, March 20, 2012

AS3: Custom Button Controller


Here is the pseudo code for the flash application architecture of custom-button movieclip.
<movieclip name="controller_mc">
 <frameset>
  <frame name="normal">
   <textfield name="caption" framespan="4"></textfield>
   <graphics color="#333333"></graphics>
  </frame>
  <frame name="over">
   <graphics color="#666666"></graphics>
  </frame>
  <frame name="down">
   <graphics color="#999999"></graphics>
  </frame>
  <frame name="disabled">
   <graphics color="#333333" alpha="0.7"></graphics>
  </frame>  
 </frameset>
</movieclip>
The controller class of the custom button.
package com.engine 
{
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 /**
  * @file CButton.as
  * @author Abhishek Kumar
  */
 public class CButton 
 {
  private var container:MovieClip;
  private var proceed:Function;
  
  public function CButton(mc:MovieClip, fn:Function) 
  {
   container = mc;
   proceed = fn;
   
   initialize();
  }
  
  private function initialize():void
  {   
   container.gotoAndStop('up');
   container.buttonMode = true;
   container.mouseChildren = false;
  }
  
  public function attachListeners():void
  {
   container.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
   container.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
   container.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
   container.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
  }
  
  public function detachListeners():void
  {
   container.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
   container.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
   container.removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
   container.removeEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
  }
  
  private function onMouseUp(me:MouseEvent):void
  {
   container.gotoAndStop('up');
   proceed(me.target);
  }
  
  private function onMouseDown(me:MouseEvent):void
  {
   container.gotoAndStop('down');
  }
  
  private function onMouseOver(me:MouseEvent):void
  {
   container.gotoAndStop('over');
  }
  
  private function onMouseOut(me:MouseEvent):void
  {
   container.gotoAndStop('up');
  }
  
  public function show():void
  {
   container.visible = true;
  }
  
  public function hide():void
  {
   container.visible = false;
  }
  
 }

}

AS3: Custom Dropdown


Here is the code for the custom dropdown component.
/**
 * @file Sample.fla
 * @author Abhishek Kumar
 */
import com.engine.CDropdown;
import flash.display.MovieClip;

var cb:CDropdown = new CDropdown(dropdown_mc, onclick);
cb.attachListeners();

function onclick(mc:MovieClip):void
{
 trace(mc.name);
}

The pseudo code of application (Sample.fla) design architecture.
{
 movieclip: 'dropdown_mc'
 {
  movieclip: 'controller'
  {
   textfield: 'caption',
   frames: [up, over, down]
  }
  movieclip: 'dropdown'
  {
   movieclip: 'item0'
   { 
    textfield: 'caption',
    movieclip: 'selected',
    frames: [up, over, down]
   }
   movieclip: 'item1'
   { 
    textfield: 'caption',
    movieclip: 'selected',
    frames: [up, over, down]
   }
   movieclip: 'item2'
   { 
    textfield: 'caption',
    movieclip: 'selected',
    frames: [up, over, down]
   }
   movieclip: 'item3'
   { 
    textfield: 'caption',
    movieclip: 'selected',
    frames: [up, over, down]
   }
  }
 }
}

The source code of the component library.
/**
 * @file Dropdown.as
 * @author Abhishek Kumar
 */
package com.engine 
{
 import flash.display.MovieClip;
 
 public class CDropdown 
 {
  private var container:MovieClip;
  private var proceed:Function;
  
  private var controller:CButton;
  private var dropdown:CList;
  private var isopen:Boolean;
  
  public function CDropdown(mc:MovieClip, fn:Function) 
  {
   container = mc;
   proceed = fn;
   
   initialize();
  }
  
  private function initialize():void
  {  
   isopen = false;
   controller = new CButton(container.controller, onCick_controller);
   dropdown = new CList(container.dropdown, onClick_dropdown, 4);
   dropdown.hide();
  }
  
  public function attachListeners():void
  {
   controller.attachListeners();
  }
  
  public function detachListeners():void
  {
   controller.detachListeners();
  }
  
  private function onCick_controller(mc:MovieClip):void
  {
   if (isopen)
   {
    dropdown.hide();
    dropdown.detachListeners();
   }
   else
   {
    dropdown.attachListeners();
    dropdown.show(); 
   }
   isopen = !isopen;
  }
  
  private function onClick_dropdown(mc:MovieClip):void
  {
   proceed(mc);
  }
 }

}

/**
 * @file CList.as
 * @author Abhishek Kumar
 */
package com.engine 
{
 import flash.display.MovieClip;
 
 public class CList 
 {
  private var container:MovieClip;
  private var proceed:Function;
  
  private var items:Array;
  private var itemcount:int;
  
  public function CList(mc:MovieClip, fn:Function, icount:int) 
  {
   container = mc;
   proceed = fn;
   
   itemcount = icount;
   
   initialize();
  }
  
  private function initialize():void
  {  
   items = [];
   for (var i:int = 0; i < itemcount; i++)
   {
    if(container['item' + i].getChildByName('selected') != null)
    {
     container['item' + i].selected.visible = false;
    }    
    items[i] = new CButton(container['item' + i], onClick);
   }
  }
  
  public function attachListeners():void
  {
   for (var i:int = 0; i < itemcount; i++)
   {
    CButton(items[i]).attachListeners();
   }
  }
  
  public function detachListeners():void
  {
   for (var i:int = 0; i < itemcount; i++)
   {
    CButton(items[i]).detachListeners();
   }
  }
  
  private function onClick(mc:MovieClip):void
  {
   for (var i:int = 0; i < itemcount; i++)
   { 
    if(container['item' + i].getChildByName('selected') != null)
    {   
     container['item' + i].selected.visible = (mc.name == 'item' + i);
    }
   }
   proceed(mc);
  }
  
  public function show():void
  {
   container.visible = true;
  }
  
  public function hide():void
  {
   container.visible = false;
  }
  
 }

}

/**
 * @file CButton.as
 * @author Abhishek Kumar
 */
package com.engine 
{
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 public class CButton 
 {
  private var container:MovieClip;
  private var proceed:Function;
  
  public function CButton(mc:MovieClip, fn:Function) 
  {
   container = mc;
   proceed = fn;
   
   initialize();
  }
  
  private function initialize():void
  {   
   container.gotoAndStop('up');
   container.buttonMode = true;
   container.mouseChildren = false;
  }
  
  public function attachListeners():void
  {
   container.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
   container.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
   container.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
   container.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
  }
  
  public function detachListeners():void
  {
   container.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
   container.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
   container.removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
   container.removeEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
  }
  
  private function onMouseUp(me:MouseEvent):void
  {
   container.gotoAndStop('up');
   proceed(me.target);
  }
  
  private function onMouseDown(me:MouseEvent):void
  {
   container.gotoAndStop('down');
  }
  
  private function onMouseOver(me:MouseEvent):void
  {
   container.gotoAndStop('over');
  }
  
  private function onMouseOut(me:MouseEvent):void
  {
   container.gotoAndStop('up');
  }
  
  public function show():void
  {
   container.visible = true;
  }
  
  public function hide():void
  {
   container.visible = false;
  }
  
 }

}

Sunday, January 15, 2012

Blogspot Code Syntax Highlighter

Here is the code to highlight syntax of the code hosted on the blogspot.
<script src="http://yandex.st/highlightjs/6.1/highlight.min.js"></script>
<link rel="stylesheet" href="http://yandex.st/highlightjs/6.1/styles/default.min.css">
<link rel="stylesheet" href="http://yandex.st/highlightjs/6.1/styles/idea.min.css">
<script>
  hljs.initHighlightingOnLoad();
</script>
<br />
<!-- Here will be the description -->
<pre style="border: 1px dashed #CCCCCC; overflow: auto;"><code style="word-wrap: normal;">
<!-- Here will be the source code -->
</code></pre>

PHP: Session based RAM

Here is a session based RAM.
<?
/**
 * @Class: CContainerManager.class.php
 * @Author: Abhishek Kumar (c) 2008.
**/ 

class ContainerManager 
{
 function __construct()
 {
  session_start();
  Get();  
 }
 
 function Get()
 {
  global $Container;
  $Container = array(); 
   
  if (isset($_SESSION['RAM'])) 
  {
   $Container = unserialize($_SESSION['RAM']); 
  }
 }
 
 function Set()
 {
  $_SESSION['RAM'] = serialize($GLOBALS['Container']); 
 }
 
 function Clean()
 {
  if (isset($_SESSION['RAM'])) 
  {
   unset($_SESSION['RAM']);
   unset($GLOBALS['Container']);
  }
 }
 
 function Add($Associate, $Value)
 {
  global $Container;
  if (!isset($Container[$Associate])) 
  {
   $Container[$Associate] = $Value;
   return true;
  }
  else
  {
   return false;
  }  
 }
 
 function Modify($Associate, $Value)
 {
  global $Container;
  if (isset($Container[$Associate])) 
  {
   $Container[$Associate] = $Value;
   return true;
  }
  else
  {
   return false;
  }  
 }
 
 function Delete($Associate)
 {
  global $Container;
  if (isset($Container[$Associate])) 
  {
   unset($Container[$Associate]);
   return true;
  }
  else
  {
   return false;
  }  
 }
}

/*
$V002O = new CContainerManager();

$V002O->Add('kid','hello');
$V002O->Add('kid1','hello1');
$V002O->Add('kid2','hello2');

//$V002O->Clean();
print_r($Container);
//$V002O->Sync();
*/

?>

AS3: Data Transporter

A data tansporter class.
package engine
{
 
 /**
  * @file CTransporter.as
  * @author Abhishek Kumar
  */
 
 import engine.CCommunicator;
 import engine.CTemplate;
 
 import engine.CQuery;
 import engine.CUrl;
 
 public class CTransporter 
 {
  private var oCommunicator:Object;
  private var oTemplate:Object;
  
  /* Ex: 
   * private var oTransporter:Object = new CTransporter();
   */ 
  public function CTransporter():void
  {
   oCommunicator = new CCommunicator();
   oTemplate = new CTemplate();
  }
  
  /* Ex:
   * oTransporter.deliver('URL01', true, 'QT001', { Username:'admin', Password:'pass' }, this.receiver);
   */ 
  public function deliver(iWebService:String, iReturn:Boolean, iQueryName:String, iQueryElement:Object, iReceiver:Function):void
  {
   oCommunicator.setUrl(CUrl.WebAppRoot + CUrl[iWebService]);
   oCommunicator.initialize();
   
   oCommunicator.setProceed(iReceiver);
   
   var queryString:String = oTemplate.setInTemplate(CQuery[iQueryName], iQueryElement);
   oCommunicator.sendDataToServer(iReturn, queryString);   
  }
 }
 
}
package engine
{ 
 import flash.net.navigateToURL;
 import flash.net.URLRequest;
 
 /**
  * @file CUrl.as
  * @author Abhishek Kumar
  */
 
 public class CUrl
 {
  public static var WebAppRoot:String;
  public static var UserAssetPath:String;
  
  public static const WS01:String = "_guru.php";
  
  public static function openUrl(iUrl:String, iWindowType:String):void
  {
   var request:URLRequest = new URLRequest(iUrl);
   try { navigateToURL(request, iWindowType); } catch (e:Error) { };
  }
 }
 
}

AS3: Form Verifier

A form verifier class.
package engine
{ 
 
 /**
  * @file CFormVerifier.as
  * @author Abhishek Kumar
  */
 
 import mx.controls.Alert;
 
 public class CFormVerifier
 {
  private var formItems:Array;
  
  public function CFormVerifier()
  {
   formItems = [];
  }
  
  public function push(itemId:int):void
  {
   formItems[itemId] = 1;
  }
  
  public function pop(itemId:int):void
  {
   formItems[itemId] = 0;
  }
  
  public function check(filledItems:int):Boolean
  {
   for (var i:int = 0, sum:int = 0; i < formItems.length; i++)
   {
    sum += formItems[i];
   }
   return ((sum == filledItems) ? true : false);
  }
  
  public function alert():void
  {   
   Alert.show('Please fill-up all the required fields!', 'Alert');
  }
 }
 
}

AS3: Form Validator

A form validator class
package engine
{ 
 
 /**
  * @file CFormValidator.as
  * @author Abhishek Kumar
  */
 
 import mx.controls.Alert;
 
 public class CFormValidator 
 {
  private var formItems:Array;
  
  public function CFormValidator()
  {
   formItems = [];
  }
  
  private function checkFormId(formId:String):void
  {
   if (formItems[formId] == null)
    formItems[formId] = [];
  }
  
  public function push(formId:String, elementId:Number):void
  {
   checkFormId(formId);
   formItems[formId][elementId] = 1;
  }
  
  public function pop(formId:String, elementId:Number):void
  {
   checkFormId(formId);
   formItems[formId][elementId] = 0;
  }
  
  public function check(formId:String, elementId:Number):Boolean
  {
   checkFormId(formId);
   for (var i:Number = 0, sum:Number = 0; i < formItems[formId].length; i++)
   {
    sum += formItems[formId][i];
   }
   return ((sum == elementId) ? true : false);
  }
  
  public function alert():void
  {   
   Alert.show('Please fill-up all the required fields!', 'Alert');
  }
 }
 
}

AS3: Date-Time Query

A Date-time query methods.
package engine 
{
 /**
  * @file CDateTimeQuery.as
  * @author Abhishek Kumar
  */
 public class CDateTimeQuery
 {
  
  public function CDateTimeQuery() 
  {
   
  }
  
  public static function isExpired(yyyy:Number, mm:Number, dd:Number):Boolean
  {
   var today:Date = new Date();
   var expiry:Date = new Date(yyyy, mm - 1, dd);
   var decision:Boolean = (today > expiry) ? true : false;
   return (decision);
  }
  
  public static function isValid(year:Number, month:Number, date:Number):Boolean
  {
   if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
   {
    return ((date >= 1 && date <= 31)?true:false);
   }
   else if (month == 4 || month == 6 || month == 9 || month == 11)
   {
    return ((date >= 1 && date <= 30)?true:false);
   }
   else if (month == 2)
   {
    if (year%100 == 0)
    {
     return ((year % 400 == 0) ? ((date >= 1 && date <= 29)?true:false) : ((date >= 1 && date <= 28)?true:false));
    }
    else if (year%4 == 0)
    {
     return ((date >= 1 && date <= 29)?true:false);
    }
    else
    {
     return ((date >= 1 && date <= 28)?true:false);
    }
   }
   return false;
  }
 }

}

AS3: Data-tube ... an evolved concept

A data-tube concept based class.
package engine 
{
 /**
  * @file CDataTube.as
  * @author Abhishek Kumar
  */
 public class CDataTube
 {
  
  public function CDataTube() 
  {
   
  }
  
  public function manageItem(iCommand:Boolean, iItem:*, iList:*):Array
  {
   if (iList == undefined)
   {
    iList = [];
    iList = addItem(iItem, iList);
   }
   else
    iList = (iCommand)? addItem(iItem, iList) : deleteItem(isPresent(iItem, iList), iList);
   return iList;
  }
  
  private function addItem(iItem:*, iList:Array):Array
  {
   iList.push(iItem);
   return iList;
  }
  
  private function deleteItem(iIndex:int, iList:Array):Array
  {
   for (var j:int = iIndex; j < iList.length; j++)
    iList[j] = iList[j + 1];
   iList.length--;
   return iList;
  }
  
  private function isPresent(iItem:*, iList:Array):int
  {
   for (var i:int = 0; i < iList.length; i++ )
    if (iList[i] == iItem)
     return i;
   return -1;
  }
  
 }

}

AS3: Cryptography Methods

Few cryptography methods.
package engine 
{
 /**
  * @file CCryptography.as
  * @author Abhishek Kumar
  */
 
 import com.hurlant.util.Hex;
 import com.hurlant.util.Base64;
 
 public class CCryptography
 {
  
  public function CCryptography() 
  {
   
  }
  
  public static function encrypt(iMsg:String):String
  {
   return Hex.fromString(Base64.encode(XOR(iMsg)));
  }
  
  public static function decrypt(iMsg:String):String
  {
   return XOR(Base64.decode(Hex.toString(iMsg)));
  }
  
  private static function XOR(source:String):String 
  {
      var key:String = "HjRUPxRjRUPxRdVDYFdVDFS0HjRUPxRdVDYF6PkFBK3YlXjc";
      var result:String = new String();
      for (var i:Number = 0; i < source.length; i++) 
      {
   if (i > (key.length - 1)) 
   {
       key += key;
   }
   result += String.fromCharCode(source.charCodeAt(i) ^ key.charCodeAt(i));
      }
      return result;
  }
  
 }

}

AS3: Flex to Web-service Communicator

Here is a flex to web-service communicator. It dispatches a package of data to the server and receives the result in response from the server.
package engine
{ 
 
 /**
  * @file CCommunicator.as
  * @author Abhishek Kumar
  */
 
 import mx.rpc.http.HTTPService;
 import com.sephiroth.Serializer;
 import mx.rpc.events.ResultEvent;
 import mx.rpc.events.FaultEvent;
 import mx.controls.Alert;
 import engine.CUtility;
 
 public class CCommunicator
 {  
  private var communicationAgent:HTTPService;
  private var communicationUrl:String;
  private var communicationProceed:Function;
  
  /* Ex:
   * public var oCommunicator:Object = new CCommunicator();
   */
  public function CCommunicator():void
  {
   //trace('CCommunicator');
  }
  
  /* Ex:
   * <mx:HTTPService id="transmittingAgent" url="<url-link>" result="oCommunicator.receiveDataFromServer(event);" fault="oCommunicator.handleCommunicationFault(event);" useProxy="false" method="POST" resultFormat="text" />
   * oCommunicator.setCommunicator(transmittingAgent);
   */
  public function setCommunicator(iEntity:HTTPService):void
  {
   communicationAgent = iEntity;   
  }
  
  /* Ex:
   * oCommunicator.setUrl();
   */
  public function setUrl(iUrl:String):void
  {
   communicationUrl = iUrl;
  }
  
  /* Ex:
   * oCommunicator.setProceed();
   */
  public function setProceed(iProcedure:Function):void
  {
   communicationProceed = iProcedure;
  }
  
  /* Ex:
   * oCommunicator.initialize();
   */
  public function initialize():void 
  {
      communicationAgent = new HTTPService();
      communicationAgent.url = communicationUrl; 
      communicationAgent.method = "POST";
      communicationAgent.addEventListener("result", receiveDataFromServer);
      communicationAgent.addEventListener("fault", handleCommunicationFault);
  }
  
  private function receiveDataFromServer(event:ResultEvent):void
  {
   var receivedDataFromServer:String = CUtility.filter(event.result.toString());
   var extractedInformationFromReceivedData:Object = Serializer.unserialize(unescape(receivedDataFromServer));
   communicationProceed(extractedInformationFromReceivedData);
  }
  
  private function handleCommunicationFault(event:FaultEvent):void
  {
   Alert.show(event.fault.faultString, 'Error');
  }
  
  public function sendDataToServer(iReturn:Boolean, iQuery:String):void
  {
   var packagedData:Object = {COMMAND:iReturn, QUERY:iQuery};
   var transmittingDataToServer:String = Serializer.serialize(packagedData);
   communicationAgent.send({message:transmittingDataToServer});
  } 
 }  
}

package engine
{
 /**
  * @file CUtility.as
  * @author Abhishek Kumar
  */
 public class CUtility
 {  
  public function CUtility() 
  {   
  }  
  public static function filter(iMsg:String):String
  {
   return iMsg.split('+').join(' ');
  }  
 }
}

PHP: Webpage Publisher

A webpage publishing class.
<?php

/**
 * @Class: CPublisher.class.php
 * @Author: Abhishek Kumar
**/

require_once("CTemplate.class.php");
require_once("CFile.class.php");

class CPublisher
{
 private static $oTemplate;

 public static function initialize()
 {
  self::$oTemplate = new CTemplate();
  self::$oTemplate->setTemplatePath('asset/template');
 }

 public static function Publish($iContent, $iInclude)
 {
  self::initialize();

  $Output = 
   self::$oTemplate->ModifyAndDump('Container.dt', 
    array(
    'Header'=>self::getHeader($iInclude),
    'Content'=>self::$oTemplate->ModifyAndDump('ContainerBody.dt', 
      array(
      'Header'=>self::$oTemplate->Dump('Header.st'), 
      'Content'=>$iContent,
      'Footer'=>self::$oTemplate->Dump('Footer.st')
      )
     ),
    )
   );

  return $Output;
 }

 private static function getHeader($iInclude)
 {
  $Output = '';
  if($iInclude != null)
  {
   $oFile = new CFile();
   for($i=0; $igetFileExtension($iInclude[$i]))
    {
     case '.js':  $template = 'JavaScript.dt'; break;
     case '.css': $template = 'StyleSheet.dt'; break;
    }
    $Output .= self::$oTemplate->ModifyAndDump($template, array('FileName'=>$iInclude[$i]));
   }
  }
  return $Output;
 }

 public static function PublishWithoutFooter($iContent, $iInclude)
 {
  self::initialize();

  $Output = 
   self::$oTemplate->ModifyAndDump('Container.dt', 
    array(
    'Header'=>self::getHeader($iInclude),
    'Content'=>self::$oTemplate->ModifyAndDump('ContainerBody.dt', 
      array(
      'Header'=>self::$oTemplate->Dump('Header.st'), 
      'Content'=>$iContent,
      'Footer'=>''
      )
     ),
    )
   );

  return $Output;
 }

}

?>
Example 1:
<?php
// Template#1
require_once('_config.php');

require_once('engine/CPublisher.class.php');
require_once('engine/CTemplate.class.php');

$oTemplate = new CTemplate();
$oTemplate->setTemplatePath('asset/template');

$Output = $oTemplate->ModifyAndDump('foExit.dt', 
 array(
  'ProceedAfterLogout'=>'Login.php'
 ));

echo CPublisher::Publish($Output, array('HojaDeEstilo.css'));

?>
Example 2:
<?php
// Template#2
require_once('_config.php');

require_once('engine/CPublisher.class.php');
require_once('engine/CTemplate.class.php');

$oTemplate = new CTemplate();
$oTemplate->setTemplatePath('asset/content');

$Output = $oTemplate->Dump('CertifiedSeller.st');

echo CPublisher::Publish($Output, array('HojaDeEstilo.css'));

?>

PHP: Image Uploader

Here is an image uploader with re-sizing methods
<?php

/**
 * @file ImageUploader.php
 * @author Abhishek Kumar
**/

$tempFile = $_FILES['Filedata']['tmp_name'];
$fileName = $_FILES['Filedata']['name'];
$fileSize = $_FILES['Filedata']['size'];

$timestamp = date("YmdHis");
$new_fileName = "IMG".$timestamp.strtolower(getFileExtension($fileName));
move_uploaded_file($tempFile, "warehouse/" . $new_fileName);

echo $new_fileName;
 
function getFileExtension($iFile)
{
 $iExtension = strrpos($iFile, ".");
 $oExtension = substr($iFile, $iExtension, strlen($iFile));
 $oString = strtolower($oExtension);
 return $oString;
}

function imageResizer($image)
{
 //$image = "Database/Foto/IMG_001.jpg"; // Name of the source image
 list($PictureWidth, $PictureHeight) = getimagesize($image); // Get original size of source image
 
 $PictureAspectRatio = $PictureWidth/$PictureHeight;

 $Width = 160;
 $Height = 120;
 $AspectRatio = $Width/$Height;
 
 if ($PictureAspectRatio > $AspectRatio)
 {
  $NewWidth = $Width;
  $NewHeight = $Width/$PictureWidth * $PictureHeight;
 }
 else if ($PictureAspectRatio < $AspectRatio)
 {
  $NewWidth = $Height/$PictureHeight * $PictureWidth;
  $NewHeight = $Height;
 }
 else if ($PictureAspectRatio == $AspectRatio)
 {
  $NewWidth = $Width;
  $NewHeight = $Height;
 }
 
 # Generate the resources
 $thumb = imagecreatetruecolor($NewWidth, $NewHeight); // Create resource for thumbnail
 $source = imagecreatefromjpeg($image); // Set the resource for the source image
 
 # Generate the actual thumbnail
 imagecopyresized($thumb, $source, 0,0,0,0, $NewWidth, $NewHeight, $PictureWidth, $PictureHeight); // Generate thumbnail data
 
 # Stream the data to a filename
 imagejpeg($thumb,$image,50); // Stream image to file 'original_thumbnail.jpg'
 
 # Release the memory
 imagedestroy($thumb); // Always remember to clear your resources!
 imagedestroy($source); // Otherwise, you get a "memory leak" 
}

?>

PHP: Directory Handlers

Directory handling methods.
<?php

/**
 * @Class: CDirectory.class.php
 * @Author: Abhishek Kumar
**/

require_once("CTemplate.class.php");
require_once("CFile.class.php");

class CDirectory
{
 private $VoTemplate;
 private $VoCFile;
 private $Avoid;

 public function __construct()
 {
  $this->VoTemplate = new CTemplate();
  $this->VoCFile = new CFile();
  
  $this->Avoid = array();
  $this->Avoid['Directory'] = array();
  $this->Avoid['File'] = array(".", "..");
  $this->Avoid['Extension'] = array();
 }

 public function Directory($iCommand, $iDir) 
 { 
  switch($iCommand)
  {
   case 'CREATE': 
    mkdir($iDir, 0700);
    $oStatus = true;
    break;
   case 'REMOVE': 
    rmdir($iDir);
    $oStatus = true;
    break;
   case 'DELETE': 
    $this->deleteDir($iDir);
    $oStatus = true;
    break;
   default:
    $oStatus = false;
  }
  
  return $oStatus;
 }

 private function deleteDir($dir) 
 { 
  if (substr($dir, strlen($dir)-1, 1) != '/') 
   $dir .= '/'; 
  
  if ($handle = opendir($dir)) 
  { 
   while ($obj = readdir($handle)) 
   { 
    if ($obj != '.' && $obj != '..') 
    { 
     if (is_dir($dir.$obj)) 
     { 
        if (!$this->deleteDir($dir.$obj)) 
         return false; 
     } 
     elseif (is_file($dir.$obj)) 
     { 
        if (!unlink($dir.$obj)) 
         return false; 
     } 
    } 
   } 
   
   closedir($handle); 
  
   if (!@rmdir($dir))
    return false; 
  
   return true; 
  }
  
  return false; 
 }
 
 public function setAvoid($Command, $List)
 {
  switch($Command)
  {
   case 'Directory':
    $this->Avoid['Directory'] = $List;
    break;
   case 'File':
    $this->Avoid['File'] = array_merge($this->Avoid['File'], $List);
    break;
   case 'Extension':
    $this->Avoid['Extension'] = $List;
    break;
  }
 }
 
 public function Explore($iFolder, $iLevel)
 {
  $Directory = opendir("./$iFolder"); 
  
  $TFolderArg = array();
  
  $fileLevelPrefix = $folderLevelPrefix = "\n";
  
  for($i=0; $i<$iLevel; $i++)
  {
   if($i < $iLevel-1)
   {
    $folderLevelPrefix .= "\t";
   }
   $fileLevelPrefix .= "\t";
  }
  
  while (false !== ($Entry = readdir($Directory)))
  {
   $fileExtension = $this->VoCFile->getFileExtensionAlt($Entry);

   if($this->isPresent($Entry, $this->Avoid['File']) == 0 && $this->isPresent($fileExtension, $this->Avoid['Extension']) == 0)
   {
    if($fileExtension == NULL)
    {
     $DiveIn = $iFolder.'/'.$Entry;

     if($this->isPresent($DiveIn, $this->Avoid['Directory']) == 0)
     {
      $TFolderArg['Content'] .= $this->Explore($DiveIn, $iLevel+1);
     }     
    }
    else
    {
     $TFileArg = array();
     $TFileArg['filepath'] = $iFolder.'/'.$Entry;
     $TFileArg['filetype'] = $fileExtension;
     $TFileArg['filename'] = $this->VoCFile->getFileNameAlt($Entry);
     
     $fileTemplate = $fileLevelPrefix.'';
     $TFolderArg['Content'] .= $this->VoTemplate->FitIn($fileTemplate, $TFileArg);
    } 
   }
  }

  closedir();
  
  $TFolderArg['folderpath'] = ($iFolder == "") ? "/." : $iFolder;
  $TFolderArg['foldername'] = $this->getFolderName($TFolderArg['folderpath']);
  $TFolderArg['Content'] = ($TFolderArg['Content'] == NULL) ? "" : $TFolderArg['Content'];
  
  $folderTemplate = $folderLevelPrefix.'[Content]'.$folderLevelPrefix.'';
  $Output = $this->VoTemplate->FitIn($folderTemplate, $TFolderArg);
  
  return $Output;
 }
 
 private function isPresent($sItem, $aDatabase)
 {
  $nOutput = 0;
  for ($i = 0; $i < count($aDatabase); $i++)
  {
   if ($aDatabase[$i] == $sItem)
   {
    $nOutput = 1;
   }
  }
  return ($nOutput);
 }
 
 private function getFolderName($iPath) 
 {
  $oPath = explode("/", $iPath);
  return $oPath[count($oPath)-1];
 }
}
  
/* EXAMPLE:

$handleDir = new CDirectory();
$handleDir->Directory('CREATE','e:/dirname');
$handleDir->Directory('DELETE','e:/dirname');

*/

?>

PHP: File Utilities Methods

Utility methods for file handling.
<?php

/**
 * @Class: CFile.class.php
 * @Author: Abhishek Kumar
**/

class CFile
{
 public function getFileExtension($iFile)
 {
  $iExtension = strrpos($iFile, ".");
  $oExtension = substr($iFile, $iExtension, strlen($iFile));
  $oString = strtolower($oExtension);
  return $oString;
 }

 public function getFileName($iFile)
 {
  $iExtension = strrpos($iFile, ".");
  $oFileName = substr($iFile, 0, $iExtension);
  return $oFileName;
 }

 public function getFileExtensionAlt($str) 
 {
  $i = strrpos($str,".");
  if (!$i) { return ""; }
 
  $l = strlen($str) - $i;
  $ext = substr($str,$i+1,$l);
 
  return $ext;
 }
 
 public function getFileNameAlt($str) 
 {
  $i = strrpos($str,".");
  if (!$i) { return ""; }
 
  $filename = substr($str,0,$i);
 
  return $filename;
 }

 public function CreateFile($iFileName)
 {
  if (!$handle = fopen($iFileName, 'w+'))
  {
   return "Error: Cannot creat file ($iFileName).";
  }
  else
  {
   fclose($handle);
  }
 }

 public function WriteOnFile($iFileName, $iContent)
 {
  // Make sure the file exists and is writable first.
  if (is_writable($iFileName))
  {
    if (!$handle = fopen($iFileName, 'w'))
    {
     $output = "Error: Cannot open file ($iFileName).";
    }
    else
    {
     // Write $iContent to this opened file.
     if (fwrite($handle, $iContent) === false)
     {
      $output = "Error: Cannot write to file ($iFileName).";
     }
     else
     {
      $output = true;     
      fclose($handle);
     }
    }
  }
  else
  {
     $output = "Error: The file ($iFileName) is not writable.";
  }
  
  return $output;
 }  
 
 public function ReadFromFile($iFileName)
 {
  // Make sure the file exists and is readable.
  if (is_readable($iFileName)) 
  {
   if (!$handle = fopen($iFileName, "r"))
   {
      $output = "Error: Cannot open file ($iFileName).";
   }
   else
   {
    $output = fread($handle, filesize($iFileName));
    if ($output === false)
    {
       $output = "Error: Cannot read from file ($iFileName).";
    }
    else
    {
       fclose($handle);
    }
   }
  } 
  else 
  {
   $output = "Error: The file ($iFileName) is not readable.";
  }

  return $output;
 }
 
 public function ReadFromRemoteFile($iFileUrl, $iMethod)
 {
  switch($iMethod)
  {
   case 'OLD':
    $handle = fopen($iFileUrl, "rb");
    $contents = '';
    while (!feof($handle)) 
    {
     $contents .= fread($handle, 8192);
    }
    fclose($handle);
    break;
   default:
    $handle = fopen($iFileUrl, "rb");
    $contents = stream_get_contents($handle);
    fclose($handle);
    break;
  }
 }

 public function AppendInFile($iFileName, $iContent)
 {
  // Make sure the file exists and is writable first.
  if (is_writable($iFileName))
  {
    if (!$handle = fopen($iFileName, 'a'))
    {
     $output = "Error: Cannot open file ($iFileName).";
    }
    else
    {
     // Write $iContent to this opened file.
     if (fwrite($handle, $iContent) === false)
     {
      $output = "Error: Cannot write to file ($iFileName).";
     }
     else
     {
      $output = true;     
      fclose($handle);
     }
    }
  }
  else
  {
     $output = "Error: The file ($iFileName) is not writable.";
  }
  
  return $output;
 }  
}
  
/* EXAMPLE:

$obj = new CFile();
echo $obj->ReadFromFile('config.xml');

*/

?>

PHP: Template Setter

A template setting class for a webpage.
<?php

/**
 * @Class: CTemplate.class.php
 * @Author: Abhishek Kumar
**/

require_once("CFile.class.php");
  
class CTemplate
{
 private $HandleFile;
 private $Template;
 private $TemplatePath;
 
 public function __construct()
 {
  $this->HandleFile = new CFile();
 }
 
 public function __destruct()
 {
  unset($this->HandleFile);
 }

 public function FitIn($iTemplate, $iTemplateArgument)
 {
  $this->Template = $iTemplate;
  $this->Template = $this->setTemplate($iTemplateArgument);
  return $this->Template;
 }

 public function ModifyAndDump($iTemplateName, $iTemplateArgument)
 {
  $this->Template = $this->getTemplate($iTemplateName);
  $this->Template = $this->setTemplate($iTemplateArgument);
  return $this->Template;
 }
 
 public function Dump($iTemplateName)
 {
  $this->Template = $this->getTemplate($iTemplateName);
  return $this->Template;
 }
 
 public function setTemplatePath($iPath)
 {
  $this->TemplatePath = $iPath;
 }

 private function getTemplate($iTemplateName)
 {
  return $this->HandleFile->ReadFromFile($this->TemplatePath.'/'.$iTemplateName); 
 }

 private function setTemplate($iTemplateArgument)
 {
  $iCache = $this->Template;
  foreach($iTemplateArgument as $iKey => $iValue)
  {
   $iTag = $this->createTag($iKey);
   $iCache = str_replace($iTag, $iValue, $iCache);
  }
  return $iCache;
 }
 
 private function createTag($iTagName)
 {
  return '['.$iTagName.']';
 }
}

/* EXAMPLE:

$handleTemplate = new CTemplate();
echo $handleTemplate->ModifyAndDump('Template001', array('Title'=>'Wow', 'Content'=>'What an idea!'));

*/

?>

Saturday, January 14, 2012

PHP: Web-service for communicating with MySQL database

Here is a php to mysql communication gateway packaged as a web-service.

Gateway.php
<?php

require_once('Config.php');
require_once('engine/CMySqlManager.class.php');

$VoCMySqlManager = new CMySqlManager();
$VoCMySqlManager->Connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_SCHEMA);

$_POST['message'] = (!isset($_POST['message']))? null : $_POST['message'];
$_GET['message'] = (!isset($_GET['message']))? null : $_GET['message'];

$C2S_message = ($_POST['message'] == null)? $_GET['message'] : $_POST['message'];
$S2S_information = unserialize(stripslashes(urldecode($C2S_message)));

if(isset($S2S_information->COMMAND) && isset($S2S_information->QUERY))
{
 $S2C_output = array();
 
 $S2C_output = $VoCMySqlManager->Process($S2S_information->QUERY, $S2S_information->COMMAND);
 
 if($S2S_information->COMMAND)
  array_pop($S2C_output);

 echo urlencode(serialize($S2C_output));
 //echo urlencode(serialize($S2S_information->QUERY));
}

?>

Config.php
<?php

$parentDir = dirname(__FILE__);
define('APPROOT',$parentDir.'/');

$serverName = $_SERVER['SERVER_NAME'];
define('WEBROOT','http://'.$serverName.'/test/');

define('DB_HOST', $serverName);
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_SCHEMA', 'test_db');

?>

CMySqlManager.class.php
<?php

/**
 * @Class: CMySqlManager
 * @Author: Abhishek Kumar
**/

class CMySqlManager
{
 public $mysql_host;
 public $mysql_user;
 public $mysql_password;
 public $mysql_database;

 public function Connect($iHost, $iUser, $iPassword, $iDatabase)
 {
  $this->mysql_host = $iHost;
  $this->mysql_user = $iUser;
  $this->mysql_password = $iPassword;
  $this->mysql_database = $iDatabase;
 }

 public function Process($iQuery, $iReturn)
 {
  if($Connection = mysql_connect($this->mysql_host, $this->mysql_user, $this->mysql_password))
   if($Database = mysql_select_db($this->mysql_database))
    if($Result = mysql_query($iQuery))
    {
     if($iReturn)
     {
      while ($Data[] = mysql_fetch_array($Result, MYSQL_ASSOC));
      mysql_free_result($Result);
     }
     mysql_close($Connection);
     return $Data;
    }
    else
     return 'Error# '.mysql_error();  
   else
    return 'Error# '.mysql_error();
  else
   return 'Error# '.mysql_error();
 }
 // deprecated
 public function Execute($iQuery)
 {
  if($Connection = mysql_connect($this->mysql_host, $this->mysql_user, $this->mysql_password))
   if($Database = mysql_select_db($this->mysql_database))
    if($Result = mysql_query($iQuery))
     mysql_close($Connection);
    else
     return 'Error# '.mysql_error();  
   else
    return 'Error# '.mysql_error();
  else
   return 'Error# '.mysql_error();
 }
 // deprecated
 public function Query($iQuery)
 {
  if($Connection = mysql_connect($this->mysql_host, $this->mysql_user, $this->mysql_password))
   if($Database = mysql_select_db($this->mysql_database))
    if($Result = mysql_query($iQuery))
    {
     while ($Data[] = mysql_fetch_array($Result, MYSQL_ASSOC));
     mysql_free_result($Result);
     mysql_close($Connection);
     return $Data;
    }
    else
     return 'Error# '.mysql_error();  
   else
    return 'Error# '.mysql_error();
  else
   return 'Error# '.mysql_error();
 }
}
/*
// Example
require_once('CMySqlManager.php');

$VoCMySqlManager = new CMySqlManager();
$VoCMySqlManager->Connect('localhost','root','password','test');
//$query = "INSERT INTO names VALUES('','Sonali','','Sharma','sonali@gmail.com')";
//$output = $VoCMySqlManager->Execute($query);
$query = 'SELECT * FROM names';
$output = $VoCMySqlManager->Query($query);
//$query = 'SELECT * FROM names';
//$output = $VoCMySqlManager->Process($query, true);

print_r($output);
*/
?>

Thursday, January 12, 2012

Android: Country's ISD Code

Recently, I got a very short missed call from an unknown foreign number. I traced back the location of that number via ISD code. From this, I got the idea of creating a program to detect this on the go (offline). So I'd created the application in flex for android platform.

Below is the snapshot of that application:

Here is a link to download the file:

Link: CountryISDCode.apk

Download it either directly on your mobile-device or transfer it from computer to the device. Then, install it via Application Installer of the device.

Wednesday, January 4, 2012

AS3: Swf Communicator

This class could be used for two-way communication in between parent swf and child swf; where the child swf is loaded inside the parent swf.

SOURCE CODE
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package
{
 import CEvent;
 
 import flash.events.Event;
 import flash.events.IEventDispatcher;
 
 import mx.events.FlexEvent;
 import mx.managers.SystemManager;
 
 import spark.components.Application;
 
 /**
  * @file CSwfCommunicator.as
  * @author Abhishek Kumar
  */
 public class CSwfCommunicator
 {
  public var prepare:Function;
  public var procedure:Function;
  public var proceed:Function;
  
  private var holder:SystemManager;
  
  private var childApp:Application;
  private var childFunc:Function;
  
  public function CSwfCommunicator()
  {
   trace("CSwfCommunicator -> constructor");
  }
  
  public function instantiate(data:*):void
  {
   trace("CSwfCommunicator -> instantiate");
   holder = data as SystemManager;    
   attachListeners(holder);
  }
  
  public function terminate():void
  {
   trace("CSwfCommunicator -> terminate");
   terminateChildApp();
   holder = null;
  }
  
  private function attachListeners(dispatcher:IEventDispatcher):void
  {
   trace("CSwfCommunicator -> attachListeners");
   dispatcher.addEventListener(FlexEvent.APPLICATION_COMPLETE, applicationCompleteHandler);
  }
  
  private function detachListeners(dispatcher:IEventDispatcher):void
  {
   trace("CSwfCommunicator -> detachListeners");
   dispatcher.removeEventListener(FlexEvent.APPLICATION_COMPLETE, applicationCompleteHandler);
  }
  
  private function applicationCompleteHandler(event:FlexEvent):void
  {
   trace("CSwfCommunicator -> applicationCompleteHandler:", event);
   detachListeners(holder);
   initializeChildApp(holder.application);
   if(prepare != null) 
    prepare(holder.application);
  }
  
  // Child App
  
  public function initializeChildApp(data:*):void
  {
   trace("CSwfCommunicator -> initializeChildApp");
   childApp = Application(data);
   attachListeners_childApp(childApp);
  }
  
  public function terminateChildApp():void
  {
   trace("CSwfCommunicator -> terminateChildApp");
   detachListeners_childApp(childApp);
   childApp = null;
  }
  
  private function attachListeners_childApp(dispatcher:IEventDispatcher):void
  {
   trace("CSwfCommunicator -> attachListeners_childApp");
   dispatcher.addEventListener(CEvent.CALL_PARENT_METHOD, callParentMethodHandler);
  }
  
  private function detachListeners_childApp(dispatcher:IEventDispatcher):void
  {
   trace("CSwfCommunicator -> detachListeners_childApp");
   dispatcher.removeEventListener(CEvent.CALL_PARENT_METHOD, callParentMethodHandler);
  }
  
  // Comunicators ... for parent
  
  private function callParentMethodHandler(e:CEvent):void
  {
   trace("CSwfCommunicator -> callParentMethodHandler:", e);
   var o:Object = e.data;
   //trace("CSwfCommunicator -> callParentMethodHandler:", o.method, o.args, o.revert);   
   if(o.revert != null)
   {
    if(procedure != null) 
     callChildMethod(o.revert, procedure(o.method, o.args));
   }
   else
   {
    if(proceed != null) 
     proceed(o.method, o.args);
   }
  }
  
  public function callChildMethod(method:String, args:Object):Object
  {  
   trace("CSwfCommunicator -> callChildMethod:", method, args);
   if (childApp.hasOwnProperty(method))
   {
    childFunc = childApp[method] as Function;
    return childFunc(args);
   }
   return null;
  }
  
  /*
  // Comunicators ... for child
  public function callParentMethod(method:String, param:Object, ack:String):void
  {
   trace("CSwfCommunicator -> callParentMethod:", method, param, ack);
   var o:Object = {
    method: method, 
    args: param, 
    revert: ack
   };
   dispatchEvent(new CEvent(CEvent.CALL_PARENT_METHOD, o));
  }
  */
 }
}

USAGE (Parent)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private function onLoad_ChildSwf():void
{
 var sc:CSwfCommunicator = new CSwfCommunicator();
 sc.procedure = commander1;
 sc.proceed = commander2;
 sc.instantiate(swfholder_sl.content);
}

private function commander1(method:String, o:Object):Object
{
 trace('commander1', method, o);
 var ack:Object = {};
 switch(method)
 {
  case 'foo': ack.text = JSON.encode(o);
   break;
 }
 return ack;
}

private function commander2(method:String, o:Object):void
{
 trace('commander2', method, o);
 switch(method)
 {
  case 'foo': display_lbl.text = JSON.encode(o);
   break;
 }
}

USAGE (Child)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import CEvent;
import CSwfCommunicator;

// Important Method
public function callParentMethod(method:String, param:Object, ack:String):void
{
 trace("callParentMethod:", method, param, ack);
 var o:Object = {
  method: method, 
  args: param, 
  revert: ack
 };
 dispatchEvent(new CEvent(CEvent.CALL_PARENT_METHOD, o));
}

protected function btn_clickHandler(event:MouseEvent):void
{
 callParentMethod('foo', {a:1, b:2}, 'acknowledge');
}

public function acknowledge(o:Object):void
{
 display_tb.text = o.text;
}