Creating view states: Flex 4

Introduction

This is a post to get you started with states in Flex. The post is part of a series: Flex 3 and Flex 4. It contains three primary sections:

  • What are states? – This section introduces states. If you know what they are, skip this section.
  • Creating view states: FLEX 4 – In this section, you will learn how to create states in Flex 4.

Focus:

Developers transitioning to Flex 4 and

Flex 4 beginners, who haven’t worked with Flex 3.

What are states?

Computer Science graduates can relate the concept of a state to a Definite Finite Automata.

In general, a state is understood as a situation or a condition of an object. In Flex, a state is one view of the Application (other components can also have states but in this post I will discuss Application states).

Consider for example an application which lets you choose from many phones to select one for yourself. Such an application can have two states for the phone display. One state displays minimal details about the phone. If the user is interested in the phone he can click on the display to go another display state containing more details.

Creating view states: Flex 4

The procedure for creating view states has been made much simpler in Flex 4. For working with Flex 4 you would use the Flash Builder 4 IDE (Flash Builder also comes with the earlier SDK, Flex 3 should you want to continue working with Flex 3).

As in the earlier section for Flex 3, I will discuss creating view states in both design view and code view. For design view, the procedure is very similar to how you would do it in Flex 3.

Creating states in design view:

Create a new project in Flash Builder 4 (same as Flex 3) and switch to the design view. Here, find the components window near the bottom left of the screen and locate the Panel container in the layout subsection. Drag and drop it over the application. Next find the TextInput, Label and Button controls and drag and drop them over the panel to create login-like view as shown in the image below.

Modify the Label control’s text properties to ‘Username’ and ‘Password’. Also, change the label property of the Buttons to ‘Register’ and ‘Submit’ respectively.

This is your login state. As yet, it has no explicit name because it is the only display state of your application. You can see the state in the states window. It is called <state1>.

If you can’t see the states window, you can open it by going to the menu bar and choosing window > States

You are creating a very basic login application which would generally contain 3 states:

  • Login state
  • Register state
  • Display state (if user is able to successful login – we will not create this state in this post)

To create a new state, right click on <State1> in the states window >New

You will see the following window:

Here is a definite difference between Flex 3 and Flex 4.

<Flex beginners and developers who haven’t worked on Flex 3 need not read this. They should move on to the next section>

When you try to create a new state in Flex 3, it has to be based on an existing state. What this means is that the new state (or the child state) will inherit its display from the older state (or parent state). Any change made in the parent state will be seen in the child state also. As an example, if a new Button control is added in the parent state, it will also be seen in the child state when the developer switches to it. Removing a control will have the same effect.

In Flex 4, new states are not based on earlier states. They can either be a duplicate of an older state or a blank state.

Changes to

A state that is made using duplicating an existing state in Flex 4 has thereafter no relation to the earlier state. Any changes in the earlier state, would lead to no change in the new state.

In the New state window, name the new state ‘register’ (you can name it anything, ‘register’ is the name I used). When you click Ok, a new state is created and added to the states window. You would, by default have the same display in the new state as in the login state. Change the display so that it looks something like the image below (Adding controls, changing properties … you know the drill).

Switch back to state1 (the default login state) by clicking on State1 in the states window. You will see that the login panel display is still intact. You now have two state displays. Next task is to switch between them.

Switching between states:

To switch between states you need to change the value of the currentState global variable. This variable contains the name of the currentState of the Application.

So in your login state (State1), select the ‘register’ button. In the properties window (usually below the states window) locate the On click property and in the corresponding text box write: currentState=’register’ as shown in the image.

This means that when you run the application and click on this button the view will change to display the register state.

Now switch to the register state in the states window and select the ‘register’ button. You want the state of the application to change back to the login state when the ‘register’ button of the register state is clicked. So similar to the login state, select the register button and in the properties window set the ‘On click’ property to “currentState= ‘State1’ ”

Run the application, and click on the buttons to verify that you can switch between the two states.

Creating view states in source view:

Now that you have created an application with two states in the design view, let’s see how to do the same in source view. Go back to the source view in Flex builder by clicking on the ‘source’ tab on the top left of the design editor. You will see that code has been generated for your actions in the design view. Let’s see the States code.

<s:states>
<s:State name=”State1″/>
<s:State name=”register”/>
</s:states>

You would also see code generated for the components that you have dropped in the two states. Here is a code snippet of my code:

<s:Panel x=”318″ y=”139″ width=”285″ height=”203″ title=”Login” height.register=”379″ y.register=”76″ width.register=”389″ x.register=”250″ title.register=”Register”>
<s:Label text=”Display name” x=”45″ y=”123″ includeIn=”register”/>
<s:Label x=”24″ y=”77″ text=”Password” x.register=”45″ y.register=”82″ text.register=”Second Name”/>


</s:Panel>

There is a significant difference in the code generated for Flex 3 and Flex 4.

<Flex beginners and developers who haven’t worked on Flex 3 need not read this. They should move on to the next section>

Here are the primary differences between state creation in Flex 3 and state creation in Flex 4 in the code view:

Flex 3 Flex 4
There is always a base state of the application (represented by empty string ‘’ ), which does not become part of the <mx:states> tag All states including the first state (there is no base state here) of the application become part of the <mx:states> state array
Elements have to be explicitly added and removed using the AddChild and RemoveChild mxml tags In Flex 4, developers can Use the includeIn and excludeFrom properties to add or remove a component from a state.

Modifying / Adding a component’s properties, styles or event handler is done using mxml tags nested inside the State tag. All this is done inline in the components declaration

To add the first new state to the Application (in this case the ‘register’ state), you have to add two State tags to the states array. One of them is the new state obviously, but you also give a name to the existing state. As an example, for adding a new state with the name ‘register’ to your application, you would add

<s:states>
<s:State name=”State1″/>
<s:State name=”register”/>
</s:states>

All elements that you have defined before adding the states tag are now available in both of the states. You can keep adding states in the states array. All of them will contain the same display (which is the default display of the application). Now to make a component appear in any one or more specific states use the includeIn property of the component. As an example to create a Button instance that appears only in the register state, the  code would be:

<s:Button includeIn=”register”/>

You can specify more than one state in the includeIn property by separating state names with a comma delimiter. Hypothetically, if your application contained a third state called ‘ErrorState’ and you wanted a button to appear only in the other two states (‘State1’ and ‘register’) and not in the ErrorState, the code would be:

<s:Button includeIn=”State1,register” /> Code statement 1

If the includeIn property is not specified for a component, it will appear in all states.

You can also use the excludeFrom property to specify states in which the component will not appear. As an example, we could also have created the above button by:

<s:Button excludeFrom=”ErrorState” /> Code statement 2

Code statement 1 and 2 are equivalent for an application containing three states: ‘State1’, ‘register’ and ‘ErrorState’.

Changing component properties

You may want the height of the Panel to increase in the register state as it contains more content than the login panel. How to make this change in the code view?

In Flex 4, component properties for different states can be specified through <propertyName.stateName>. As an example, for creating a panel which has a height of 200 in the login state (State1) and a height of 400 in the register state, the code would be:

<s:Panel height.state1=”200″ height.register=”400″/>

If you don’t specify a state name after the property name then that becomes the default value of the property in all states that have no explicit value specified for them.

<s:Panel height.state1=”200″ height =”400″/>

In the above code, the panel will have a height of 400 in all states but State1.

In my opinion, Flex 4 provides a much cleaner approach to creating states and is the clear SDK choice for developers starting with States. You may also want to learn about transitions between states for Flex 3 and Flex 4.

It’s coming!

Creating view states: Flex 3

Introduction

This is a post to get you started with States in Flex. The post is part of a series: Flex 3 and Flex 4. It contains two primary sections:

  • What are states? – This section introduces states. If you know what they are, skip this section.
  • Creating view states in FLEX 3 – This section will describe in detail how you can create and implement states in Flex 3.

Reader Focus: Flex 3 beginners.

What are states?

In general, a state is understood as a situation or a condition of an object.

In Flex, a state is one view of the Application (other components can also have states but in this post I will discuss Application states).

Consider for example an application which lets you choose from many phones to select one for yourself. Such an application can have two states for the phone display. One state displays minimal details about the phone. If the user is interested in the phone he can click on the display to go another display state containing more details.

Creating view states in Flex 3

Open Flex builder and create a new project by going to File -> New -> Flex project. In the window that follows give an appropriate name to the project. I called it LoginProject. Click ‘Finish’ to complete project creation.

In Flex Builder, you can create states in both code view and design view. This post will talk about both. Let’s first see how to create states in design view

Creating states in design view:

Go to Flex Builder design view by clicking on the design tab on top left of your code editor.

Now, find the components window near the bottom left of the screen and locate the Panel container in the layout subsection. Drag and drop it over the application.

Next, find the TextInput, Label and Button controls and drag and drop them inside the panel to create login-like view as shown in the image.

Modify the Label control’s text properties to ‘Username’ and ‘Password’ from the Flex Properties panel on the left hand side as shown in the image above. Also, change the Label property of the Buttons to ‘Register’ and ‘Submit’ respectively.

This is one state of your application. You will see it in the states window. It is called the <base state>. You will also see ‘start’ written next to the state name in parentheses. This means that this is the view, application will display when you run it.

If you can’t see the states window, you can open it by going to the menu bar and choosing window > states

You are creating a very basic login application which should contain 3 states:

  • Login state
  • Register state
  • Display state (if user is able to successfully login – I will not discuss creating this state in this post)

You already have your Login state (base state). You will now create the ‘register’ state.

To create a new state, right click on <base state> in the states window >New

You will see the following window:

Here you can choose which state to base this new state on. Any new state will, by default contain all components that its parent state (state it is based on) contains. Any subsequent changes in the base state will also be reflected in the new state. Developers using Flex 4 will notice a change here. To know more about that read Creating view states in Flex 4

You can also choose to set this state as the start state of the application by clicking on ‘Set as start state’ checkbox.

Name the new state ‘register’ (you can name it anything, ‘register’ is the name I used) and base it on the base state of the application. When you click Ok, the register state is added to the states window.

Try switching between the states in the ‘states’ window. You will see that the new state is the exact duplicate of its parent state. You need to now change the display of the new state to look like that in the image below.

You need to change a few properties and add some new controls to create a display like above.

This done, click on the <base state> state in the states window to switch to the base state. You will see that the login state display is intact and none of the changes made in the derived state will be seen in the parent state. If you change something in the parent state however, like add another control to its display, the control will appear in the child state.

Switching between states:

To switch between states you need to change the value of the currentState global variable. This variable contains the name of the current state of the Application.

So in Flex Builder design view, go to the login state (base state of the application) and select the ‘register’ button. In the properties panel locate ‘On click’ and in the corresponding text box type: currentState=’register’ as shown in the image below.

This means that when you run the application and click on this button the currentState of the application should become ‘register’

Now switch to the register state in the states window of Flex Builder and select the ‘register’ button. In the properties panel, you will see the On click property for this button has also been changed to “currenState=’register’ ”. This is expected as changes to the parent state will be reflected in the child state. However, you want the state of the application to change back to the login state when the ‘register’ button of the register state is clicked.

To do this, modify the ‘On click’ porperty to “ currenState= ‘ ’ ”. Assigning an empty string to the currentState variable changes the application state to <base state>.

Run the application by pressing <CTRL+F11>.

You will see that you can switch between the login and register states by clicking on the ‘register’ buttons.

Creating view states in source view:

Now that you have created an application with two states in the design view, let’s see how to do the same in source view. Go back to the source view in Flex builder by clicking on the ‘source’ tab on the top left of the design editor. You will see that code has been generated for your actions in the design view.

<mx:states>
<mx:State name=”register”>
<mx:RemoveChild target=”{button1}”/>
<mx:AddChild relativeTo=”{panel1}” position=”lastChild”>
<mx:SetProperty target=”{panel1}” name=”height” value=”410″/>


</mx:State>
</mx:states>

Any new state in Flex will be added to the states array. As you can see in the code snippet above, when we create a new state in the design view, a <mx:states> tag is created. This is an array of all new states (it does not include the base state) of the application. To create a new state inside the <mx:states> tag, start a <mx:State> tag as can be seen in the code snippet. Every state has a basedOn property which is the name of the parent state of this state. If it is not specified for a state it will have the base state as its parent.

The state that you have thus created is a duplicate of its parent state. You will now learn how to change the new state. Following are the changes that you would generally make in a state and how you implement them:

Add a component:

To do this, add a <mx:AddChild> mxml tag inside the State tag. The new component will become the child of the <mx:Addchild> tag. As an example to add a new TextInput to a panel (id=’panel1’) inside the state ‘register’ the code would be:

<mx:State name=”register”>

<mx:AddChild relativeTo=”{panel1}” position=”lastChild”>

<mx:TextInput x=”122″ y=”33″ width=”143″/>

