768x90 Getting Online Shouldn't be Tough- $7.49 .com Domains at Go Daddy

How to make Air Application become iPhone SDK

Adobe air is great and smooth desktop application, many developers of Air dream their application can be installed into iPhone SDK. Now that dream come true. Thanks to my friend auraAnar for this great information :

First thing you do is downloading editor Eclips (like Flex Builder) from openplug.com, once you have successfully download it, create new project, in this show case i would to create sample parking searcher based on google Map for iPhone SDK.


Preview builder application

  1. Create WindowedApplication example project name is parkingApp.mxml
  2. Design indexView for iPhone application, let's called it as indexView.mxml (click the link)
  3. For component you can use mx:xxx like Flex or Air, but for control you should use mob:xxx from openPlug. Take a look my textinput Here
  4. Here is the screenshot of iPhone Emulator :


Preview Emulator


Once you success compiling your script without error, you need XCode of Apple to compile your script to iPhone SDK, i am using this way to compile my script in XCode. Happy iPhoning.

PS: I've tried commiting my script to google codes but it seems the google SVN is under maintenance, once it works i will upload the sample codes. Here is the address:

svn checkout http://airiphone.googlecode.com/svn/trunk/

AutoLogin to google account in Air without Oauth

i believe a part number of you there want their application allow the user to enter google account credential information to access the page, right? It's like i were faced off in my project. So how we will do it ?

If you use webservice, here's the information you should send to air application :
Google Account Credential Information and CallBack Url (the next url you want go after login)
I believe to access protected google page it will asked thridparty login, right? Note: OAuth, AuthSub and ClientLogin will not allow you to remote interface specially page after login google. In this case i create a component which is called GoogleBrowser.mxml and here the codes:

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

     <mx:Window xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" 
                   width="600" height="600" backgroundColor="#242424"
                   creationComplete="init()"  >

     <mx:Script>
      <![CDATA[
         private var googleUserName:String = "yacobus.r@kiranatama.com";
         private var googlePassword:String = "i_love_u";
         private var nextUrl:String = "http://docs.google.com/a/kiranatama.com/Doc?docid=0AWbobJ8BSfPlZGcyaGtiYmJfMjlkajlwc3hncw&hl=en";  

         private function init():void{
           browserStack.selectedIndex = 1;
           gdocHtml.addEventListener(Event.COMPLETE, onCompleteHandler);
           gdocHtml.location = nextUrl;
         }

   
         private function onCompleteHandler(event:Event):void{
           gdocHtml.removeEventListener(Event.COMPLETE, removeListenerHandler);
           var additionalScript:String = '<script type="text/javascript">\n'+
                                   "gaia_setFocus();\n" + 
                                   "document.gaia_loginform.submit();\n"+
                                   "</script>";
           var username:String = googleUserName.split("@")[0];
           var body:String = String(event.target.htmlLoader.window.document.body.innerHTML);
           body = body.replace('id="Passwd"','id="Passwd" value="'+googlePassword+'" ');
           body = body.replace('value="" class','value="'+username+'" class"');
           body = body + addScript;
           gdocHtml.htmlLoader.window.document.body.innerHTML = body;
           browserStack.selectedIndex = 0;
          }

           private function removeListenerHandler(event:Event):void{
              event.stopPropagation();
           }

        ]]>
      </mx:Script>

      <mx:ViewStack id="browserStack" width="100%" height="100%">
        <mx:Canvas width="100%" height="100%">
          <mx:HTML width="100%" height="100%" id="gdocHtml" />    
        </mx:Canvas>
        <mx:Text id="loadingText" text="Loading ..." />
      </mx:ViewStack>  
</mx:Window>

Autocomplete from arrayCollection data in Flex and Air

Autocomplete is still high traffic in search engine for flex or action script, although it has plugin or component now (FLEX 4 is available). But now i would like to share you my script about how find documents, which is stored in arrayCollection and reflect with autocomplete textInput. here the sample code :

