768x90 Getting Online Shouldn't be Tough- $7.49 .com Domains at Go Daddy
Showing posts with label Air. Show all posts
Showing posts with label Air. Show all posts

Create Game in Air or Flex Easily

I am the admirer of bored.com website, this site will help you with its games to reduce your stressing in office or work. But How you can create your own game in Flex or Adobe air with painless ? I have found a great library to help developer in making 2D game easily, it is called FlashPunk by Paul Sztajer. Thanks dude.

FlashPunk is a free ActionScript 3 library designed for developing 2D Flash games. It provides you with a fast, clean framework to prototype and develop your games in. This means that most of the dirty work (timestep, animation, input, and collision to name a few) is already coded for you and ready to go, giving you more time and energy to concentrate on the design and testing of your game.

This framework is designed for use with the free Flex framework, used for building Flash applications; by combining this with a code editor such as FlashDevelop or Flash Builder, you can import the FlashPunk library and develop games without the need of the official Flash IDE.

You can feel the delicious of features:
  • Framerate-independent and fixed-framerate timestep support.
  • Fast & manageable rectangle, pixel, and grid collision system.
  • Helper classes for animations, tilemaps, text, backdrops, and more.
  • Debug console for real-time debugging and information tracking.
  • Sound effect support with volume, panning, and fading/crossfading.
  • Powerful motion tweening for linear, curved, and path-based movement.
  • Z-sorted render lists for easy depth management.
  • Simple keyboard and mouse input state checking.
  • Quick & efficent particle effects and emitters.
Click here to see flashPunk sample game which is not for flex or flash but it is already used for android.

Download Youtube Video Using ActionScript or Air

Youtube is my favorite website and very entertaining, not only in video but also making money. How you can download youtube video to flv format? A week ago, i have little experiment to make Air application for downloading Youtube. The important thing you have to get is the video id http://www.youtube.com/watch?v=yGTg5116dCM, the action script is very simple, even you can make multiple download as many as you want, here is the script:

private function configureListeners(stream:URLStream):void {
    var _date:Date = new Date();
    var _fileName:String = String(_date.milliseconds)+".flv";
    stream.addEventListener(Event.COMPLETE, function(event:Event):void {
      var fileData:ByteArray = new ByteArray();
      stream.readBytes(fileData,0,stream.bytesAvailable);
      var file:File = File.documentsDirectory.resolvePath(_fileName);
      var fileStream:FileStream = new FileStream();
      fileStream.open(file, FileMode.WRITE);
      fileStream.writeBytes(fileData,0,fileData.length);
      fileStream.close();
     });
    downloadProgress.source = stream; //downloadProgress is ProgressBar id    
  }
  
  public static const GET_VIDEO_INFO :String = "http://youtube.com/get_video_info.php";
            
  public function downloadVideo(_youtubeId:String):void{
    var service :HTTPService = new HTTPService();
    service.url = GET_VIDEO_INFO + "?video_id=" + _youtubeId;
    service.resultFormat = 'object';  

    service.addEventListener(ResultEvent.RESULT, function(evt:ResultEvent):void{
      var request:URLRequest = new URLRequest(unescape(evt.result.toString()).split("|")[1]);
      var stream:URLStream = new URLStream;
      configureListeners(stream);
       try {
         stream.load(request);
       } catch (error:Error) {
         trace("Unable to load requested URL.");
       }
     });
     service.send();
    }

Yeah, that is a short codes, for advance application you can use as3youtubelib to search, subscribe and comment the video. I have used oauth google and youtube API for multiple uploads to youtube. And once again no webservice unless google data protocol. i use pinless oauth. Please read the previous article. Thank you.

Sort Collection Rss By PubDate in ActionScript

XML can be friendly and some times can be nightmare for me. A few days ago, i have task to sort rss results from multiple sites by the pubDate. If you see the source xml of rss, each websites has common format pubDate : Wed, 03 Nov 2010 22:31:34 +0000 . As my experience, converting string date to datetime in actionScript using DateField.stringToDate not always give you actual result and my client want get the results are sorted up to milliseconds. There are some suggestion to use XSLT to sort xml by pubDate, but my application is desktop Air, how to do that without connect to webservice and parsing the rss result to XSLT ?

ActionScript is very fast to recursive big of data. So I decide to sort rss results in XMLListCollection, here is my codes:

//_result are composite of total rss results from a number of websites.
    // _results += new XMLList(XML(event.result)..item);
    public function sortRss(_results:XMLList, sortedResults:XMLListCollection):void{
      var sort:Sort = new Sort();
      sortedResults = new XMLListCollection(_results);
          
      var sortField:SortField = new SortField();
      sortField.compareFunction = sortRssByDate;
      sortField.descending = true;
     sort.fields = [sortField]
           
      sortedResults.sort = sort;
      sortedResults.refresh();
    }
    
    public var months:Array = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

    private function convertPubDate(_pubDate:String):Date{
      var arrDate:Array = _pubDate.split(/\s/gi);
      var _strDate:String = arrDate[0]+" "+arrDate[1]+" "+arrDate[2]+" "+arrDate[3];
      var arrTime:Array = arrDate.length > 5 ? String(arrDate[4]).split(/\:/gi) : [];        
      var _hour:Number = arrTime.length == 3 ? Number(arrTime[0]) : 0;
      var _minute:Number = arrTime.length == 3 ? Number(arrTime[1]) : 0;
      var _second:Number = arrTime.length == 3 ? Number(arrTime[2]) : 0;
      var _dateTime:Date = new Date(Number(arrDate[3]), months.indexOf(arrDate[2]),Number(arrDate[1]),_hour,_minute,_second);
      return _dateTime;
    }
      
    private function sortRssByDate(itemA:Object,itemB:Object,fields:Array = null):int{
    var dateA:Date = convertPubDate(itemA.pubDate);
      var dateB:Date = convertPubDate(itemB.pubDate);
      return ObjectUtil.dateCompare(dateA,dateB);
  }

Finally, it works without crash the application. I have tested from 10 websites with 25 items for each rss per 1 box, and i have 10 boxes. Total 100 websites rss that have to be sorted together by pubdate and grand total item is 2500 items.

BBAuth, Y!Oauth with pinless authentication in Air

I developed Air application which requires yahoo profile data. I think the application is little bit extraordinary since it doesn't need webservice, because my client won't it. I found Yahoo SDK for AS3 to build simple Yahoo Social Applications. It is quite satisfied to introduce me how to use Browser-Based Authentication (BBAuth) or Yahoo! Oauth, but how to make it not to open external browser and automatically get access token without invoking webservice and get verification pin? I got inspiration from twitter pinless . Fortunately, it works, you can see my screencast below:



When you click "Login To Yahoo" button, the authorize() method is executed, below is the codes.

private function authorize():void{
        YSession = new YahooSession(StormModel.YCONSUMER_KEY, StormModel.YSECRET_KEY, StormModel.YAPPLICATION_ID);
        YSession.clearSession();
        YSession.auth.addEventListener(YahooResultEvent.GET_REQUEST_TOKEN_SUCCESS, handleRequestTokenSuccess);
        YSession.auth.addEventListener(YahooResultEvent.GET_ACCESS_TOKEN_SUCCESS, handleAccessTokenSuccess);
        YSession.auth.pinlessAuth = true;
        
        var rect:Rectangle = new Rectangle(50,50, 780, 500);
        var browser:CustomHtmlHost = new CustomHtmlHost;
        var newHTMLOptoions:HTMLWindowCreateOptions = new HTMLWindowCreateOptions;
        newHTMLOptoions.x = 50;
        newHTMLOptoions.y = 50;
        newHTMLOptoions.scrollBarsVisible = true;   
        htmlBox = browser.createWindow(newHTMLOptoions);
        YSession.auth.htmlLoader = htmlBox;
       YSession.auth.getRequestToken("http://www.google.com");
      }
      
      private function handleRequestTokenSuccess(event:YahooResultEvent):void{
       YSession.auth.sendToAuthorization(event.data as OAuthToken);
      }
      
      private function handleAccessTokenSuccess(event:YahooResultEvent):void{
        YSession.auth.token = event.data as OAuthToken;
        htmlBox.stage.nativeWindow.close();
        YSession.setAccessToken(event.data as OAuthToken);
        gridProviders.addItem({token: YSession.auth.token.key, secret: YSession.auth.token.secret});
      }