</mx:AddChild>

</mx:State>

The relativeTo property specifies a preexisting component used as the reference point for adding the new component. If this property is not specified the parent of the view state becomes the relativeTo value. The position property specifies how the new component is placed with respect to the component in the relativeTo property. It (position) can have the following values:

  • before – The new component is placed before the relativeTo component.
  • after  – New component is placed after the relativeTo component
  • firstChild – New component becomes the first Child of the relativeTo component
  • lastChild – New component becomes the last child of the relativeTo component

Remove a component:

To do remove a component in a state use <mx:RemoveChild>. As an example, to remove a button (id=’button1’) from the state ‘register’, the code should be:

<mx:State name=”register”>
<mx:RemoveChild target=”{button3}”/>
</mx:State>

Change or set a component property

To do this, add a <mx:SetProperty> tag as a child of the State tag. As an example, to change the ‘height’ property of a panel (id=’panel1’) in the register state to the ‘value’ ‘410’, the code would be:

<mx:State name=”register”>
<mx:SetProperty target=”{panel1}” name=”height” value=”410″/>
</mx:State>

Change or set event handler

You can also use the <mx:SetEventHandler> mxml tag to set a new event handler for some event. While doing this, specify the target as the component on which event would be dispatched, the name as the event type and as the handler specify the name of the new event handler method. As an example, to add an event handler for a button (id=’button2’) in the ‘register’ state for the click event type, the code would be:

<mx:State name=”register”>
<mx:SetEventHandler target=”{button2}” name=”click” handler=”newFunc()”/>
</mx:State>

So this is how you create view states in Flex 3. If you think this is easy, you should read how easy it is for Flex 4.

Flex 3 and Flex 4

Well, Hello Flexters!

This is an introduction post to a series of Blog posts I will be releasing during the next few weeks.

These posts will talk about how to get things rolling in both Flex 3 and 4. I have tried to take a ‘topic’ based approach having tried to list out the set of ‘things’ I did in Flex before I started thinking of myself as a ‘Flex user’ and no longer a beginner. Then when I started with Flex 4, I went through the same process, learning about and repeating similar tasks.

In course of this series, I will provide a step-by-step on how you can do such a task ‘xyz’ in Flex 3 (Using Flex Builder 3). The very next post will tell you how to the same ‘xyz’ in Flex 4 (On Flash Builder). In this second post on Flex 4, I will also highlight (in marked passages that you can skip over) the difference in executing ‘xyz’ in Flex 4 as compared to Flex 3. So there will be two posts on every topic (Will release sample posts by end of week).

Bear in mind these are independent posts and can be read separately or together. I have divided the readers in the following 4 broad groups:

Flex 3 Beginners:

Developers entering the world of Flex, who have started working with Flex 3 or are soon to start working on it. They can read the Flex 3 post to learn how to do job ‘xyz’ in Flex 3. They can also choose to check out the corresponding Flex 4 post to know how this has been made easier/better in Flex 4.

Flex 4 beginners, haven’t worked with Flex 3:

Developers who are starting with Flex 4 but have no prior experience of working with Flex 3 or any of the earlier versions. They can read the Flex 4 posts on how to get job ‘xyz’ done in Flex 4. As I have mentioned earlier, there will be sections in the post specifying the differences between Flex 3 and Flex 4(these sections will be highlighted in a different color). They can skip over these sections.

Developers transitioning to Flex 4:

Engineers who have been working with Flex 3 and are now switching to Flex 4 or those who still work with Flex 3 but are interested in knowing how Flex 4 is different from Flex 3.They can read through the second post on Flex 4 (Flex 3 post optional) and go through the differences sections to understand while learning Flex 4, how things have changed in this version.

Developers working with Flex 4:

Flex developers working on Flex 4 but are curious to know how it is different/better from Flex 3.

These posts don’t have much for the advanced Flex developers, most of the topics being introductory.
With this in mind, here is the list of topics I plan to write on:

Retrieving data through HTTPService: Flex 3

Retrieving data through HTTPService Flex 4

Data binding: Flex 3

Data binding: Flex 4

Creating view states: Flex 3

Creating views states: Flex 4

Transitions between states: Flex 3

Transitions between states: Flex 4

Styling through CSS: Flex 3

Styling through CSS: Flex 4

Animations and Effects: Flex 3

Animations and Effects: Flex 4