CASE:
In a form there's Multiple selection List the List can be clicked multiply or can be selected using auto complete in text input. the List dataProvider is from arrayCollection. The arrayCollection is filled by data from database.

  <mx:VBox
     xmlns:mx = "http://www.adobe.com/2006/mxml"
     width = "100%"
     height = "100%"
     creationComplete = "{onComplete()}" >

  <mx:Script>
      <![CDATA[

   private var docDummyData:ArrayCollection = new ArrayCollection(
                              [{id:234, title:"qwerty data"}], 
                              [{id:1020, title:"employee data"}],
                              [{id:1033, title:"salary data"}],
                              [{id:643, title:"tomorrow presentation"}],
                              [{id:721, title:"kiranatama human resource"}],
                              [{id:162, title:"flex and air outsource"}],
                              [{id:905, title:"ruby on rails docs"}],
                              [{id:453, title:"and many more"}]);

    private var copyData:ArrayCollection = new ArrayCollection;

    private function onComplete():void{
      copyData = docDummyData;
      docDummyData.sort = sortDoc();
      docDummyData.refresh();
      listDocuments.dataProvider = docDummyData;
    }

    private function sortDoc():Sort{
       var mySort:Sort = new Sort();
       var sortLevel:SortField = new SortField("title");
       sortLevel.numeric = false;
       sortLevel.descending = false;
       mySort.fields = [sortLevel];
       return mySort;
    }

    private function filterTitle(item:Object):Boolean
    {
      var arrTxtDocs:Array = txtGDocs.text.split(", ");
      var keyWord:String = String(arrTxtDocs[arrTxtDocs.length-1]);
      listDocuments.scrollToIndex(0); // scrolled the top item
      i++;
      return item['title'].match(new RegExp(keyWord,"i")); 
    }

    private function onTyping():void{
      if(listDocuments.dataProvider != null){
        docDummyData.filterFunction = filterTitle;
        docDummyData.refresh();
       }
    }

    private function detectEnter(event:KeyboardEvent):void{

       if(event.charCode == 13){
         listDocuments.selectedIndex = i;
        if(docDummyData.length < 1){
         Alert.show("This Document is not exist or invalid");   
        }else{
         var arrInputDoc:Array = txtGDoc.text.split(",");
         arrInputDoc[arrInputDoc.length-1] = String(listDocuments.selectedItem.title)+ ", ";
         txtGDoc.text = arrInputDoc.join(", ");
         docDummyData = copyData;
         docDummyData.refresh();
         listDocuments.invalidateDisplayList();
        }
      }
    }

    private function onSelectDocs(event:ListEvent):void{
       var arrDocTitles:Array = listDocuments.selectedItems;
       var strText:String = txtGDocs.text;

       for(var i:int = 0; i < arrDocTitles.length;i++){
         var nameTitle:String = arrDocTitles[i].title.toString();
         txtGDocs.text += nameTitle+ ', ';
       }
     }
   ]]>
  </mx:Script>

  <mx:Text  text="Please enter your document title" width="100%"/>
  <mx:TextInput width="100%"
           id="txtGDocs"
           change="{onTyping()}"
           keyDown="detectEnter(event)"/>

   <mx:List id="listDocuments"
      labelField="title"
      rowCount="5"
      itemClick="{onSelectDocs(event)}"
      width="100%" 
     allowMultipleSelection="true"/>         
  </mx:VBox>        



That's all :), any body know how to make code sniped like wordpress in blogspot ?

Servicing Restful CakePHP in Flex/Air

I have found a great framework of Dima Berastau which is called Restfulx, this framework is helping you to abstract your application from repetitive CRUD code and switch/synchronize between various data providers with minimal effort, very suitable for Ruby on rails and Phyton(Django) Developers. What about PHP?

Honestly Restfulx is suitable for php developer like CakePHP, CodeIgniter or any MVC and Restful framework as their webservice in flex or Air. But now I would like to share about simple Restful webservice utility for php framework, my handmade, if i get wrong please send me feedback correction.

The main idea of using is :
//http://localhost/baking_cake/users/?first_name=yacobus

RestfulPhp.index(User,{first_name: "yacobus"}, onIndexSuccess, onIndexFailure);


//http://localhost/baking_cake/users
  var params:Object = new Object;
  params.first_name = "yacobus";
  params.last_name = "reinhart";
  params.current_company = "kiranatama.com";
  RestfulPhp.add(User,params, onCreateSuccess, onCreateFailure);



  //http://localhost/baking_cake/users/7.xml
  var params:Object = new Object;
  params.id = "7";
  params.first_name = "yacobus";
  params.last_name = "reinhart";
  params.current_company = "www.wgs.co.id";
  RestfulPhp.edit(User,params, onEditSuccess, onEditFailure);


  //http://localhost/baking_cake/users/7.xml
  RestfulPhp.show(User,{id: "7"}, onShowSuccess, onShowFailure);

  //http://localhost/baking_cake/users/7.xml
  RestfulPhp.delete(User,{id: "7"}, onDeleteSuccess, onDeleteFailure);

First step and the last are :

you should create utility class or any class name that will have function as webservice, for example : I create RestfulPhp in com.reinhartlab.share