The screencast seems little fool, because i use callback to www.google.com, but you can use any redirect url, eg: to your webservice, your domain or yahoo.com. Aside issues, to make my pinless authentication work sexier, I should hacks some line codes in YahooSession.as and AuthorizationRequest.as . (You can copy paste from these links). After i get the accessToken and accessSecret, i store them in sharedObject, and then re-validate any time you want extend the expired token. So what is CustomHtmlHost? Adobe has changed the policy for HTML where HTMLLoader is no available if you create directly new HTMLLoader, it is little hack solution from me:

package com.yahooStorm.utilities
{
    import flash.display.NativeWindowInitOptions;
    import flash.events.Event;
    import flash.geom.Rectangle;
    import flash.html.*;

    public class CustomHtmlHost extends HTMLHost
    {
        import flash.html.*;
        
        public function CustomHtmlHost():void{}
        
        override public function 
            createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader
        {
            var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
            var bounds:Rectangle = new Rectangle(windowCreateOptions.x,
                                                 windowCreateOptions.y, 
                                                 1000,
                                                 650);
            var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions,
                                        windowCreateOptions.scrollBarsVisible,bounds);

            htmlControl.addEventListener(Event.COMPLETE, onCompleteWindowHandler); 
            return htmlControl;
        }
        
        public function makeWindow(options:HTMLWindowCreateOptions):HTMLLoader{
          return createWindow(options)
        }
        
        public function onCompleteWindowHandler(event:Event):void{
        }
        
        override public function windowClose():void
        {
            htmlLoader.stage.nativeWindow.close();
        }
        
        override public function updateTitle(title:String):void
        {
          htmlLoader.stage.nativeWindow.title = "Placepoint Browser: " + title;
        }
    }
}

I am very interested to make BBauth pinless version work too in Flex and Flash As3 and then build the package scripts to swc, but i still have no time to do that, ASAP i will post the swc and documentation here.

If there's any question or suggestion please post in the comment box. Thank you.

ArrayCollection Mapping From Multiple Object Types

 private function listToString(element:*, index:int, arr:Array):String {
   var _return:String = "";
   if(element is FeedInfo){ 
     _return = element.address;
   }else if(element is UserFeed){
     _return = element.name;
   }else{
     _return = element.id;
   }
    return _return;
 }
    
 private function prepareSaveFeeds(_list:RxCollection):void{
   var _tmpUserFeed:UserFeed = new UserFeed;
   _tmpUserFeed.feedAccount = _account;
   _tmpUserFeed.user = userModel.currentUser;
   _tmpUserFeed.keywords = _list.toArray().map(listToString).join("::");
 }

The output will be

 "yacobus::reinhart::blog"

How To Create List & Add User Twitter in Flex and Air

A moment ago i have a problem about how to get Home Line or status from a group users list in my Air Application and sort them by date ascending. My analyst is if an account has 20 tweets but the group has 10 users, it means that i have to sort 200 list. Why don't use SortOn for Array? If you try myArray.SortOn("date",[Array.CASE_SENSITIVE, Array.UNIQUE ]), it can't sort date (string type in twitter) very well, we have to convert them from string to millisecond, and it will take time, maybe crashed.

My idea is, unite them in a list in customer twitter account then get the list status, make sense, no ? For this case i use library from Sandro (Thanks Dude) , which is named tweetr, badly no more example about create list like my case. When i read the documentation, it seems simple, but the process is not like that. The list status, only can pull status of users which are public, so if it is protected you can't pull them.

Here is the sample of my work, you can try by clicking the demo link below (this sample not stores your twitter login ^_^), the demo is in flex version, but you can convert it to Air easily.

DEMO
SOURCE (Flex)

Basic Authentication in Flex or Air

After discussing about AuthSub and ClientLogin in Google in Flex or Air, now I would like to step forward about Basic authentication in Flex or Air. To know more about Basic Authentication please browse to this link https://mail.google.com/mail/feed/atom/all , you will be asked by pop up window to enter your login information right? now let we see how to handle it :



<mx:VBox
xmlns:mx = "http://www.adobe.com/2006/mxml"
width = "100%"
height = "100%"
verticalAlign = "middle"
horizontalAlign = "center"
backgroundColor = "#364a59"
creationComplete= "{creationHandler()}"
>