Components – Controls and Containers: Flex 3

Components – Controls and Containers: Flex 4

Creating Custom components: Flex 3

Creating Custom components: Flex 4

Event Handling and propagation: Flex 3

Event Handling and propagation: Flex 4

Passing data through an event object – Custom events: Flex 3

Passing data through an event object – Custom events: Flex 4

Skinning your components: Flex 3

Skinning your components: Flex 4

Using Graphics to draw: Flex 3

Using Graphics to draw: Flex 4

Creating item renderers and item editors: Flex 3

Creating item renderers and item editors: Flex 4

Implementing skin parts: Flex 4

Displaying data using the DataGroup container: Flex 4

This is not an ordered list as I have tried to keep the posts independent of each other. So the posts may not come in the order in which they are listed. Few posts may require knowledge/overview of a previous post in which case, I will mention it.

The titles in this list will become links to the posts as I keep adding to the stack of articles. I plan to submit 2 articles every week. So every week I cover one topic, releasing one Flex 3 and one Flex 4 post for it.

I may add to the list of the topics on feedback. The two final topics in the list (“Implementing skin parts” and “Displaying data using the DataGroup container”) are Flex 4 specific and have no Flex 3 counterpart.

The first 2 posts will be on “Creating View States” in Flex 3 and 4. Coming out by end of week.

Adobe CS5 on twitter

I searched for #CS5 on twitter and was amazed at the amount of content I saw. Thought I should share some of it:

pablokorona Adobe CS5 looks like an update that may rattle the FCP foundation of many, myself included. After effects update looks massive

SHAYNEWILLIAMS RT @techradar: RT @ComputerArts: It’s CS5 Monday! You want to know the 40 top things in CS5? Here you go: http://bit.ly/40cs5

OneScholar Photography judging panels will face greater headaches with the release of Photoshop CS5: http://fwd4.me/L9g

siddharthlele The Adobe CS5 is here. And Dreamweaver CS5 rocks!! http://www.adobe.com/products/dreamweaver/

flashmagazine Flash Professional CS5 Review: http://www.flashmagazine.com/reviews/detail/flash_cs5_review/

ericjordan: Computer Arts has a good breakdown of the 40 new features in the CS5 Suite. http://trunc.it/7314k

stewy6 RT @Gartenberg: Some of the features in CS5 border on the magical. Or witchcraft. Not sure which. #amazing

zarathevegan I’ll be watching the CS5 release in a couple of hours. Soooooooooooo excited!

fuseltd_chris Can’t wait for the CS5 trial to be released. Rotoscoping, colour correction, and compositing never looked this good.. http://bit.ly/949Vz9

supervee Adobe CS5 Brings Sexy Back http://www.webdesignerdepot.com/2010/04/adobe-creative-suite-5-brings-sexy-back/

marimoart Top 5 Photoshop CS5 Features http://youtu.be/imEZ4Y9eTRk

macbebekin Can’t wait to get my hands on Adobe CS5. Among other things: Puppet Warp! Although I’ll probably never need or use the tool.

cpoette RT @flashmagazine: Flash Professional CS5 Review: http://www.flashmagazine.com/reviews/detail/flash_cs5_review/

Mandypops reallly want CS5! Photoshop CS5 looks good 🙂

Joseph_Sa Cant wait to put my hands on the new Photoshop CS5 .. (excited)

Eugene_G RT @thomashawk: New Adobe Photoshop CS5 ROCKS! http://goo.gl/OVfl

SarbenPhotos Today is better than Christmas for some people and they don’t even realize it yet. Now we can tell people alllll about Photoshop #CS5 :):)

Portrait2a_normal huseyinthebrain Photoshop CS5 is bananas – http://links.assetize.com/links/de6435
hebiflux RT @dotmick: Flash Professional CS5 Review > http://tinyurl.com/yyhd2kp #cs5

Tweets just kept pouring in and it was surprising that CS5 was not trending. One link which kept popping up was:

http://www.computerarts.co.uk/in_depth/features/40_new_features_in_cs5

Other links I saw:

http://www.flashmagazine.com/reviews/detail/flash_cs5_review/

http://thomashawk.com/2010/04/adobe-photoshop-cs5-boldly-empowers-the-digital-artist.html

http://links.assetize.com/links/de6435

http://tinyurl.com/yyhd2kp

Trending or no trending CS5 is going to be big.