package com.teapoci.share
{
  import flash.utils.getQualifiedClassName;
  import mx.messaging.messages.HTTPRequestMessage;
  import mx.rpc.events.FaultEvent;
  import mx.rpc.events.ResultEvent;
  import mx.rpc.http.HTTPService;

  public class RestfulPhp {

    private static var restful:RestfulPhp;
    private static var baseURL:String = "http://localhost/baking_cake/";
    public static function getInstance():RestfulPhp {
      (restful == null) ? restful = new RestfulPhp();
      return restful;
    }

    public function index(model:Class, params:Object = null, successFunction:Function = null, faultFunction: Function = null, resultFormat:String = "e4x"):void
    {
      var sendData:XML = ;
      var httpService : HTTPService = new HTTPService();
      httpService.contentType = "text/xml";
      httpService.method = HTTPRequestMessage.GET_METHOD;
      doHttpService(model, httpService, "GET", resultFormat, params, successFunction,  faultFunction);
     }

     public function add(model:Class, resultFormat:String = "e4x"):void{
       var sendData:XML = ;
       var httpService : HTTPService = new HTTPService();
       httpService.contentType = "text/xml";
       httpService.method = HTTPRequestMessage.POST_METHOD;
       doHttpService(model, httpService, "POST", resultFormat, params, successFunction, faultFunction);
     }

     public function edit(model:Class, params:Object = null, successFunction:Function = null, faultFunction: Function = null, resultFormat:String = "e4x"):void
     {
        var sendData:XML = ;
        var httpService : HTTPService = new HTTPService();
        httpService.contentType = "text/xml";
        httpService.method = HTTPRequestMessage.PUT_METHOD;
        doHttpService(model, httpService, "PUT", resultFormat, params, successFunction, faultFunction);
     }

     public function delete(model:Class, params:Object = null, successFunction:Function = null, faultFunction: Function = null, resultFormat:String = "e4x"):void
     {
         var httpService : HTTPService = new HTTPService();
         httpService.contentType = "text/xml";
         httpService.method = HTTPRequestMessage.DELETE_METHOD;
         doHttpService(model, httpService, "DELETE", resultFormat, params, successFunction, faultFunction);
     }

     public function show(model:Class, params:Object = null, successFunction:Function = null, faultFunction: Function = null, resultFormat:String = "e4x"):void
     {
         var httpService : HTTPService = new HTTPService();
         httpService.contentType = "text/xml";
         httpService.method = HTTPRequestMessage.GET_METHOD;
         doHttpService(model, httpService, "GET", resultFormat, params, successFunction, faultFunction);
     }

     private function doHttpService(_model:Class, _service:HTTPService, _method:String, _format:String, _params:Object,_onSuccess:Function, _onFailure:Function):void
     {         
         var sendData:XML = ;
         (_params!= null) ? sendData.appendChild(_params);
         var controllerUrl:String = flash.utils.getQualifiedClassName(_model)+"s";
         _service.url =  baseURL + controllerUrl;
        if(_method != "POST" && _params.id != null){
        _service.url = _service.url + "/" + String(_params.id)+".xml";
      }
             

     _service.headers = {"REQUEST_METHOD": _method,
                         "X_HTTP_METHOD_OVERRIDE": _method};
     _service.resultFormat = _format;
     _service.addEventListener( ResultEvent.RESULT, _onSuccess);

     if(_onFailure != null )
       _service.addEventListener( FaultEvent.FAULT, _onFailure );

     _service.send( sendData ); 

   }
  }
}             

Resize image to squared in CakePHP

The code is almost closer with my previous article, just change function resize_image to square_image


function crop_img($imgname, $scale, $filename) {

$filetype = $this->getFileExtension($imgname);

$filetype = strtolower($filetype);


switch($filetype){


case "jpeg":


case "jpg":


$img_src = ImageCreateFromjpeg ($imgname);


break;


case "gif":


$img_src = imagecreatefromgif ($imgname);


break;


case "png":


$img_src = imagecreatefrompng ($imgname);


break;


}


$width = imagesx($img_src);


$height = imagesy($img_src);


$ratiox = $width / $height * $scale;


$ratioy = $height / $width * $scale;


//-- Calculate resampling


$newheight = ($width <= $height) ? $ratioy : $scale;


$newwidth = ($width <= $height) ? $scale : $ratiox;


//-- Calculate cropping (division by zero)


$cropx = ($newwidth - $scale != 0) ? ($newwidth - $scale) / 2 : 0;


$cropy = ($newheight - $scale != 0) ? ($newheight - $scale) / 2 : 0;


//-- Setup Resample & Crop buffers


$resampled = imagecreatetruecolor($newwidth, $newheight);


$cropped = imagecreatetruecolor($scale, $scale);


//-- Resample


imagecopyresampled($resampled, $img_src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);


//-- Crop


imagecopy($cropped, $resampled, 0, 0, $cropx, $cropy, $newwidth, $newheight);


// Save the cropped image


switch($filetype)


{


case "jpeg":


case "jpg":


imagejpeg($cropped,$filename,80);


break;


case "gif":


imagegif($cropped,$filename,80);


break;


case "png":


imagepng($cropped,$filename,80);


break;


}


}