<mx:Script>
<![CDATA[

import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.mxml.HTTPService;
import mx.utils.*;

private function creationHandler():void{
gmailService.headers = {Authorization:"Basic " + basicAuth()};
gmailService.url = "https://mail.google.com/mail/feed/atom/all"
gmailService.contentType = "application/x-www-form-urlencoded"
gmailService.resultFormat = "e4x"
gmailService.addEventListener(ResultEvent.RESULT, feedSuccess);
gmailService.addEventListener(FaultEvent.FAULT, faultHandler);
gmailService.send(); //Update Here
}

private function basicAuth():String{
var encoder:Base64Encoder = new Base64Encoder();
encoder.insertNewLines = false;
encoder.encode("yacobus.r@kiranatama.com:Dec.07.1082"));
return String(encoder);
}

private function feedSuccess(event:ResultEvent):void{
//Do any logic for feed result here
trace(XML(event.result))
}


private function faultHandler(event:FaultEvent):void{

}

]]>
</mx:Script>

<mx:HTTPService id="gmailService" showBusyCursor="true"/>

</mx:VBox>


Perfect right!!

AuthSub Authentication on Flex or Air

There are 3 types of authentication on when you are accessing website nowdays, they are :

  1. AuthSub / ClientLogin authentication, this authentication uses credential login information and give back to you authentication token that will be used on header as security login token to make you available login in 24 hours.
  2. OAuth authentication, this authentication is using secret key and customer key, more secure than AuthSub, this kind authentication will use your token and secret token in header Authentication information to identify you are the valid user when accessing secure data or page.
  3. Basic Authentication, if you see pop up alert that ask you to enter username or password, that is Basic Authentication.
Now i would like to share you about how to make those authentication become autologin without you face on their login page. First let discuss AuthSub or ClientLogin :

Now, try access this page : http://docs.google.com/feeds/documents/private/full

You will see error like this Authorization required, Error 401. These scripts all you need to pass the authentication easily :

you can use or just a class of HTTPService.


<mx:VBox
xmlns:mx = "http://www.adobe.com/2006/mxml"
width = "100%"
height = "100%"
verticalAlign = "middle"
horizontalAlign = "center"
backgroundColor = "#364a59"
creationComplete= "{creationHandler()}"
>

<mx:Script>
<![CDATA[

import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.mxml.HTTPService;
import mx.utils.*;

private function creationHandler():void{
var data:Object = new Object;
data.Email = "yacobus.r@kiranatama.com";
data.Passwd = "Dec.07.1082"
data.accountType = "GOOGLE";
data.service = "writely";
//ClientLogin Url : https://www.google.com/accounts/ClientLogin
//AuthSub Url : https://www.google.com/accounts/AuthSubRequest
gmailService.url = "https://www.google.com/accounts/ClientLogin";
gmailService.contentType = "application/x-www-form-urlencoded";
gmailService.method = "POST";
gmailService.request = data;
gmailService.addEventListener(ResultEvent.RESULT, successHandler);
gmailService.addEventListener(FaultEvent.FAULT, faultHandler);
gmailService.send();
}

private function successHandler(event:ResultEvent):void{
gmailService.removeEventListener(ResultEvent.RESULT, new Function);
var txtAuth:String = String(event.result);
var authPosition:int = txtAuth.search("Auth");
txtAuth = txtAuth.substring(authPosition);
txtAuth = txtAuth.replace("Auth=","");
authPosition = txtAuth.length;
authPosition = authPosition - 1;
txtAuth = txtAuth.substring(0,authPosition);

accessProtectedUrl(txtAuth);
}

private function accessProtectedUrl(txtAuth:String):void{

gmailService.headers = {Authorization:"GoogleLogin auth="+txtAuth};
gmailService.url = "http://docs.google.com/feeds/documents/private/full";
gmailService.method = "GET";
gmailService.addEventListener(ResultEvent.RESULT, feedSuccess);
gmailService.addEventListener(FaultEvent.FAULT, faultHandler);
}

private function feedSuccess(event:ResultEvent):void{
//Do any logic for feed result here
trace(XML(event.result))
}


private function faultHandler(event:FaulttEvent):void{

}


]]>
</mx:Script>

<mx:HTTPService id="gmailService" showBusyCursor="true"/>

</mx:VBox>


List of Google Apps Service : http://code.google.com/apis/base/faq_gdata.html#clientlogin

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 ); 

   }
  }
}             

 
powered by Blogger