Web Service

You are currently browsing articles tagged Web Service.

The following post contains information on how to create a “Domain who is” Air application with Flash Builder 4 beta using a web service.
You can download the Flash Builder 4 beta from Adobe Labs.
More information about the Flex 4.0 SDK can be found here.
The requirements are:
- Flash Builder 4 Beta 2 with Flex SDK 4.0

I choose a free web service from www.ecocoma.com
As you can see on this page I use the “Whois Webservices” (seen at the bottom of the page). The service url is “http://service.ecocoma.com/domain/whois.asmx?wsdl”

Be aware that you will need a
KeyID : DOM-T90971404J

The guys from the ecocoma mention the KeyID will be changing every week so you’d better have a look on the URL above to get the latest one.
KeyID will be needed for the call to the web service.

Ok, let’s get cracking!

As in my previous post you will need to create a new flex project for this as well. I call it “whois”, just to remind you to select Flex SDK 4.0 and Desktop under Application type.

First we need to create the application layout. Drag and drop a panel layout component and set width, height and label text. I used width 250, height 120 and set the label to “Search for a domain name”. After that, I draged and dropped a Form layout component, a textinput and a button component from the design view. I set labels and IDs and here you go:

00

The code so far should more or less look like this:

Panel and Textinput code

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" width="350" height="340" xmlns:whois="services.whois.*">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Panel width="250" height="120" horizontalCenter="0" title="Search for a domain name" top="20">
<mx:Form x="0" y="0" width="248" height="90"> <mx:FormItem label="Domain">
<s:TextInput id="DomainName"/> </mx:FormItem> <mx:FormItem>
<s:Button label="Submit" id="Submit_Btn" click="Submit_Btn_clickHandler()"/>
</mx:FormItem>
</mx:Form>
</s:Panel>
</s:WindowedApplication>

I will now use the Flash Builder to call the web service. From the Data/Services View, select ‘Connect to Data/Service’ and choose Web Service (the last one on the right hand side) and click next. Now add the web service path as I mentioned above ‘http://service.ecocoma.com/domain/whois.asmx?wsdl’, set the service name as “whois” so the service package will be “service.whois” and the data type package “valueObjects”.

03

Now in the Data/Services View you can see the web service method and the three required arguments. The first one is the KeyID the second is the DomainId (you can leave this blank as it’s not a required argument) and the last one is the domain name we need to search in (actually this will be the value of our textinput):

01

Once we connect the web service with our application the Flash Builder 4 beta will create a couple of files for us. It first introspects the web service and then creates two folders and some ActionScript files. Putting the drag and drop functionality from the design view behind us, lets start coding some mxml and actioscript stuff.
The code inside the mxml file should look like the one before, no changes needed at all.
First we need to call the service “whois”. It’s really easy, start typing inside the “fx:Declarations” tag whois and you will get this:

04

Continue by giving it an id (I use the “whois_service” and set the “showBusyCursor” to true as I want the cursor to be different when the form submission pops up). I also need to set up a general fault function so write “fault” and choose “Generate Fault Handler” from the hint pop up. Flash Builder 4 beta will generate a function handler for you that will look like this:

Generated fault handler


protected function whois_service_faultHandler(event:FaultEvent):void
{
// TODO Auto-generated method stub
}

You need to change the code a bit so it gives you an error if anything bad happens:

Final fault handler


protected function whois_service_faultHandler(event:FaultEvent):void
{
Alert.show(e.currentTarget.toString());
}

you also need to add these on the top of the “fx:script” tag

Code additions


import mx.controls.Alert;
import mx.rpc.events.FaultEvent;

Now that the general whois service fault method is ready lets really get into this excersise. I need to create a Call responder by using the who is service. Inside the “fx:Declarations” tag use the spark component CallResponder by writing “<s:CallResponder” set a unique ID and give it a result handler, for the example I used the id “GetDomainInformation” and the “GetDomainInformation_resultHandler(event)” as result handler.

Call responder


<s:CallResponder id="GetDomainInformation" result="GetDomainInformation_resultHandler(event)"/>

Leave the result handler blank at the moment and don’t forget to import the ResultEvent class:

Result handler


//class for the result event
import mx.rpc.events.ResultEvent;
//Result event handler
protected function GetDomainInformation_resultHandler(e:ResultEvent):void
{

}

Ok! Now that you have the result event you need the form submission by using the call responder service that we just set up. Write down another function (I call it “Submit_Btn_clickHandler”) to handle the form submission. The code for the function is:

Result handler


//submit button handler
protected function Submit_Btn_clickHandler():void
{
GetDomainInformation.token = whois_service.GetWhois('DOM-T90971404J','',DomainName.text);
}

Let’s explain the code a bit: I use the “GetDomainInformation” call responder that I just created and the “whois_service” service. I call the “GetWhois” method that is available from the web service since, as I mentioned at the begining of the post, we need to pass three parameters. The first is the KeyID (use the one that found on the ecocoa website) the second is the DomainID (leave it blank) and the third is the textinput value.