function crop_img($tempFile, $scale, $newFile) {

$filetype = $this->getFileExtension($tempFile);

$filetype = strtolower($tempFile);

switch($filetype) {

case "jpeg":

case "jpg":

 $img_src = imagecreatefromjpeg($tempFile);

 break;

case "gif":

$img_src = imagecreatefromgif ($tempFile);

break;

case "png":

$img_src = imagecreatefrompng ($tempFile);

case "bmp":

$img_src = imagecreatefromwbmp ($tempFile);

break;

}

$width = imagesx($img_src);

$height = imagesy($img_src);

$scale = explode('x',strtolower($size));

$ratiox = $width / $height * $scale[0];

$ratioy = $height / $width * $scale[0];

//-- Calculate resampling

$newheight = ($width <= $height) ? $ratioy : $scale[0];

$newwidth = ($width <= $height) ? $scale[0] : $ratiox;

//-- Calculate cropping (division by zero)

$cropx = ($newwidth - $scale != 0) ? ($newwidth - $scale) / 2 : 0;

$cropy = ($newheight - $scale != 0) ? ($newheight - $scale) / 2 : 0;

//-- Setup Resample & Crop buffers

$resampled = imagecreatetruecolor($newwidth, $newheight);

$cropped = imagecreatetruecolor($scale[0], $scale[0]);

//-- Resample

imagecopyresampled($resampled, $img_src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

//-- Crop

imagecopy($cropped, $resampled, 0, 0, $cropx, $cropy, $newwidth, $newheight);

// Save the cropped image

switch($filetype)

{

case "jpeg":

case "jpg":

imagejpeg($cropped,$newFile,80);

break;

case "gif":

imagegif($cropped,$newFile,80);

break;

case "png":

imagepng($cropped,$newFile,80);

break;

}

}

Upload and Resize Image in CakePHP

I have spent many hours to see articles about resizing and uploading image in cakePHP, almost of them are sounding sucks for me like resizing on View by accessing or injecting the url or copy paste by another written without testing code. Event I was trying to convert AkImage from Akelos (Closer to ImageMagick in Rails) but got bunch of errors.

Any way i got article from sobbour website, but i am not satisfied with the code because the component automatically resize for big and thumb by 2 method directly, it will make bounced my hosting with trash image. And some lines were not realible any more with CakePHP, here is my modified Code (save it to /appName/controller/components/image.php)

class ImageComponent extends Object
{
var  $contentType =  array('image/jpg','image/bmp','image/jpeg','image/gif','image/png','image/pjpg','image/pbmp','image/pjpeg','image/ppng','image/pgif');
function  upload_image_and_thumbnail($fileData,$size,$subFolder,$prefix) {
if  (strlen($fileData['name'])>4)
 {
$error =  0;
$destFolder =  WWW_ROOT.$subFolder;
$realFileName  = $fileData['name'];
if(!is_dir($destFolder))  mkdir($destFolder,true);
  $filetype = $this->getFileExtension($fileData['name']);
$filetype  = strtolower($filetype);
if(!in_array($fileData['type'],$this->contentType)){
return false;exit();
}
else if($fileData['size'] > 700000 ){
return false;exit();
}
else
{
$imgsize =  GetImageSize($fileData['tmp_name']);
}
 if  (is_uploaded_file($fileData['tmp_name']))
 {
if  (!copy($fileData['tmp_name'],$destFolder.'/'.$realFileName ))
{
 return false;
exit();
}
else  {
  $this->resize_img($destFolder.'/'.$realFileName, $size,  $destFolder.'/'.$prefix.$realFileName);
 unlink($destFolder.'/'.$realFileName);
 }
 }
return  $fileData;
}
}
function delete_image($filename)
{
unlink($filename);
}
function  resize_img($tempFile, $size, $newFile)
{
$filetype =  $this->getFileExtension($tempFile);
$filetype =  strtolower($filetype);
switch($filetype) {
case "jpeg":
case "jpg":
 $img_src  = imagecreatefromjpeg($tempFile);
 break;
case "gif":
$img_src = imagecreatefromgif  ($tempFile);
break;
case "png":
$img_src = imagecreatefrompng  ($tempFile);
 case "bmp":
$img_src = imagecreatefromwbmp  ($tempFile);
break;
}
$true_width  = imagesx($img_src);
$true_height = imagesy($img_src);

$size = explode('x',strtolower($size));
if  ($true_width>=$true_height)
{
 $width=$size[0];
 $height =  ($width/$true_width)*$true_height;
}
else
{
 $height=$size[1];
 $width =  ($height/$true_height)*$true_width;
}
$img_des =  imagecreatetruecolor($width,$height);
imagecopyresampled  ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width,  $true_height);
// Save the resized image
switch($filetype)
{
 case "jpeg":
 case "jpg":
 imagejpeg($img_des,$newFile,80);
 break;
 case "gif":
 imagegif($img_des,$newFile,80);
break;
case  "png":
imagepng($img_des,$newFile,80);
case "bmp":
imagewbmp($img_des,$newFile,80);
break;
}
}
function  getFileExtension($str)
{
$i  = strrpos($str,".");
if (!$i) { return ""; }
$l =  strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
}


class  ImageComponent extends Object

{

var  $contentType =  array('image/jpg','image/bmp','image/jpeg','image/gif','image/png','image/pjpg','image/pbmp','image/pjpeg','image/ppng','image/pgif');

function  upload_image_and_thumbnail($fileData,$size,$subFolder,$prefix) {

if  (strlen($fileData['name'])>4)

 {

$error = 0;

$destFolder = WWW_ROOT.$subFolder;

$realFileName = $fileData['name'];

if(!is_dir($destFolder))  mkdir($destFolder,true);

 $filetype =  $this->getFileExtension($fileData['name']);

$filetype  = strtolower($filetype);

if(!in_array($fileData['type'],$this->contentType)){

return false;exit();

}

else if($fileData['size'] >  700000 ){

return  false;exit();

}

else

{

$imgsize =  GetImageSize($fileData['tmp_name']);

}

 if  (is_uploaded_file($fileData['tmp_name']))

 {

if  (!copy($fileData['tmp_name'],$destFolder.'/'.$realFileName ))

{

 return false;

exit();

}

else  {

  $this->resize_img($destFolder.'/'.$realFileName, $size,  $destFolder.'/'.$prefix.$realFileName);

  unlink($destFolder.'/'.$realFileName);

 }

 }

return $fileData;

}

}

function  delete_image($filename)

{

unlink($filename);

}

function  resize_img($tempFile, $size, $newFile)

{

$filetype =  $this->getFileExtension($tempFile);

$filetype =  strtolower($filetype);

switch($filetype) {

case "jpeg":

case "jpg":

 $img_src  = imagecreatefromjpeg($tempFile);

 break;

case "gif":

$img_src = imagecreatefromgif  ($tempFile);

break;

case "png":

$img_src = imagecreatefrompng  ($tempFile);

  case "bmp":

$img_src  = imagecreatefromwbmp ($tempFile);

break;

}

$true_width  = imagesx($img_src);

$true_height = imagesy($img_src);



$size =  explode('x',strtolower($size));

if  ($true_width>=$true_height)

{

 $width=$size[0];

 $height =  ($width/$true_width)*$true_height;

}

else

{

 $height=$size[1];

 $width =  ($height/$true_height)*$true_width;

}

$img_des =  imagecreatetruecolor($width,$height);

imagecopyresampled  ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width,  $true_height);

// Save the resized image

switch($filetype)

{

 case "jpeg":

 case "jpg":

 imagejpeg($img_des,$newFile,80);

 break;

 case "gif":

 imagegif($img_des,$newFile,80);

break;

case  "png":

imagepng($img_des,$newFile,80);

case  "bmp":

imagewbmp($img_des,$newFile,80);

break;

}

}

function  getFileExtension($str)

{

$i = strrpos($str,".");

if  (!$i) { return ""; }

$l = strlen($str) - $i;

$ext  = substr($str,$i+1,$l);

return $ext;

}

}

