Flex and ColdFusion Services
Join the DZone community and get the full member experience.
Join For FreeIf you were asked to create a cutting edge, feature-rich, easy-to-use website, what technology would you use to create it? If you said "Flex," then you are off to a good start. Not only does Flex offer a rapid development environment and come packaged with many of the UI components that you need for any application, but it also offers ways to communicate with outside resources. Why does communicating with outside resources matter? It matters because the one thing that Flex does not offer is any kind of server-side technology. This is because Flex was solely created and intended for the creation of client-side applications. So though your Flex application can have the ability to process and manipulate data, that is pretty much where its data functionality ends. Flex on its own has no way to communicate with a mail server, create documents, or even write data to the server’s file system (AIR does have this ability but only for the user’s machine and not for a centralized server that everyone can access). If there were no way for Flex to communicate with a server-side technology that could offer this functionality, then it would not be possible to create the awe-inspiring applications that we have on the internet today.
So the question is: what should you do with the data that your newly created Flex application has gathered? Using the RemoteObject, httpservice, or webservice tags, you can communicate with a server-side scripting language such as .NET, PHP, or Java, sending data via post commands or Soap calls and receiving data via Soap responses or XML. This is all well and good, but how would the server-side script be created? Even though your manager thinks that because you know ActionScript you know all the other languages, that might not actually be the case. What if you don’t know these other languages? Should you try and learn them or hire a freelancer, just so you can have your application send out emails? Well, with the introduction of ColdFusion 9, you will no longer need to worry about that problem anymore.
With the recent release of ColdFusion 9, Flex, as well as other 3rd party technologies, now has direct access to some of the core services that ColdFusion uses. Since Adobe purchased Macromedia in 2005, ColdFusion has been using the same image and PDF technologies that originally put Adobe on the map. With access to these services, developers who do not know how to write a line of ColdFusion will still be able to create high quality images and PDFs. The introduction of ColdFusion as a Service (CFAAS) allows 3rd party technologies access to the following ColdFusion proxy ActionScript Classes:
- Config (Configures the application for using ColdFusion Services)
- Util
(Includes file upload support)
- Chart (Charting functionality)
- Document (PDF Creation)
- Image (Image Creation and Manipulation)
- Mail (Email Creation and Sending)
- PDF (PDF manipulation)
- POP (Email Retrieval through POP3 Mail Server)
Installing ColdFusion 9
The first thing you need to do to install ColdFusion 9 is download a copy from the Adobe Labs website.
Once the download is completed, follow the on-screen prompts.
Most of the screens are self explanatory, but let’s just review a couple that could trip you up.
When
you get to the “Install Type Step" (figure 1), you are asked to either
provide a serial number or choose a 30-day trial or developer edition.
Select the developer edition. The developer edition will install a
fully functional copy of ColdFusion that can only be accessed locally.
The “Installer Configuration Step” (figure 2) is where you can choose how ColdFusion will be installed on your machine. For now choose the default server configuration option. All examples below will be assuming that this was your configuration choice.
ColdFusion comes pre-packaged with a built-in web server. If you have apache or IIS installed on your machine you will be able to choose to run ColdFusion through these during the “Configure Web Servers Step” (figure 3), but for simplicity’s sake, select the built-in web server option.
Once
all the steps have been completed, ColdFusion 9 will be installed on
your computer. If you selected all the default settings during the
installation process, you will have the following server information:
Web Root: C:\ColdFusion9\www root OR /applications/ColdFusion9/wwwroot/
Server Root: http://localhost:8500/ OR http://127.0.0.1:8500
ColdFusion Administrator: {server root}/cfide/administrator/
For
those of you who want to experiment with ColdFusion 9 but do not wish
to install the server on your local machine, you can get free
ColdFusion 9 hosting from a number of ColdFusion hosting companies.
As
we don’t want everybody to be able to access the services on your
machine, it is necessary to create a user account to access the
services.
In the ColdFusion Administrator go to the “User
Manager” page under the “Security” section. Click “add user” and
provide a username and password. Remember the details, as you will
need them later. Whenever you see “Your Username” or “Your Password”
in the code examples, put this information in. Before clicking “add
user,” go to the “Exposed Services” section and move all the services
from “Prohibited Services” to “Allowed Services.” Don’t worry, things
are still secure, because the services are also restricted by IP
address. Click on “add user” to finally add the user.
Now that
the user is added, you need to click on “Allowed IP Addresses,” which
is also under the “Security” section. In the IP address box add the IP
127.0.0.1. If you do not have ColdFusion installed on your machine,
you will need to add your external IP address. You are now ready to use
CFAAS.
Setting Up Your Project
To utilize CFAAS
the only thing that you will need to do differently when creating your
project is to add the cfservices.swc file. The cfservices.swc file is
located at {server root}/CFIDE/scripts/AIR/cfservices.swc. Even though
you will be communicating with ColdFusion, you do not need to select
ColdFusion in the "Server Technology" area of the "New Project Wizard."
Once
your project has been created, you will need to add a ColdFusion
namespace. To create the namespace, add the following to your
application tag at the top of the main file:
xmlns:cf="coldfusion.service.mxml.*". Note: Everything that is covered
in this article also applies if you are creating an AIR Application.
If you are using CFAAS within an AIR Application remember, remember
that in order to use the services, the user must have access to the
ColdFusion server, so always check that an internet connection exists
before making the call.
You now have everything set up so that
you can start accessing ColdFusion 9. The first thing to do is to
specify how the ColdFusion server should be contacted by using a
<cf:Config> tag. All the information that you supply in the
config tag can be overwritten in the individual tags that we are going
to use. However, if you are going to use multiple ColdFusion service
tags, it is easier to specify all the information in one central
location.
The config tag has the following available attributes:
- serviceUsername (The username specified in the "add user" step above)
- servicePassword (The password specified in he "add user" step above)
- cfServer (The server name or IP address of the CF Server; use 127.0.0.1 for this example.)
- cfPort (Port on which the CF Server is running; use 8500 for this example.)
- cfContectRoot (Used with j2EE installs; it can be ignored for this example.)
- secureHTTP (Boolean value specifying whether to use http or https)
- destination (The destination attribute can be used to specify a user defined remoting destination in WEB-INF/flex/remoting- config.xml. If not specified, default ColdFusion destination is used.)
Here is an example of what the tag might look like:
<cf:Config id="conf" cfServer="127.0.0.1" cfPort="8500"
serviceUserName="Your Username" servicePassword="Your Password" />
With this tag created and placed inside your application, you can move onto the more enjoyable task of adding functionality to your application. So let’s start out by creating something.
Creating PDFs
Being
able to create a PDF dynamically is a great feature for any site, no
matter what language it is developed in. Having the ability to export
data to a PDF or provide customer receipts in a PDF format is a great
selling point for any application, and it will let you shine above your
competition. Writing to anything other than a text file has often been
daunting to many, but since Adobe is the creator of the PDF format,
they have made it nice and simple for Adobe products, such as
ColdFusion, to create PDFs. Using CFAAS you not only have the ability
to create PDFs through the document class, but you also have the
ability to update and modify PDFs with the PDF class.
Let’s take a look at an example.
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
[Bindable]
public var chaSer:Array;
public var chaDat:Array;
[Bindable]
public var pdfContent:String;
private function renderPDF():void {
pdfContent = sourceText.htmlText;
doctest.execute();
}
private function handleResult(event:ResultEvent):void {
Alert.show(event.result.toString());
}
]]>
</mx:Script>
<cf:Config id="configid" cfServer="localhost"
cfPort="8500" servicePassword="your password"
serviceUserName="your username" />
<cf:Document
id="doctest"
action="generate"
format="pdf"
content="{pdfContent}"
result="handleResult(event)" />
<mx:RichTextEditor title="Your Content" id="sourceText" width="400" height="400" />
<mx:Button label="Render PDF" click="renderPDF()" />
In
this example you will see that we have a config tag and a document
tag. The config tag specifies the information about the ColdFusion
service, as discussed above, and the document tag specifies some of the
information about the document that will be created. The tag states
that we wish to generate a document and that it should be of PDF
format. With these 2 tags alone nothing will happen. For the PDF to
be generated the execute() method must be called on the document tag
(doctest). Upon execution, the information is sent to ColdFusion via
CFAAS.
Below the document tag we have a Rich Text Editor and a
button that calls the renderPDF() function. When creating a PDF, any
HTML supplied will be rendered when creating the document. Any
formatting, such as bolding or underlining, which is done within the
Rich Text Area will translate to the generated PDF.
The
renderPDF() function that is called when the button is clicked does 2
things. It takes the HTML content from the rich text editor and sets
it to the Bindable pdfContent variable, and it also calls the execute()
method on the document tag. When this execute() method is called, all
the data is sent to ColdFusion via CFAAS.
When the PDF has been
generated, the resultEvent will be fired and caught by the
handleResult() function, which was supplied in the Document tag. In
the result there is a URL for the generated PDF. No actual files are
returned with the operation; only the URL of the PDF that is located on
the server is returned. It is then up to you to do with the URL as you
see fit.
It’s pretty easy, right? Now let’s dip our feet into something a little more complicated.
Creating Charts
Being
able to display data in an easy to read way, such as a chart, is a
great way to get your point across to users. If you have a chart, you
don’t need to sit in endless meetings, attempting to glean meaningful
data from pages and pages of information. Instead, you can learn
everything you need to know by looking at some pretty pictures.
From
the example above we have seen how the CFAAS classes work. You create
your config object and your service object (Document in the case of the
example above), and then you execute the service object. Creating a
graph is no different. Take a look at this example:
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
[Bindable]
public var chaSeries:Array;
public var chaData:Array;
function init():void
{
chaData =
[{item:"Facilities",value:"35000"}, {item:"Facilities1",value:"32000"}];
chaSeries = [{type:"bar",chartdata:chaData}];
chartest.execute();
}
function handleResult(event:ResultEvent):void
chartImg.source = event.result.toString();
}
]]>
</mx:Script>
<cf:Config id="configid" cfServer="localhost"
cfPort="8500" servicePassword="your password"
serviceUserName="your username" />
<cf:Chart id="chartest"
action="generate"
format="Flash"
xAxisTitle="Department"
yAxisTitle="Salary Average"
chartSeries="{chaSeries}"
labelFormat = "number"
font = "arial"
title = "CFAAS Integration Testing"
result="handleResult(event)"/>
<mx:Image id="chartImg" />
In
this example we use some static information to generate a chart when
the application is created. The config object provides all the
information needed to access the CFAAS. The chart object provides the
information needed for formatting the charts, such as what data,
labels, and fonts to use. The chart object also specifies what format
to create the chart in. There are 3 formats available to you: JPG, PNG
and Flash. Both JPG and PNG will give you a flat image; the Flash
format will create a SWF file that includes animation and rollover
tooltips.
The init() function, which is called when the
creationComplete event is fired, specifies what data should be used to
create the charts. The first array, chaData, specifies which data
values and labels to use. The second array, chaSeries, specifies the
type of chart to be generated, in this case bar, and what data should
be used, in this case chaData. As multiple types of charts can be
overlaid on top of each other, the variable type used is an Array. The
order of the elements in the Array dictate the layering positioning in
the chart, where the first element is at the bottom and the last
element is at the top.
Once all the data has been set, the
execute() method is called on the chart object. This then sends all
the information to ColdFusion via CFAAS. When the chart has been
generated, the handleResult() method which was specified in the chart
tag is called. Contained within the result is a URL to the SWF file
located on the server. Just like the PDF creation process, no files
are actually transferred between ColdFusion and your Flex application.
Once the URL has been received, an image object is used to display the
resulting chart. Nothing too complicated with that, right?
Sending Emails
Now
that we have delved into the world of graph and document creation,
let’s look at one of the features that nearly every application can
use, email. Having the ability to send communications from the
application is very important, and it really couldn’t be any simpler.
The
first thing that you need to do is set up ColdFusion to handle emails.
Server-side languages such as ColdFusion and PHP do not physically send
out emails. All that they do is package the data up and communicate
with a mail server and pass the information along. For that we need to
tell ColdFusion which mail server to communicate with. Unlike other
server-side scripting languages, ColdFusion lets you do a one-time set
up that allows all email communication from the server to run through
one mail server.
To set up your mail server settings you need an
SMTP server. Most of us do not readily have one, especially for
testing, so I recommend creating a free SMTP account with one of the
free providers out there such as GMX (www.gmx.com) or lavabit
(www.lavabit.com).
Once you have your SMTP server details in
front of you, log back into the ColdFusion Administrator ({server
root}/cfide/administrator/) and click on “mail” on the left hand side.
You will find it under the Server Settings section. You should see a
screen that looks something like Figure 4.
Enter the SMTP information in the first 3 boxes and hit "submit
changes." Your ColdFusion server is now set up to route all email
through that server.
Now with that all set up, let’s move back to the code.
The
<cf:Mail > tag requires only a few attributes be passed to it so
that it can send out emails. The attributes that you would most expect
(email address, subject, content, etc.) are all required fields.
Server is an additional attribute that is needed, but this information
can be pulled from the config tag that is already on the page. This
can be seen in the example below. Email sent through ColdFusion can be
of either plain text or HTML. If you wish to send an HTML email, you
must supply the type attribute and set it to HTML (the default type is
text). If you are sending an HTML email and you wish to include
images, be sure to use fully qualified URLs in the image path.
Let’s take a look at the code below:
<mx:Script>
<![CDATA[
import coldfusion.service.events.*;
import mx.controls.Alert;
public function init(){
mailtest.execute();
}
public function handleResult(event:ColdFusionServiceResultEvent):void {
Alert.show("Mail was delivered Successfully");
}
public function handleError(event:ColdFusionServiceFaultEvent):void {
Alert.show("Failure"+ event.toString());
}
]]>
</mx:Script>
<cf:Config id="configid" cfServer="localhost"
cfPort="8500" servicePassword="your password"
serviceUserName="your username" />
<cf:Mail id="mailtest"
server="{configid.cfServer}"
to="test@example.com"
subject="This is my Subject"
content="This is my content"
from="simon@simonfree.com"
result="handleResult(event)"
fault="handleError(event)"/>
As you can see from the code, the mail tag is set up to send an email from test@example.com to simon@simonfree.com with the subject line “This is my Subject” and the body of “This is my Content”. Obviously, if this were to go into production, you would pass in the to, subject, and email. When the creation complete event is fired the init() function is called which calls the execute() method on the mail tag, sending the information to the ColdFusion service. The ColdFusion service then returns either a ColdFusionServiceResultEvent if successful or a ColdFusionServiceFaultEvent if unsuccessful. That’s it. Your email is on its way.
Conclusion
So as you can see, integrating and utilizing ColdFusion 9 into your Flex applications is not daunting at all, even for those of you who have no programming experience. These examples have demonstrated a few of the options available to you, but there are a still a number of options left for you to explore. Take a look and see what is on offer, no longer feel tied down to a developer, and say good bye to those costly freelancers. From now on, you can do it all yourself!
Opinions expressed by DZone contributors are their own.
Comments