Archive for April 28, 2010

Access data in flex using Webservice Component

<

Flex applications can interact with web services that define their interfaces in a Web Services Description Language 1.1 (WSDL 1.1) document, which is available as a URL. WSDL is a standard format for describing the messages that a web service understands, the format of its responses to those messages, the protocols that the web service supports, and where to send messages. The Flex web service API generally supports Simple Object Access Protocol (SOAP) 1.1, XML Schema 1.0 (versions 1999, 2000, and 2001), and WSDL 1.1 RPC-encoded, RPC-literal, and document-literal (bare and wrapped style parameters). The two most common types of web services use remote procedure call (RPC) encoded or document-literal SOAP bindings; the terms encoded and literal indicate the type of WSDL-to-SOAP mapping that a service uses.

Flex applications support web service requests and results that are formatted as SOAP messages. SOAP provides the definition of the XML-based format that you can use for exchanging structured and typed information between a web service client, such as a Flex application, and a web service.

 

Sample WebService application

 

In this example I will show how to create a webservice in vs 2005, and how to  access that webservice in flex.

So, our goal is to make Flex talk with Asp.Net, but not only talk , we want it to query a database so that we can get data from it, well, here are the ingredients to do that, we need:

 

-Flex (I’m using flexbuilder 2)
-Asp.Net (I’m using Visual studio 2005)
Database (I’m Using Microsoft SQL 2000)

1. Create Database table Employee using Microsoft Sql 2000

First We have to create a database named ‘sample’, and create a table named ‘Employee’ in Sql server 2000

CREATE TABLE Employee(Employeechar(50),Departmentchar(50))

then insert values into that Table Employee

INSERT INTO Employee(Employee,Department)VALUES(‘ravi’,‘Engineering’)

INSERT INTO Employee(Employee,Department)VALUES(‘John’,‘Finance’)

INSERT INTO Employee(Employee,Department)VALUES(‘Marylin’,‘Administration’)

Now, we created database for the employee with name and his department.

2.

Create a Webservice a in VB.net

In Visual Studio 2005, select New Website -> Asp.net Webservice.

Name the Project as Employee. Click ok

Select Service.vb in Solution Explorer

By Default, we have a Webmethod i.e, Helloworld. Now we have write a new webmethod to query  the database Table Employee which we created earlier. For that we need to Import some classes

Imports System.Data

Imports
System.Data.SqlClient

Now we will Write  <webmethod>_ Function GetDepartment() which will take employee name as input parameter and retrieve Department name of that Employees

Public Function GetDepartment(ByVal
name1
As String) As String

Dim i As String

Dim objCon As SqlConnection = NewSqlConnection(“server=localhost;uid=sa;pwd=khammam;database=Sample”)

Dim objCom As SqlCommand = New SqlCommand

objCom.Connection = objCon

objCom.CommandText = “select Department from employee where Employee = ‘” & name1 & “‘”

objCon.Open()

Dim result As Object

result = objCom.ExecuteScalar

If Not IsDBNull(result) Then

i = result

Return i

Else

i = 0

Return i

End If

objCon.Close()

End Function

Now run the project:

Now we can see the two methods Helloworld() and GetDepartments(). Click GetDepartments()

Now it will ask you the name of the employee and return the department name of that employee. for Ex. I will type John and  invoke that method

The Final Result is Department of the John is: Finance.The Output is in XML format and this webservice is location ishttp://localhost/employee/Service.asmx

.

3. Final part is Create Application in Flex

Step 1 – Create a New Project in Flex Builder

  1. Start your Flex Builder. On the top menu, click File -> New -> Flex Project

  2. Give a name to your project, e.g. FlexWebService.

  3. Keep the default value for the rest parts, click Finish button.

Step 2 – Add Flex WebService Component

Flex provides a MXML tag <mx:WebService> to call web services, that is all you need right now. So just add the following lines to you main MXML file.

<mx:WebService id="myservice" wsdl="http://localhost/employee/Service.asmx?WSDL">
    <mx:operation name="GetDepartment()" result="result(event)">
	<mx:request xmlns="">
		<name1>{emp1.text}</name1>
	</mx:request> 
   </mx:operation>
</mx:WebService>

What have we just done?

  • We create a <mx:WebService> with id myservice.
  • We point <mx:WebService> to the URL (http://localhost/employee/Service.asmx?WSDL) of a wsdl file created by our web service provider.

  • We specify the operation to use (GetDepartment) and the functions to handle the result result(event))./font>

  • Step 3 – Add Flex WebService Event Handlers

    Now, we add the following code to handle the Flex WebService result and fault event.

    <mx:Script>  
      <![CDATA[
    import mx.rpc.events.ResultEvent;
    import mx.controls.Alert;
     
    private function result(event:ResultEvent):void 
    {txtdept.text = event.result.toString();
    }
     
    private function send_data():void
    {myservice.GetDepartment.send();}
    ]]>
     
    </mx:Script>


    The above code should be very simple tofollow:

    • resultHandler

      function gets the web service’s return data from ResultEvent (event.result), converts it to a string, then bind it to a Flex Text component (Deptvalue) for display.

    Step 4 – Add Flex UI Components to Display Employee and his Department

    In this last step, let’s create a simple UI:

    <mx:Panel x=”248.5” y=”95” width=”311” height=”185” layout=”absolute” title=”Get Department>

    <mx:Label x=”12” y=”25” text=”Name of the Employee:/>

    <mx:TextInput x=”157” y=”23” width=”124” id=”empname/>

    <mx:Button x=”157” y=”53” label=”Get Department

    click=”send_data()”/>

    <mx:ControlBar height=”55” y=”100>

    <mx:HBox>

    <mx:Label text=”Department:/>

    <mx:TextInput id=”txtdept/>

    </mx:HBox>

    </mx:ControlBar>

    </mx:Panel>

    Basically, we create a Panel which contains two HBox to get user input and display the result from the web service. The only thing special here is the Click Event of the Submit button.

    <mx:Button id="submit" label="Convert"click="send_data()"/>
    

    Here we refer to our Flex WebService through its id myservice, call its operation GetDepartment ,and pass a value coming from the TextInput controlempname.

    Now let’s click Run button in your Flex builder and see what will happen…

    April 28, 2010 at 1:16 pm 1 comment


    Calendar

    April 2010
    M T W T F S S
     1234
    567891011
    12131415161718
    19202122232425
    2627282930  

    Posts by Month

    Posts by Category