Phoebe: Not just Big. This is huge. This is bigger than huge. This is like, all right, what’s bigger than huge?

JOEY: Um, this?

Presentations and source Zips from DevSummit

Had an incredible time in Chennai talking about Flash Builder Data Centric features. I talked about how to connect to Java and PHP backend from a Flex Client. Flex UI was created in an earlier session by Shyam P. Loved the crowd; event received over 600 people, containing a good mix of students and professional developers.They were interactive and enthusiastic till the end. Would like to do more events in Chennai 🙂
A apologize to friends whom I promised to meet in Hyderabad. Had to skip the trip due to health reasons.

Presentation
Here is my presentation for the summit.

Set up instructions
To know the set-up instructions for the learn by doing session read:
http://flashahead.adobe.com/events/devsummit2009/lbd/lbd_setup_instructions.pdf

You can keep visiting this site for updates about future events.

We also have a twitter account forFlashahead (@FlashAhead). You can follow it to receive updates, announcements and other fun stuff on Adobe Flash Platform.

Catalyst Demo

Here is UI source generated by Flash Catalyst in the first session.

Instructions on How-To-Connect

Click here to read the instructions on how to connect to Java and PHP backend from the User Interface generated above.

DCD demo

The source of the final funtioning project can be downloaded from here. For creating it, I imported the FXP created through Catalyst into Flash Builder,where I used the DCD features of Flash Builder to connect to the Java and PHP backends. Please feel free to contact me  if you have issues with any of the above stuff.

Speaking at Adobe Devsummit Chennai and Hyderabad

After an amazing event in Bangalore, Adobe DevSummit is now coming to Chennai and Hyderabad. To register or to know about the venues and dates click here.  I would strongly urge any new Flex developers to attend the talks on Adobe Flash Catalyst and Data centric development.

I will be taking the tutorial session on how to connect to the backend (Learn by doing – Part 2: Integrate with server) together with fellow  technical evangelist, Sujit. This session talks about how to access data from a database through Flash builder. It will cover in detail how to connect to multiple backends from flex. Any developer thinking of starting with flex are encouraged to attend the tutorial sessions.

Hoping to see you there….

PS: All Platinum delegates will get Flex Builder 3 Professional Licence for free !!

Exposing Java project as Web Service to Flash Builder 4 using Data Centric Development (DCD)

The definition of a Web Service as given by W3C is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP-messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standard.

Web services are often used to provide an Application programming interface to clients systems which use the Server methods running on a remote system.

In this post I will talk about how to expose a java service as a web service. For accessing this service(or any other web service),  user requires a WSDL descriptor file. WSDL stands for Web Services Description Language. How to generate this WSDL will also be explained in this post.

I split this post in the following sections:
•    Creating database and Backend
•    Generating the WSDL
•    Connect to service using DCD in Flash Builder
•    Displaying data fetched by the service

Creating database and Backend

I will not go into the details of how to create the backend.
I am assuming user has a working Java project which can produce the data required by the client. In my opinion the implementation should be hidden to expose only an interface to the required methods. In any case, the user will have a class or an interface file containing declarations of needed methods. I will call this file BackendService.

Generating the WSDL

There are multilple tools available for generating the the WSDL. I have used Apache’s XFIRE. An upgrade of this tool with the name CFX is also available now. I would recommend using the older XFIRE for its simplicity. It can be downloaded from here .
User also needs to have a J2EE web server up and running. I recommend Tomcat but any other server will also do. On your server go to the directory where you would deploy your web applications(Web-apps) and create a directory with the name of your project. Here create another directory with the name WEB-INF. Open WEB-INF and now create the following subdirectories and files inside WEB-INF:

Classes

This directory should contain all the compiled Java classes with their package structure intact.  Also create a subdirectory with the name META-INF. Inside META-INF create another subdirectory with the name “xfire”. Create a new file “services.xml” in “xfire”.
Paste this xml code in Services.xml:
xml1
Change the name of the service to the name of your own service. Accordingly change the serviceClass tag to contain the path of the class from the “classes” directory. The namespace tag should contain your desired namespace.

LIB

In this directory copy all the libraries required by xfire. You can get the list of dependencies and their download links from here. Before downloading any check the libraries that you got from the Xfire download. Most of the dependencies will already be there.

web.xml

Now that you have created and populated the directories, create a new file in the WEB-INF directory with the name web.xml. In this file copy the following content:xml2