More information on spark component s:CallResponder and the new service operations can be found in Adobe’s Flex 4.0 SDK documentation
Accessing Data with Flex : Building data-centric applications with Flash Builder

That’s it! We now have the submission form ready but we still need to display the result, let’s get back to our result handler and add a couple of lines:

Final result handler


//Result event handler
protected function GetDomainInformation_resultHandler(e:ResultEvent):void
{
//set up an object and pass the result to it
var res:Object = e.result;
//set up a string variable and fill it with the result description
var description:String = res['Description'];
//display the description string to the Alert pop up
Alert.show(description);
}

The result handler and the general fault handler set up so all we have to do is to run the application.

I almost forget a piece of code that added, I have created a function called ‘init()” and set the textInput component to be focused at the creation of the air application, this makes our life easier so we can start typing the domain name right away. You also need to define when you need the init() function to be run. This can be done by adding this attribute to the “s:WindowedApplication” tag
creationComplete=”init()”

And the init() code is:

init function


protected function init():void
{
DomainName.setFocus();
}

Here is the final mxml code:

Final mxml code


<?xml version="1.0" encoding="utf-8"?> <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" width="500" height="400" xmlns:whois="services.whois.*" creationComplete="init()">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectUtil;

protected function init():void
{
DomainName.setFocus();
}
protected function whois_service_faultHandler(e:FaultEvent):void
{
Alert.show(e.currentTarget.toString());
}
protected function GetDomainInformation_resultHandler(e:ResultEvent):void
{
var res:Object = e.result;
var description:String = res['Description']; Alert.show(description);
}
protected function Submit_Btn_clickHandler():void
{
GetDomainInformation.token = whois_service.GetWhois('DOM-T90971404J','',DomainName.text);
}
]]>
</fx:Script>
<fx:Declarations>
<whois:Whois fault="" id="whois_service" showBusyCursor="true"/>
<s:CallResponder id="GetDomainInformation" result="GetDomainInformation_resultHandler(event)"/> </fx:Declarations>
<s:Panel width="400" height="120" horizontalCenter="0" title="Search for a domain name" top="20">
<mx:Form width="400" height="90" horizontalCenter="0" top="0"> <mx:FormItem label="Domain">
<s:TextInput id="DomainName"/>
</mx:FormItem>
<mx:FormItem>
<s:Button label="Submit" id="Submit_Btn" click="Submit_Btn_clickHandler()"/>
</mx:FormItem>
</mx:Form>
</s:Panel>
</s:WindowedApplication>

Here you go!

Picture 2

You could go on and use more features to have better results and a better design view. You should give it a try!

I hope you like my post and found this information interesting!

Tags: ,

00

The following post contains information on how to create a login Air application with Flash Builder 4 using a cfc web service.
You can download the Flash Builder 4 beta from Adobe Labs
More information about the Flex 4.0 SDK can be found here
The requirements are:
- Flash Builder 4 Beta 2
- Coldfusion 8+
- SQL server 2005+

Create a new flex project ‘Login_Webservice_cfc’

01