And in your class instance method , run this line

<?php
class DeJavu extends Appcontroller {
var $components = array("Image");
function add(){
....any code....
$this->Image->upload_image_and_thumbnail($this->data['Webinfo']['file'],'150x150','img','logo_');
....any code....
}
}
?>

now I am happy to see my app can resize image without annoying script any more. Good Luck for you too.

SharedObject in Sever Using NetConnection or by Remote

A few days ago i have problem how to implement my live streaming using SharedObject in Red5 because usually SharedObject, as i know, only good implementable for local only (like getting or store cookies), before implemented to my live streaming application, i created simple chat application to remote SharedObject :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
<mx:Script source="streaming.as"/>
<mx:TextInput x="10" y="10" id="rtmpUrl" text="your rtmp address"/>
<mx:Button x="216" y="10" id="connectBtn"/>
<mx:TextInput x="10" y="269" id="enterMsg" />
<mx:TextArea x="10" y="40" height="221" id="msgBoard" width="222" />
<mx:Button x="178" y="269" id="sendBtn"/>
</mx:Application>

And now let create streaming.as script :
import flash.events.MouseEvent;
import flash.events.NetStatusEvent;
import flash.events.SyncEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.SharedObject;

import mx.controls.Alert;

public var NetCont:NetConnection;
public var NetStrem:NetStream
public var SharObj:SharedObject;

public function creationComplete():void{
connectBtn.label = "Connect";
connectBtn.addEventListener(MouseEvent.CLICK, ConnectServer);

sendBtn.label = "Send";
sendBtn.addEventListener(MouseEvent.CLICK, SendChat);
}

public function ConnectServer(event:MouseEvent):void{
NetCont = new NetConnection();
NetCont.client = new NetConnectionClient;
NetCont.connect(rtmpUrl.text);
NetCont.addEventListener(NetStatusEvent.NET_STATUS, createSharedObject);
}

public function createSharedObject(event:NetStatusEvent):void{

if(NetCont.connected){
SharObj = SharedObject.getRemote("SampleMessage",NetCont.uri,false,false);
SharObj.connect(NetCont);
SharObj.addEventListener(SyncEvent.SYNC, SharObjView);


}else{

Alert.show('Unable to Connect Internet or Rtmp Address');


}
}


public function SharObjView(event:SyncEvent):void{
msgBoard.htmlText += SharObj.data['SampleMessage']+"<br>";

}

public function SendChat(event:MouseEvent):void{
SharObj.setProperty("SampleMessage",enterMsg.text);
}

There are 2 optional for using SharedObject in ActionScript specially for flex SharedObject.getLocal() method or the SharedObject.getRemote()

What we use for internet connection is using getRemote. And here is code for next connection client :
package
{
public class NetConnectionClient
{
public function NetConnectionClient()
{
}
public function onBWDone(... rest):void
{

}
public function onBWCheck(... rest):uint
{
//have to return something, so returning anything :)
return 0;
}

public function onMetaData(info:Object):void {
trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
}
}
}

Anti Spam Email For Your Rails Page with Javascript

In your view : <%= js_antispam_email_link('username@domain.com') %>


Code for your helper


# Takes in an email address and (optionally) anchor text,

# its purpose is to obfuscate email addresses so spiders and

# spammers can't harvest them.

def js_antispam_email_link(email, linktext=email)

user, domain = email.split('@')

user = html_obfuscate(user)

domain = html_obfuscate(domain)

# if linktext wasn't specified, throw encoded email address builder into js document.write statement

linktext = "'+'#{user}'+'@'+'#{domain}'+'" if linktext == email

rot13_encoded_email = rot13(email) # obfuscate email address as rot13