Now check out this URL:

http://localhost:8400/ProjectName/services/dataService?wsdl

In the above URL replace “ProjectName” with your actual project name. Replace dataService with the name of your dataService. Change the port if required and try accessing it from a browser.

You should now be able to view the generated WSDL . I will call this URL WSDL-URL. The next step is to access it from Flash builder.

Connect to service using DCD in Flash Builder

Open Flash builder and create a new project by going to file -> New -> Flex project. In the window that follows give an appropriate name to the project. I called it InvokeWSProject. Click Next->Finish to complete project completion.

1

Next step is to connect to the Java service. For this, Click on the Data/Services tab in the bottom frame of the screen.

2

In the screen that follows select Web service and click on next.

3

Enter WSDL-URL. Flash builder populates the Service details.

4

Click on next to see a screen like this. Here select the functions you want to import. All functions are selected by default.

5

When you click finish, you see all functions that you wished to import are now available to you in the Data/Services tab.

6

What remains now is to get the data fetched by the dataService and display them.

Displaying data fetched by the service

Go to Flash builder Design view. Drag and Drop a DataGrid from Flex component controls.

7

Your data will be shown in this grid. All that remains is to put the data in the grid. You already have the data methods in the Data/Services tab. Select the method whose output you want to see in the grid. Just drag and drop this method on the grid.

8

You see that the grid changes to the return value of the method. In my case it looked like this

9

Only thing remaining is to run the project. Press CTRL+F11 to run it.

10

Reviewing once …

User creates the database, populates it, writes a data service (dataService) to fetch the data. This completes the backend work. User exposes the service as a WSDL descriptor. User creates a flex project and links to the WSDL descriptor to get access to his functions on Client.

PS: User has not written a line of code on the Frontend J

QandA

User: Where can I get to know more about WSDL’s and web services?

Editor: http://en.wikipedia.org/wiki/Web_Services_Description_Language http://en.wikipedia.org/wiki/Web_service

User: I am using Eclipse IDE to code in Java. Is there some way I can generate my WSDL directly?

Editor: The Latest Eclipse build which can be downloaded from here has a feature of generating the WSDL. But the generated WSDL is just a prototype and needs work. Check out eclipse documentation to find out more. You can also download and install the axis plugin for eclipse. This tool directly converts Java to WSDL. Download the plugin from here. For installation instructions read this.

User: Flash Builder beta 2 was recently launched. Where can I download it?

Editor: To download Flash Builder 4 beta2  go here.

User: Any way I can know more about this product and its new features?

Editor:  Tim Buntel has a written an excellent article on what is new in this Beta. Here is the link: http://www.adobe.com/devnet/flex/articles/flashbuilder4_whatsnew.html

An aggregated list of articles on Flash Builder 4 was created by Sujit Reddy. Here is the link: http://sujitreddyg.wordpress.com/flash-builder-4/

How to use Flash Builder 4 DB introspector with PHP

How to use Flash Builder 4 DB introspector with PHP

Content
The second beta of Flash builder 4 is now available on Adobe labs. This new beta comes with the original goodness of the earlier versions and addition of many requested features. To see what’s new with this beta click here. Release notes can be viewed at http://labs.adobe.com/wiki/index.php/Flash_Builder_4:Release_Notes One of the many features introduced in this beta is the Database introspector. It can be a drag sometimes to write basic read and update methods and classes for each and every table in a database. This is where the Database introspector of Flash builder 4 will become very handy. A developer can use this feature to generate a sample code in PHP or ColdFusion for basic CRUD operations simply by pointing to the database from Flash builder project. This post contains details for generating PHP code. Here is a step by step for how to invoke the database introspector

Create the database and tables

I am using the following commands in mysql to create two tables, User, User_profile in the database “testdb”.