We first need to create the application layout. We choose the design view to make our life easier (ctrl+`), then drag and drop a Panel component from the Coponents views.

From the Properties View set the Title as ‘Login’ and set width and height as 250,150 respectively. Set the Panel to always be in the center of the screen by selecting the proper checkboxes from the Constrains area and set both values to ’0′.

02

After that, drag and drop a form component inside the panel from the componets view and set width and height to 100%. We next need to add two TextInput components; one for the Username and one for the Password inputs.

When you add a form component using the design view, Flash builder adds a FormItem wraper for you. So the code for each of your inputs will be similar to this:

Formitem


<mx:FormItem label="FirstInput">
    <s:TextInput id="FirstInput"/>
</mx:FormItem>

Set the labels and IDs using proper values (for the example I use ‘Username’ and ‘Password’ respectively).
At the end you will need a submit button to handle the form submission. Drag and drop a button from the component view below the two text inputs. Use the ‘SubmitBtn’ as an ID value and the ‘Login’ as label value.
As you can see, you need to remove the label value from the submit button FormItem. Click on it and just remove it.

The Login panel should look like this:
03

and the mxml code like this:

Panel component code


<s:Panel width="250" height="150" title="Login" horizontalCenter="0" verticalCenter="0">
<mx:Form width="100%" height="100%" left="0" top="0">
<mx:FormItem label="Username">
<s:TextInput id="Username"/>
</mx:FormItem>
<mx:FormItem label="Password">
<s:TextInput id="Password"/>
</mx:FormItem>
<mx:FormItem>
<s:Button id="SubmitBtn" label="Login"/>
</mx:FormItem>
</mx:Form>
</s:Panel>

If you build your application you will see that everything looks fine except for the password input that needs to display its value as password rather than as normal text. All you need is to add this as an input attribute:
displayAsPassword=”true

Now we need to connect our application to a Web service. For this example I use a coldfusion component (cfc). This is the code for my coldfusion component (.cfc):

Cfc component source


<cfcomponent output="false">
<cffunction access="remote" name="Authenticate" output="false" returntype="struct" hint="This Component authenticates User Accounts">
<cfargument name="Username" required="yes" type="string" />
<cfargument name="Password" required="yes" type="string" />

<cfquery name="Login" datasource="#Session.DSN#">
SELECT * FROM tblLogin
WHERE Username = '#Arguments.Username#'
AND Password = '#Arguments.Password#'
</cfquery>

<cfset ReturnObj = structNew() />
<cfif Login.recordcount gt 0>
<cfset ReturnObj.Success = true />
<cfset ReturnObj.Message = "Login successfull" />
<cfset ReturnObj.ReturnCode = 1 />
<cfset ReturnObj.Username = #Login.AccountName# />
<cfset ReturnObj.Password = #Login.AccountSurname# />
<cfelse>
<cfset ReturnObj.Success = false />
<cfset ReturnObj.Message = "Login incorrect" />
<cfset ReturnObj.ReturnCode = 2 />
</cfif>

<cfreturn ReturnObj>
</cffunction>
</cfcomponent>

Save the file as ‘login.cfc’ on your local web server.
You can see that we ask for two required arguments to be passed: Username and Password and then we create a structure and fill in it with some information. If we validate the user we also put the Name and the surname of the user within the structure.

Now I will use the Flash Builder to call the web service. The Flash builder makes our life easier with new functionality. From the Data/Services View, select ‘Connect to Data/Service’ and choose Web Service (the last one on the right hand side) and click next.

Now add the web service path ‘http://localhost/Login_Webservice_cfc/login.cfc?wsdl’, leave the rest of the settings as they are and click finish. Be aware that if the web service is on a remote machine you need to edit the ‘crossdomain.xml’ file for security reasons.

Now in the Data/Services View you can see the cfc method and the two required arguments.
04

Username and Password are required arguments and the return type will be Object, because we set the coldfusion function to use ‘struct’ as returntype.

We are almost there!

Drag the Authenticate function from the Data/Services view and drop it on the Submit button. Flash builder does all the hard work for you: it creates the actionscript classes and adds some pieces of code as well within your mxml file. Flash builder would just have made a submit handler for you and you need to edit it a bit.

Your function should look like this:

Login handler


protected function SubmitBtn_clickHandler(event:MouseEvent):void
{
AuthenticateResult.token = login.Authenticate(Username.text, Password.text);
}

I will edit the code a bit so I can have a result function as well as a custom fault handler function.
I also create some variables to hold the user’s data if the authentication is successful.
The full code will be like this:

Full mxml code


<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
   xmlns:s="library://ns.adobe.com/flex/spark"
   xmlns:mx="library://ns.adobe.com/flex/halo" width="100%" height="100%" xmlns:login="services.login.*">
<fx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectUtil;
import mx.controls.Alert;

private var rs:Object;
private var Success:Boolean;
private var Message:String;
private var ReturnCode:int;
private var FullName:String;

//Failed to connect to the wsdl service
private function GeneralFailed_Handler(e:FaultEvent):void
{
Alert.show(e.fault.faultString, "Error connecting to the service");
}
//Login Handler
private function SubmitBtn_clickHandler(event:MouseEvent):void
{
AuthenticateResult.token = login.Authenticate(Username.text, Password.text);
}
//Result Handler for Account Authentication
private function AuthenticateResult_resultHandler(e:ResultEvent):void
{
//check the result
Alert.show(ObjectUtil.toString(e.result),"Login Results")

rs = new Object();
rs = e.result;
Success = rs['SUCCESS'];
Message = rs['MESSAGE'];
ReturnCode = rs['RETURNCODE'];

if(ReturnCode == 1)
{
FullName = rs['LOGIN']['NAME'] + " " + rs['LOGIN']['SURNAME'];

}else{
Alert.show(Message, "Try Again");
}
}

]]>
</fx:Script>

<fx:Declarations>
<login:Login id="login" fault="GeneralFailed_Handler(event)" showBusyCursor="true"/>

<s:CallResponder id="AuthenticateResult" result="AuthenticateResult_resultHandler(event)"/>
</fx:Declarations>

<s:Panel width="250" height="150" title="Login" horizontalCenter="0" verticalCenter="0">
<mx:Form width="100%" height="100%" left="0" top="0">
<mx:FormItem label="Username">
<s:TextInput id="Username"/>
</mx:FormItem>
<mx:FormItem label="Password">
<s:TextInput id="Password" displayAsPassword="true"/>
</mx:FormItem>
<mx:FormItem>
<s:Button id="SubmitBtn" label="Login" click="SubmitBtn_clickHandler(event)"/>
</mx:FormItem>
</mx:Form>
</s:Panel>
</s:Application>

Now, if you test your application you will see I have put two alert messages, one for a failed login and a general one to display the result of the submission form:
05

I hope you found this interesting and informative! :D

Enjoy!

Tags: , ,