out = "#{linktext}&lt;br/&gt;&lt;small&gt;#{user}(at)#{domain}&lt;/small&gt;\n" # js disabled browsers see this

out += "// <![CDATA[

\n"

out += " \n"

out += " string = '#{rot13_encoded_email}'.replace(/[a-zA-Z]/g, function(c){ return String.fromCharCode((c = (c = c.charCodeAt(0) + 13) ? c : c - 26);});\n"

out += " document.write('#{linktext}'); \n"

out += " //\n"

out += "

// -->

// ]]>\n"

return out

end


private

# Rot13 encodes a string

def rot13(string)

string.tr "A-Za-z", "N-ZA-Mn-za-m"

end


# HTML encodes ASCII chars a-z, useful for obfuscating

# an email address from spiders and spammers

def html_obfuscate(string)

output_array = []

lower = %w(a b c d e f g h i j k l m n o p q r s t u v w x y z)

upper = %w(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

char_array = string.split('')

char_array.each do |char|

output = lower.index(char) + 97 if lower.include?(char)

output = upper.index(char) + 65 if upper.include?(char)

if output

output_array << "&##{output};"

else

output_array << char

end

end

return output_array.join

end

Move To Word Press

I Recently Move my Blog To Wordpress --> inobject.wordpress.com

Track Total Coverage of Your Test Unit Code with RCOV

Hi All :

I just want share my testing with Ruby coverage code or Rcov. It is fun (for me, dont know for others) playing with Rcov report, i think it is like bugs tracking but i dont know other people called it or maybe it is like tool to coverage test your application codes.

First think you have to do is installing the gem :

gem install rcov

and then write simple code to run it as rake then save it in your_app/lib/tasks :

require 'rcov/rcovtask'

namespace :test do
namespace :coverage do

desc "Delete aggregate coverage data."

task(:clean) { rm_f "coverage.data" }
end

desc 'Aggregate code coverage for unit, functional and integration tests'

task :coverage => "test:coverage:clean"

%w[unit functional integration].each do |target|

namespace :coverage do

Rcov::RcovTask.new(target) do |t|
t.libs << "test"
t.test_files = FileList["test/#{target}/*_test.rb"]
t.output_dir = File.dirname(__FILE__)+"/report_rcov/#{target}"
t.verbose = true
t.rcov_opts << '--rails --aggregate coverage.data'
end
end

task :coverage => "test:coverage:#{target}"

end

system(" \"C:/Program Files/Mozilla Firefox/firefox.exe\" " +
"file:///"+File.dirname(__FILE__)+"/report_rcov/unit/index.html")

end


Absolutly i am using windows if you are using another OS not windows you could change the 4th line from bottom to :

system(open File.dirname(__FILE__)+"/report_rcov/unit/index.html")


Open your shell or CMD then execute rake test:coverage or open rake -T

rake test:coverage # Aggregate code coverage for unit,...
rake test:coverage:clean # Delete aggregate coverage data.
rake test:coverage:clobber_functional # Remove rcov products for functional
rake test:coverage:clobber_integration # Remove rcov products for integration
rake test:coverage:clobber_unit # Remove rcov products for unit
rake test:coverage:functional # Analyze code coverage with tests ...
rake test:coverage:integration # Analyze code coverage with tests ...
rake test:coverage:unit # Analyze code coverage with tests ...



Here I attached sample report from rcov. I hope this written can be useful for you gentleman and ladies.

Step by step to deploy application using SVN and Capistrano

Here process deploying of application in a hosting (in this case i deploy my application in FastCGI on HostingRails.com). There are 3 major steps of deployment :


  1. Create SVN Repository (Next I will explain about GIT)
  2. Setup Capistrano & Deploy Application with Capistrano


Create SVN Repository

  • Create REPOSITORY to your hosting account, please ensure that your hosting is already installed capistrano & SVN or ask your hosting admin/support to install SVN and Capistrano.
username@mydomain.com [~]$ mkdir -p ~/svn/your_app_name
username@mydomain.com [~]$ svnadmin create ~/svn/your_app_name
username@mydomain.com [~]$ mkdir -p ~/tmp/your_app_name/{tags,branches,trunk}
username@mydomain.com [~]$ svn import ~/tmp/your_app_name file:///home/username/svn/your_app_name -m "Created Repository"

  • At this point you have enough setup on your Hosting account for single-user access to Subversion. You can now check out your repository at:
username@mydomain.com [~]$ svn co svn+ssh://username@mydomain.com/home/username/svn/your_app_name/trunk

  • Next we are going to add your existing Rails app to the Subversion repository. If you don't have an existing app, you will need to create one.
username@mydomain.com [~]$ svn co svn+ssh://username@mydomain.com/home/username/svn/your_app_name/trunk your_app_name_dev

  • Ok, it looks fine if you do right. The next step is copy your application for repository. Before this process, upload your existing application folder to your host in zip or tar.gz file. After uploaded, extract it to up folder of public_html (do not extract your application in public_html). After extracting, we will modify some data and permission file.

  • Your database.yml(.online) file simply needs to look like this:

production:
 adapter: mysql
 database: [your_hosting_username]_[your_database_name]
 username: [your_hosting_username] OR [your_hosting_username]_[your_database_name]
 password: your_password


  • And in your environment.rb(.online) file you'll just need to uncomment the following line to confirm you're in production mode:
ENV['RAILS_ENV'] ||= 'production'

  • Make sure your .htaccess file sends requests to dispatch.fcgi. Please Note - as of Rails 2.1.0 the .htaccess file no longer exists in the default skeleton.  Run a "rails _2.0.2_ testapp" and move over the public/.htacess from there.  This one is easy but also critically important.   In your local Rails application's public/.htaccess file change the :

RewriteRule ^(.*)$ dispatch.cgi [QSA,L]

  • EXACTLY where it is already in the file, don't change its position, to: 
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

  • also - very important make sure the 'AddHandler fastcgi-script .fcgi' is commented out at the top of your .htaccess:  
    # General Apache options
    # AddHandler fastcgi-script .fcgi
    And that's it

  • Now look into public folder and edit all files with name "dispatch" (they are 3 files), edit the first line and change to :
#!/usr/local/bin/ruby

  • Do not forget to change permission into 755 for all files in public folder specially all dispatch.* files and .htaccess.

  • Next, you will need to copy your existing Rails app on your local machine into the version we just checked out
username@mydomain.com [~]$ cp -R your_app_name/* your_app_name_dev

  • Now you can see if Subversion recognizes the updated files and directories:
username@mydomain.com [~]$ cd your_app_name_dev
username@mydomain.com [~/your_app_name_dev]$ svn status

  • You should get something like this:

?      test
?      app
?      tmp
?      log
?      Rakefile
?      script
?      components
?      config
?      db
?      doc
?      lib
?      README
?      vendor
?      public


  • Now, just add them to the repository:

username@mydomain.com [~/your_app_name_dev]$ svn add test app tmp log Rakefile script components config db doc lib README vendor public

  • You will see a list of the files that were added with an 'A' next to indicating that the files will be added on the next commit. You will see something like this:

A         test
A         test/fixtures
A         test/fixtures/contact_mailer
A         test/fixtures/contact_mailer/notify
A         test/fixtures/contact_mailer/validate_email
A         test/fixtures/contacts.yml
A         test/functional
A         test/functional/website_controller_test.rb
A         test/integration
# and so on


  • Next, lets commit the Rails app to the repository
username@mydomain.com [~/your_app_name_dev]$ svn commit -m "Added The Application"

  • This may take a few minutes depending on the size of your application. You will see the list of files appear again followed by this:
  • Transmitting file data .................................................................
    Committed revision 2.

  • Now your will be able to edit your code on your local machine and have the changes reflected in newer revisions simply by adding and committing files.


Setup Capistrano & Deploy Application


  • Setup your Rails application to work with Capistrano. Once you have checked out your code from the svn repository, change to the root of the Rails app on your development machine and run (look carefully there is a dot after capify command, just type it completely with a dot):

    username@mydomain.com [~/your_app_name_dev]$ capify .

    # This is the output
    [add] writing `./Capfile'
    [add] writing `./config/deploy.rb'
    [done] capified!
    Capistrano created two files: /config/deploy.rb and Capfile. (Note: /config/deploy.rb might have been skipped if you already had a deploy.rb file in your app.) The config/deploy.rb file will contain your application variables used to deploy your app, while the Capfile will contain your deployment tasks.


  • So open the deploy.rb file and we'll start customizing the deployment process. The first thing we want to do is set our application variables. So let's modify this first section of the file:

set :application, "your_app_name"   set :domain, "mydomain.com"  set :user, "username"        set :repository,  "svn+ssh://#{user}@#{domain}/home/#{user}/svn/#{application}/trunk"  set :use_sudo, false     set :deploy_to, "/home/#{user}/#{application}"   set :deploy_via, :checkout set :chmod755, "app config db lib public vendor script script/* public/disp*"  set :svn_username, "username" set :svn_password, "hosting_password" set :password, "hosting_password" default_run_options[:pty] = true ssh_options[:keys] = %w(/Path/To/id_rsa) role :app, "mydomain.com" role :web, "mydomain.com"
role :db, "mydomain.com", :primary => true

  • Now that everything is in place, you can commit your changes to the Subversion repository if you want:

    username@mydomain.com [~/your_app_name_dev]$ svn add config/deploy.rb Capfile
    username@mydomain.com [~/your_app_name_dev]$ svn commit -m "Configured application for Capistrano"

  • Last Step - Setup Your Hosting Account. Next we need to setup our Hosting account. This is where our hard work pays off with Capistrano. From your local machine enter the following commands:
username@mydomain.com [~/your_app_name_dev]$ cap setup


  • Next you need to run a cold deploy.

username@mydomain.com [~/your_app_name_dev]$  cap cold_deploy


  • Next we can do a full deploy

username@mydomain.com [~/your_app_name_dev]$  cap deploy


  • Or if you want Capistrano to run your migration files (be sure to have your database and database.yml setup properly).

username@mydomain.com [~/your_app_name_dev]$  cap deploy_with_migrations


  • If you ever run into problems and need to rollback to a previous revision of your code simple enter:

username@mydomain.com [~/your_app_name_dev]$  cap rollback


  • As you make revisions to your code on your local machine and are ready to deploy your updated application to the production server all you have to do is:

username@mydomain.com [~/your_app_name_dev]$ $ svn commit -m "Your Custom Reference Message";cap deploy


Case Abtractions [Indonesian Language]

Sorry for you guys, i write this article for my friends in my country, indonesia, to support their final thesis projects.


1. SPPK Pembelian Property atau Real Estate.

  • Description : Sistem ini ditujukan bagi user atau konsumen yang memiliki keinginan untuk membeli rumah namun memiliki pengetahuan terbatas tentang lokasi mana saja yang masih tersedia sesuai dengan keinginan mereka. Input user konsumen dapat berupa range budget atau harga yang di inginkan konsumen, luas tanah, luas bangunan, lokasi, dll. Diharapkan sistem ini dapat bekerja sama dengan para realestate group sehingga pengusaha realestate dapat menginputkan informasi tipe rumah, harga, lokasi, gambar rumah/design dan peta (dapat menggunakan peta dari google), harga basis investasi dapat didesign berdasartkan permintaan user developer untuk ditampilkan semakin meningkat berdasarkan periode waktu. Output bagi user konsumen adalah daftar real estate, diikuti dengan sublist informasi rumah yang masih tersedia (belum laku terjual) yang terdiri dari gambar rumah atau denah rumah, harga, dan detail property serta prediksi nilai investasi jika membeli rumah tersebut serta fasilitas anggunan yang ditawarkan developer jika tersedia.
  • Contoh www.propertyfinder.com
  • Skala user : masih dalam satu k0ta
  • Software Target: property group atau real estate group.
  • Tantangan: gunakan mushup google map untuk realtime peta jika tidak terdapat peta kota. Sistem dapat mendukung upload gambar atau video promosi jika diperlukan.
  • Teknologi basis web.

2. Event Management
  • sebagai salah satu contoh event management ditujukan untuk dosen universitas atau fakultas. Sistem ini dapat dikatakan sebagai perencanaan aktivitas dosen yang memudahkan mahasiswa untuk memantau keberadaan dosen untuk keperluan konsultasi. Dosen juga dapat memberikan keterangan terhadap jadwal konsultasi dan mahasiswa dapat mendaftar langsung untuk konsultasi, seperti pasien mendaftar dokter dirumah sakit, sehinga dosen dapat mengetahui siapa saja mahasiswa yang ingin berkonsultasi atau bertemu dengan dosen. Mahasiswa juga dapat memilih tanggal konsultasi dan jam yang diinginkan untuk bertemu dengan dosen, dosen akan menerima laporan berupa pesan pada halaman pribadinya. Output hampir mirip dengan kalender agenda dan email portal. untuk registrasi konsultasi fisik, system menampilkan daftar user pada tanggal tertentu berdasarkan urutan tanggal, deskripsi keperluan, dan nama mahasiswa.
  • Hal-hal yang dapat dilakukan : booking dosen, email portal, mahasiswa dan dosen, dapat upload dan download file dari email portal tersebut, calendar agenda.
  • Tantangan : dosen dapat menginput agenda dia melalui sms lalu event portal memprosesnya dan menampilkannya ke agenda event dan portal memberi report sms bahwa agenda telah dibentuk.
  • Contoh kasus lain sebagai perbandingan dapat dilihat disini : http://www.peoplecube.com/solutions-event-management.htm

3. Electric card or business card
  • Web ini ditujukan buat user yang ingin membuat kartu nama, kartu pos, atau poster, user dapat mengupload designnya untuk dicetak atau dijual memalui perantara yang punya website. owner website akan mengirim pesanan user jika telah selesai, pembayaran dapat berupa transfer bank.
  • Tantangan : sistem mendukung user mendesign sendiri postcardnya secara online atau mendesign ulang yang sudah jadi atau gunakan ajax dalam aplikasi ini.
  • kasus tidak hanya untuk kartu tapi dapat diganti dengan design baju online.
  • Contoh kasus : http://www.harboarts.com/shirtdesigner/productpage01.php
  • Tantangan : gunakan flex atau ajax untuk redesign atau design online

4. Web Operation System
  • Silahkan pelajari web ini : http://www.cloudcomputing.gopc.net/?gclid=CIr-xbi03pQCFQWxsgodJnu_SQ
  • Dapat diimplementasikan sebagai notebook untuk dosen atau mahasiswa, untuk menyimpan kuliah praktikum yang dpt dilakukan secara online, sehingga user dapat membuka kembali hasil praktikumnya diwarnet atau hasil kerja dan kuliahnya diwarnet.
  • Solusi : Gunakan Flex atau RJS atau AJAX.

5. Posyandu Online atau Apotik Online
  • Web ini serupa SPPK yang membantu user memilih obat berdasarkan penyakit yang dihadapinya atau ciri-ciri penyakit yang dihadapinya dan alergi user terhadap obat jika ada, output berupa daftar obat dan indikasinya serta aturan pemakaian.
  • Tantangan terhubung dengan apotik, artinya jika output obat sudah ditampilkan user dapat memesan langsung obat yang bersangkutan, dan obat dapat diantar. (lingkup hanya dalam kota saja.)

 
powered by Blogger