DROP TABLE IF EXISTS `testdb`.`user`;
CREATE TABLE `testdb`.`user` (
`ID` int(10) unsigned NOT NULL auto_increment,
`FIRST_NAME` varchar(100) default NULL,
`LAST_NAME` varchar(100) default NULL,
`DISPLAY_NAME` varchar(250) default NULL,
`COMPANY_ID` varchar(100) default NULL,
`LOGIN_ID` varchar(250) NOT NULL default '',
`LOGIN_PASSWORD` varchar(45) NOT NULL default '',
`DEPARTMENT` varchar(100) default NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;


DROP TABLE IF EXISTS `testdb`.`user_profile`;
CREATE TABLE `testdb`.`user_profile` (
`ID` int(10) unsigned NOT NULL auto_increment,
`USER_ID` int(10) unsigned NOT NULL default '0',
`BLOG_URL` varchar(300) default NULL,
`DESCRIPTION` varchar(300) default NULL,
`TWITTER_URL` varchar(300) default NULL,
PRIMARY KEY (`ID`),
CONSTRAINT `FK_COURSE_USAGE_USER` FOREIGN KEY (`USER_ID`) REFERENCES `user` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8;

Execute these commands in Mysql and you will have your tables. The next step obviously is to create client code. You start by creating a flex project.

Create the flex project

Start Flash builder 4. Go to File menu select New and then select Flex Project. A window appears with options to fill up the project details. 1

  • Give an appropriate name to the project (here I gave it the name testIntrospector)
  • Change the application server type to PHP.
  • Let other options keep their default value

2

Click on next and you see options to fill in the server details.

  • Web root: Specify the root folder of your web server (in my case it was C:\Program Files\Apache Software Foundation\Apache2.2\htdocs)
  • Next specify the root URL as appropriate (I entered -> http://localhost:8080)
  • Now click on validate configuration. In case there is an error in accessing the data server, it will be shown. Otherwise Flash builder tells you that the root folder and URL are valid.

The output folder can be changed according to your need. I am kept the default value 3 Click on next -> finish to be done with the project completion. What next? Now you need a PHP service that can read and edit the database

Generate the Service

Click on the Data/Services tab in the bottom frame. 4 This tab shows a link which says “Connect to Data/Service”. Click on this link to see this window 5 Here select PHP as your service type and click on next. The same can be done by going to Data in the tool bar and selecting Connect to PHP. You will be taken to a window where you need to fill in details about the service. The next step is to generate the PHP Code based on our Database Table. 6

Generating PHP Code based on a Database Table

Here is how you do that. Click on the link which says “click here to generate a sample”. 7 It opens a window where you can enter details about the database you want to connect to. You would be required to enter the following details about the database:

  • Username – Enter the username having all privileges over the table you want to generate the service for (I entered root)
  • Password – Enter the password for that user.
  • Host name and port– Give the name of the host where the database is and the port on which it can be accessed(localhost,3306 in my case)
  • Finally enter the name of the database

Click on the “Connect to Database” button. If all details have been correctly entered all tables from the entered database will be now visible in Table comboBox like this.. 8

Select the table (I select the User table from our database testdb ) for which you require the CRUD methods and click on OK. You can also select the location where this sample PHP service is created. I have used the default location. Once you click OK Flash builder might show you a warning that the service generated is intended for a trusted environment. The code generated will allow anyone with network access to your server to be able to select, insert, update or delete information from this table. The code should be reviewed before it’s used for production purposes. If you go ahead and press Ok and finish with the default values of the Service name and Service package, the introspector generates a Sample PHP and opens it for you to view and edit. Here is a code snippet of what was generated for me for the table testdb.User


public function getAllUser()
{
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->ID, $row->FIRST_NAME, $row->LAST_NAME, $row->DISPLAY_NAME, $row->COMPANY_ID, $row->LOGIN_ID, $row->LOGIN_PASSWORD, $row->DEPARTMENT);
while (mysqli_stmt_fetch($stmt))
{
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->ID, $row->FIRST_NAME, $row->LAST_NAME, $row->DISPLAY_NAME, $row->COMPANY_ID, $row->LOGIN_ID, $row->LOGIN_PASSWORD, $row->DEPARTMENT);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $rows;
}

This method gets all users present in the user table. Now that you have your service to get you data from the database, you just need to display it. Go to Flash builder design view and drag and drop a DataGrid on the application. This done you have to decide what to display in this grid. In this case let us say you want this grid to display all users. To get the DataGrid to show all users drag and drop the above method getAllUser from the Data/Services tab on the DataGrid 9 When you drop the method on the grid it the grid adapts to the return value of the function and looks something like this now.10 If you now run the project with data in the database, this is what you see.11 You have created an application which reads from a Mysql database through a PHP service and displays the data on a Flex DataGrid and you have not written one line of code. Feels like magic? It is 🙂 More on Flash Builder 4 can be seen at http://sujitreddyg.wordpress.com/flash-builder-4/